Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ Don't manually adjust formatting β€” just run `pnpm lint:fix` if needed.
- Tool names: `snake_case` (e.g., `search_catalog`)
- Tool components: PascalCase + `Tool` suffix (e.g., `SearchCatalogTool`)
- Handlers return `CallToolResult` with a `content` array β€” always (including error results with `isError: true`)
- Peer deps: React β‰₯ 18, React DOM β‰₯ 18, Zod β‰₯ 3. Only runtime dep is `zod-to-json-schema`
- Peer deps: React β‰₯ 18, React DOM β‰₯ 18, Zod `^3.25.0 || ^4.0.0` (3.25 is the floor because it ships `zod/v4/core`, including `toJSONSchema`). `zod-to-json-schema` is only for classic Zod 3 *instances* (no `_zod`); those are not Zod 4 schemas, so native `toJSONSchema` cannot walk them.
- Warnings use `warnOnce()` β€” dev-only, fires once per key to avoid console spam

## Boundaries
Expand Down
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
"peerDependencies": {
"react": ">=18.0.0",
"react-dom": ">=18.0.0",
"zod": ">=3.0.0"
"zod": "^3.25.0 || ^4.0.0"
},
"dependencies": {
"zod-to-json-schema": "^3.24.1"
Expand All @@ -80,7 +80,7 @@
"tsup": "^8.5.1",
"typescript": "^5.9.3",
"vitest": "^3.2.7",
"zod": "^3.25.76"
"zod": "^4.4.3"
},
"lint-staged": {
"*.{ts,tsx}": [
Expand Down
23 changes: 14 additions & 9 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/__tests__/smoke.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ function AvailabilityDisplay() {
return <span data-testid="smoke-available">{available ? "yes" : "no"}</span>;
}

type ToolConfig = McpToolConfigZod<z.ZodRawShape> | McpToolConfigJsonSchema;
type ToolConfig = McpToolConfigZod | McpToolConfigJsonSchema;

function SmokeToolComponent({ config }: { config: ToolConfig }) {
const { state } = useMcpTool(config as McpToolConfigJsonSchema);
Expand Down
40 changes: 39 additions & 1 deletion src/hooks/__tests__/useMcpTool.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { StrictMode } from "react";
import { renderToString } from "react-dom/server";
import { afterEach, describe, expect, it, vi } from "vitest";
import { z } from "zod";
import * as z3 from "zod/v3";
import { _resetPolyfillConsumerCount, WebMCPProvider } from "../../context";
import { cleanupPolyfill } from "../../polyfill";
import type { CallToolResult, McpToolConfigJsonSchema, McpToolConfigZod } from "../../types";
Expand Down Expand Up @@ -38,7 +39,7 @@ async function waitForRegistration() {

type ExecuteFn = ReturnType<typeof useMcpTool>["execute"];
type ResetFn = ReturnType<typeof useMcpTool>["reset"];
type ToolConfig = McpToolConfigZod<z.ZodRawShape> | McpToolConfigJsonSchema;
type ToolConfig = McpToolConfigZod | McpToolConfigJsonSchema;

// ─── Test component ──────────────────────────────────────────────

Expand Down Expand Up @@ -110,6 +111,43 @@ describe("registration lifecycle", () => {
expect(schema.required).toContain("name");
});

it("registers and validates Zod 3 schemas on both execution paths", async () => {
const executeRef = { current: null } as React.MutableRefObject<ExecuteFn | null>;

renderWithProvider(
<ToolComponent
config={{
name: "greet",
description: "Say hello",
input: z3.object({ name: z3.string().min(3) }),
handler: async ({ name }) => makeResult(`hello ${name}`),
}}
onExecuteRef={executeRef}
/>,
);

await waitForRegistration();

const tools = navigator.modelContextTesting?.listTools() ?? [];
const schema = JSON.parse(tools[0].inputSchema ?? "{}");
expect(schema.properties.name.type).toBe("string");

let directResult: CallToolResult | undefined;
await act(async () => {
directResult = await executeRef.current?.({ name: "world" });
});
expect(directResult?.content[0]).toMatchObject({ type: "text", text: "hello world" });

let externalResultJson: string | null | undefined;
await act(async () => {
externalResultJson = await navigator.modelContextTesting?.executeTool(
"greet",
JSON.stringify({ name: "x" }),
);
});
expect(JSON.parse(externalResultJson ?? "{}")).toMatchObject({ isError: true });
});

it("registers tool with JSON Schema on mount", async () => {
renderWithProvider(
<ToolComponent
Expand Down
40 changes: 21 additions & 19 deletions src/hooks/useMcpTool.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { useCallback, useContext, useEffect, useRef, useState } from "react";
import { z } from "zod";
import { MISSING_PROVIDER, WebMCPContext } from "../context";
import type {
CallToolResult,
Expand All @@ -8,8 +7,14 @@ import type {
ToolDescriptor,
ToolExecutionState,
UseMcpToolReturn,
ZodObjectSchema,
} from "../types";
import { schemaFingerprint, zodToInputSchema } from "../utils/schema";
import {
isZodObjectSchema,
parseZodInput,
schemaFingerprint,
zodToInputSchema,
} from "../utils/schema";
import { warnOnce } from "../utils/warn";

const TOOL_OWNER_BY_NAME = new Map<string, symbol>();
Expand Down Expand Up @@ -46,13 +51,13 @@ const INITIAL_STATE: ToolExecutionState = {
executionCount: 0,
};

export function useMcpTool<T extends z.ZodRawShape>(config: McpToolConfigZod<T>): UseMcpToolReturn;
export function useMcpTool<T extends ZodObjectSchema>(
config: McpToolConfigZod<T>,
): UseMcpToolReturn;

export function useMcpTool(config: McpToolConfigJsonSchema): UseMcpToolReturn;

export function useMcpTool(
config: McpToolConfigZod<z.ZodRawShape> | McpToolConfigJsonSchema,
): UseMcpToolReturn {
export function useMcpTool(config: McpToolConfigZod | McpToolConfigJsonSchema): UseMcpToolReturn {
const ctx = useContext(WebMCPContext);
if (ctx === MISSING_PROVIDER) {
warnOnce(
Expand All @@ -61,16 +66,16 @@ export function useMcpTool(
);
}

const isZodPath = "input" in config && config.input instanceof z.ZodObject;
const isZodPath = "input" in config && isZodObjectSchema(config.input);

const inputFingerprint = schemaFingerprint(
isZodPath
? (config as McpToolConfigZod<z.ZodRawShape>).input
? (config as McpToolConfigZod).input
: (config as McpToolConfigJsonSchema).inputSchema,
);
const outputFingerprint = schemaFingerprint(
isZodPath
? (config as McpToolConfigZod<z.ZodRawShape>).output
? (config as McpToolConfigZod).output
: (config as McpToolConfigJsonSchema).outputSchema,
);
const annotationsFingerprint = config.annotations ? JSON.stringify(config.annotations) : "";
Expand Down Expand Up @@ -105,12 +110,10 @@ export function useMcpTool(
try {
let validatedInput: Record<string, unknown> = input ?? {};
const currentConfig = configRef.current;
const currentIsZod = "input" in currentConfig && currentConfig.input instanceof z.ZodObject;
const currentIsZod = "input" in currentConfig && isZodObjectSchema(currentConfig.input);

if (currentIsZod) {
validatedInput = (currentConfig as McpToolConfigZod<z.ZodRawShape>).input.parse(
validatedInput,
);
validatedInput = parseZodInput((currentConfig as McpToolConfigZod).input, validatedInput);
}

const result = await handlerRef.current(validatedInput as Record<string, unknown>);
Expand Down Expand Up @@ -161,14 +164,14 @@ export function useMcpTool(
const mc = document.modelContext;
const cfg = configRef.current;
const ownerToken = Symbol(cfg.name);
const zodPath = "input" in cfg && cfg.input instanceof z.ZodObject;
const zodPath = "input" in cfg && isZodObjectSchema(cfg.input);

// Compute resolved schemas inside effect body to avoid per-render allocation
const resolvedInputSchema = zodPath
? zodToInputSchema((cfg as McpToolConfigZod<z.ZodRawShape>).input)
? zodToInputSchema((cfg as McpToolConfigZod).input)
: (cfg as McpToolConfigJsonSchema).inputSchema;

const zodOutput = zodPath ? (cfg as McpToolConfigZod<z.ZodRawShape>).output : undefined;
const zodOutput = zodPath ? (cfg as McpToolConfigZod).output : undefined;
const resolvedOutputSchema = zodPath
? zodOutput
? zodToInputSchema(zodOutput)
Expand All @@ -191,11 +194,10 @@ export function useMcpTool(
try {
let validatedArgs = args;
const currentConfig = configRef.current;
const currentIsZod =
"input" in currentConfig && currentConfig.input instanceof z.ZodObject;
const currentIsZod = "input" in currentConfig && isZodObjectSchema(currentConfig.input);

if (currentIsZod) {
validatedArgs = (currentConfig as McpToolConfigZod<z.ZodRawShape>).input.parse(args);
validatedArgs = parseZodInput((currentConfig as McpToolConfigZod).input, args);
}

const result = await handlerRef.current(validatedArgs as Record<string, unknown>);
Expand Down
21 changes: 16 additions & 5 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { ReactNode } from "react";
import type { z } from "zod";
import type * as z3 from "zod/v3";
import type * as z4 from "zod/v4/core";

export type MaybePromise<T> = T | Promise<T>;

Expand Down Expand Up @@ -87,12 +88,22 @@ interface McpToolConfigBase {
onError?: (error: Error) => void;
}

export interface McpToolConfigZod<T extends z.ZodRawShape> extends McpToolConfigBase {
input: z.ZodObject<T>;
export type ZodObjectSchema = z3.AnyZodObject | z4.$ZodObject;

/** Parsed schema output β€” same semantics as Zod's `z.infer`. */
export type ZodParsed<T extends ZodObjectSchema> = T extends z4.$ZodType
? z4.output<T>
: T extends z3.ZodTypeAny
? z3.infer<T>
: never;

export interface McpToolConfigZod<T extends ZodObjectSchema = ZodObjectSchema>
extends McpToolConfigBase {
input: T;
inputSchema?: never;
output?: z.ZodObject<z.ZodRawShape>;
output?: ZodObjectSchema;
outputSchema?: never;
handler: (args: z.infer<z.ZodObject<T>>) => MaybePromise<CallToolResult>;
handler: (args: ZodParsed<T>) => MaybePromise<CallToolResult>;
}

export interface McpToolConfigJsonSchema extends McpToolConfigBase {
Expand Down
50 changes: 49 additions & 1 deletion src/utils/__tests__/schema.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { describe, expect, it } from "vitest";
import { z } from "zod";
import * as z3 from "zod/v3";
import * as z4 from "zod/v4";
import * as zm from "zod/v4/mini";
import type { InputSchema } from "../../types";
import { schemaFingerprint, zodToInputSchema } from "../schema";

const z = z3;

// ─── zodToInputSchema ────────────────────────────────────────────

describe("zodToInputSchema", () => {
Expand Down Expand Up @@ -140,6 +144,50 @@ describe("zodToInputSchema", () => {
expect(result.properties?.work).toHaveProperty("type", "object");
expect(result.properties?.work).not.toHaveProperty("$ref");
});

it("converts Zod 4 schemas with descriptions and constraints", () => {
const schema = z4.object({
emails: z4.array(z4.email()).min(1).max(25).describe("Email addresses to invite."),
});
const result = zodToInputSchema(schema);

expect(result).toMatchObject({
type: "object",
properties: {
emails: {
type: "array",
minItems: 1,
maxItems: 25,
description: "Email addresses to invite.",
items: { type: "string", format: "email" },
},
},
required: ["emails"],
});
expect(result).not.toHaveProperty("$schema");
});

it("converts Zod 4 Mini schemas", () => {
const schema = zm.object({ name: zm.string() });
const result = zodToInputSchema(schema);

expect(result).toMatchObject({
type: "object",
properties: { name: { type: "string" } },
required: ["name"],
});
});

it("inlines shared Zod 4 sub-schemas instead of emitting $ref", () => {
const address = z4.object({ street: z4.string(), zip: z4.string() });
const schema = z4.object({ home: address, work: address });
const result = zodToInputSchema(schema);

expect(result.properties?.home).toHaveProperty("type", "object");
expect(result.properties?.work).toHaveProperty("type", "object");
expect(result.properties?.work).not.toHaveProperty("$ref");
expect(result).not.toHaveProperty("$defs");
});
});

// ─── schemaFingerprint ───────────────────────────────────────────
Expand Down
Loading