fix(core): make fromJsonSchema() use runtime-aware default validator … (#1825)
Co-authored-by: Felix Weinberger <3823880+felixweinberger@users.noreply.github.com>
This commit is contained in:
parent
2fd7f5ff26
commit
5f32a90f0d
9 changed files with 74 additions and 6 deletions
|
|
@ -210,7 +210,7 @@ Zod schemas, all callback return types. Note: `callTool()` and `request()` signa
|
|||
|
||||
The variadic `.tool()`, `.prompt()`, `.resource()` methods are removed. Use the `register*` methods with a config object.
|
||||
|
||||
**IMPORTANT**: v2 requires schema objects implementing [Standard Schema](https://standardschema.dev/) — raw shapes like `{ name: z.string() }` are no longer supported. Wrap with `z.object()` (Zod v4), or use ArkType's `type({...})`, or Valibot. For raw JSON Schema, wrap with `fromJsonSchema(schema, validator)` from `@modelcontextprotocol/server`. Applies to `inputSchema`, `outputSchema`, and `argsSchema`.
|
||||
**IMPORTANT**: v2 requires schema objects implementing [Standard Schema](https://standardschema.dev/) — raw shapes like `{ name: z.string() }` are no longer supported. Wrap with `z.object()` (Zod v4), or use ArkType's `type({...})`, or Valibot. For raw JSON Schema, wrap with `fromJsonSchema(schema)` from `@modelcontextprotocol/server` (validator defaults automatically; pass an explicit validator for custom configurations). Applies to `inputSchema`, `outputSchema`, and `argsSchema`.
|
||||
|
||||
### Tools
|
||||
|
||||
|
|
|
|||
|
|
@ -274,10 +274,10 @@ server.registerTool('greet', {
|
|||
inputSchema: type({ name: 'string' })
|
||||
}, async ({ name }) => { ... });
|
||||
|
||||
// Raw JSON Schema via fromJsonSchema
|
||||
import { fromJsonSchema, AjvJsonSchemaValidator } from '@modelcontextprotocol/server';
|
||||
// Raw JSON Schema via fromJsonSchema (validator defaults to runtime-appropriate choice)
|
||||
import { fromJsonSchema } from '@modelcontextprotocol/server';
|
||||
server.registerTool('greet', {
|
||||
inputSchema: fromJsonSchema({ type: 'object', properties: { name: { type: 'string' } } }, new AjvJsonSchemaValidator())
|
||||
inputSchema: fromJsonSchema({ type: 'object', properties: { name: { type: 'string' } } })
|
||||
}, handler);
|
||||
|
||||
// For tools with no parameters, use z.object({})
|
||||
|
|
|
|||
9
packages/client/src/fromJsonSchema.ts
Normal file
9
packages/client/src/fromJsonSchema.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import { DefaultJsonSchemaValidator } from '@modelcontextprotocol/client/_shims';
|
||||
import type { JsonSchemaType, jsonSchemaValidator, StandardSchemaWithJSON } from '@modelcontextprotocol/core';
|
||||
import { fromJsonSchema as coreFromJsonSchema } from '@modelcontextprotocol/core';
|
||||
|
||||
let _defaultValidator: jsonSchemaValidator | undefined;
|
||||
|
||||
export function fromJsonSchema<T = unknown>(schema: JsonSchemaType, validator?: jsonSchemaValidator): StandardSchemaWithJSON<T, T> {
|
||||
return coreFromJsonSchema<T>(schema, validator ?? (_defaultValidator ??= new DefaultJsonSchemaValidator()));
|
||||
}
|
||||
|
|
@ -73,5 +73,8 @@ export { StreamableHTTPClientTransport } from './client/streamableHttp.js';
|
|||
// experimental exports
|
||||
export { ExperimentalClientTasks } from './experimental/tasks/client.js';
|
||||
|
||||
// runtime-aware wrapper (shadows core/public's fromJsonSchema with optional validator)
|
||||
export { fromJsonSchema } from './fromJsonSchema.js';
|
||||
|
||||
// re-export curated public API from core
|
||||
export * from '@modelcontextprotocol/core/public';
|
||||
|
|
|
|||
|
|
@ -138,5 +138,6 @@ export type { StandardSchemaWithJSON } from '../../util/standardSchema.js';
|
|||
export { AjvJsonSchemaValidator } from '../../validators/ajvProvider.js';
|
||||
export type { CfWorkerSchemaDraft } from '../../validators/cfWorkerProvider.js';
|
||||
export { CfWorkerJsonSchemaValidator } from '../../validators/cfWorkerProvider.js';
|
||||
export { fromJsonSchema } from '../../validators/fromJsonSchema.js';
|
||||
// fromJsonSchema is intentionally NOT exported here — the server and client packages
|
||||
// provide runtime-aware wrappers that default to the appropriate validator via _shims.
|
||||
export type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator, JsonSchemaValidatorResult } from '../../validators/types.js';
|
||||
|
|
|
|||
|
|
@ -10,6 +10,11 @@ import type { JsonSchemaType, jsonSchemaValidator } from './types.js';
|
|||
* The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript
|
||||
* types attached). Cast at the call site, or use the generic `fromJsonSchema<MyType>(...)`.
|
||||
*
|
||||
* @param schema - A JSON Schema object describing the expected shape
|
||||
* @param validator - A validator provider. When importing `fromJsonSchema` from
|
||||
* `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate
|
||||
* default is provided automatically (AJV on Node.js, CfWorker on edge runtimes).
|
||||
*
|
||||
* @example
|
||||
* ```ts source="./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage"
|
||||
* const inputSchema = fromJsonSchema<{ name: string }>(
|
||||
|
|
|
|||
9
packages/server/src/fromJsonSchema.ts
Normal file
9
packages/server/src/fromJsonSchema.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import type { JsonSchemaType, jsonSchemaValidator, StandardSchemaWithJSON } from '@modelcontextprotocol/core';
|
||||
import { fromJsonSchema as coreFromJsonSchema } from '@modelcontextprotocol/core';
|
||||
import { DefaultJsonSchemaValidator } from '@modelcontextprotocol/server/_shims';
|
||||
|
||||
let _defaultValidator: jsonSchemaValidator | undefined;
|
||||
|
||||
export function fromJsonSchema<T = unknown>(schema: JsonSchemaType, validator?: jsonSchemaValidator): StandardSchemaWithJSON<T, T> {
|
||||
return coreFromJsonSchema<T>(schema, validator ?? (_defaultValidator ??= new DefaultJsonSchemaValidator()));
|
||||
}
|
||||
|
|
@ -43,5 +43,8 @@ export type { CreateTaskRequestHandler, TaskRequestHandler, ToolTaskHandler } fr
|
|||
export { ExperimentalMcpServerTasks } from './experimental/tasks/mcpServer.js';
|
||||
export { ExperimentalServerTasks } from './experimental/tasks/server.js';
|
||||
|
||||
// runtime-aware wrapper (shadows core/public's fromJsonSchema with optional validator)
|
||||
export { fromJsonSchema } from './fromJsonSchema.js';
|
||||
|
||||
// re-export curated public API from core
|
||||
export * from '@modelcontextprotocol/core/public';
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@
|
|||
import { Client } from '@modelcontextprotocol/client';
|
||||
import type { TextContent } from '@modelcontextprotocol/core';
|
||||
import { AjvJsonSchemaValidator, fromJsonSchema, InMemoryTransport } from '@modelcontextprotocol/core';
|
||||
import { completable, McpServer } from '@modelcontextprotocol/server';
|
||||
import { completable, fromJsonSchema as serverFromJsonSchema, McpServer } from '@modelcontextprotocol/server';
|
||||
import { toStandardJsonSchema } from '@valibot/to-json-schema';
|
||||
import { type } from 'arktype';
|
||||
import * as v from 'valibot';
|
||||
|
|
@ -428,6 +428,44 @@ describe('Standard Schema Support', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('fromJsonSchema with default validator (server wrapper)', () => {
|
||||
test('should use runtime-appropriate default validator when none is provided', async () => {
|
||||
const inputSchema = serverFromJsonSchema<{ name: string }>({
|
||||
type: 'object',
|
||||
properties: { name: { type: 'string' } },
|
||||
required: ['name']
|
||||
});
|
||||
|
||||
mcpServer.registerTool('greet-default', { inputSchema }, async ({ name }) => ({
|
||||
content: [{ type: 'text', text: `Hello, ${name}!` }]
|
||||
}));
|
||||
|
||||
await connectClientAndServer();
|
||||
|
||||
const result = await client.request({ method: 'tools/call', params: { name: 'greet-default', arguments: { name: 'World' } } });
|
||||
expect((result.content[0] as TextContent).text).toBe('Hello, World!');
|
||||
});
|
||||
|
||||
test('should reject invalid input with default validator', async () => {
|
||||
const inputSchema = serverFromJsonSchema({ type: 'object', properties: { count: { type: 'number' } }, required: ['count'] });
|
||||
|
||||
mcpServer.registerTool('double-default', { inputSchema }, async args => {
|
||||
const { count } = args as { count: number };
|
||||
return { content: [{ type: 'text', text: `${count * 2}` }] };
|
||||
});
|
||||
|
||||
await connectClientAndServer();
|
||||
|
||||
const result = await client.request({
|
||||
method: 'tools/call',
|
||||
params: { name: 'double-default', arguments: { count: 'not a number' } }
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
const errorText = (result.content[0] as TextContent).text;
|
||||
expect(errorText).toContain('Input validation error');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Prompt completions with Zod completable', () => {
|
||||
// Note: completable() is currently Zod-specific
|
||||
// These tests verify that Zod schemas with completable still work
|
||||
|
|
|
|||
Loading…
Reference in a new issue