Skip to content

feat: add optional strict parameter to registerTool for Zod validation #846

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -949,6 +949,31 @@ server.registerTool("tool3", ...).disable();
// Only one 'notifications/tools/list_changed' is sent.
```

### Parameter Validation and Error Handling

Control how tools handle parameter validation errors and unexpected inputs:

```typescript
// Strict validation for development - catches typos immediately
const devTool = server.registerTool("dev-tool", {
inputSchema: { userName: z.string(), itemCount: z.number() },
strict: true // Reject { username: "test", itemcount: 42 }
}, handler);

// Lenient validation for production - handles client variations gracefully
const prodTool = server.registerTool("prod-tool", {
inputSchema: { userName: z.string().optional(), itemCount: z.number().optional() },
strict: false // Accept extra parameters (default behavior)
}, handler);
```

**When to use strict validation:**
- Development and testing: Catch parameter name typos early
- Production APIs: Ensure clients send only expected parameters
- Security-sensitive tools: Prevent injection of unexpected data

**Note:** The `strict` parameter is only available in `registerTool()`. The legacy `tool()` method uses lenient validation for backward compatibility.

### Low-Level Server

For more control, you can use the low-level Server class directly:
Expand Down
50 changes: 50 additions & 0 deletions src/server/mcp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4290,4 +4290,54 @@ describe("elicitInput()", () => {
text: "No booking made. Original date not available."
}]);
});

/**
* Test: Tool parameter validation with strict mode
* This test verifies that tools with strict: true reject unknown parameters,
* including those with incorrect capitalization.
*/
test("should reject unknown parameters when strict validation is enabled", async () => {
const mcpServer = new McpServer({
name: "test server",
version: "1.0",
});

const client = new Client({
name: "test client",
version: "1.0",
});

// Register a tool with strict validation enabled
mcpServer.registerTool(
"test-strict",
{
inputSchema: { userName: z.string().optional(), itemCount: z.number().optional() },
strict: true,
},
async ({ userName, itemCount }) => ({
content: [{ type: "text", text: `${userName || 'none'}: ${itemCount || 0}` }],
})
);

const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();

await Promise.all([
client.connect(clientTransport),
mcpServer.server.connect(serverTransport),
]);

// Call the tool with unknown parameters (incorrect capitalization)
// With strict: true, these should now be rejected
await expect(client.request(
{
method: "tools/call",
params: {
name: "test-strict",
arguments: { username: "test", itemcount: 42 }, // Unknown parameters should cause error
},
},
CallToolResultSchema,
)).rejects.toThrow("Invalid arguments");
});
});
13 changes: 10 additions & 3 deletions src/server/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -772,13 +772,18 @@ export class McpServer {
inputSchema: ZodRawShape | undefined,
outputSchema: ZodRawShape | undefined,
annotations: ToolAnnotations | undefined,
strict: boolean | undefined,
callback: ToolCallback<ZodRawShape | undefined>
): RegisteredTool {
const registeredTool: RegisteredTool = {
title,
description,
inputSchema:
inputSchema === undefined ? undefined : z.object(inputSchema),
inputSchema === undefined
? undefined
: strict === true
? z.object(inputSchema).strict()
: z.object(inputSchema),
outputSchema:
outputSchema === undefined ? undefined : z.object(outputSchema),
annotations,
Expand Down Expand Up @@ -914,7 +919,7 @@ export class McpServer {
}
const callback = rest[0] as ToolCallback<ZodRawShape | undefined>;

return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, callback)
return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, false, callback)
}

/**
Expand All @@ -928,14 +933,15 @@ export class McpServer {
inputSchema?: InputArgs;
outputSchema?: OutputArgs;
annotations?: ToolAnnotations;
strict?: boolean;
},
cb: ToolCallback<InputArgs>
): RegisteredTool {
if (this._registeredTools[name]) {
throw new Error(`Tool ${name} is already registered`);
}

const { title, description, inputSchema, outputSchema, annotations } = config;
const { title, description, inputSchema, outputSchema, annotations, strict } = config;

return this._createRegisteredTool(
name,
Expand All @@ -944,6 +950,7 @@ export class McpServer {
inputSchema,
outputSchema,
annotations,
strict,
cb as ToolCallback<ZodRawShape | undefined>
);
}
Expand Down