feat: zod v4 with backwards compatibility for v3.25+ (#1040)
This commit is contained in:
parent
7fca1f2b15
commit
418b7f9b85
20 changed files with 14723 additions and 1002 deletions
|
|
@ -1,5 +1,5 @@
|
|||
import { RequestHandler } from 'express';
|
||||
import { z } from 'zod';
|
||||
import * as z from 'zod/v4';
|
||||
import express from 'express';
|
||||
import { OAuthServerProvider } from '../provider.js';
|
||||
import { rateLimit, Options as RateLimitOptions } from 'express-rate-limit';
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { z } from 'zod';
|
||||
import * as z from 'zod/v4';
|
||||
import express, { RequestHandler } from 'express';
|
||||
import { OAuthServerProvider } from '../provider.js';
|
||||
import cors from 'cors';
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { z } from 'zod';
|
||||
import * as z from 'zod/v4';
|
||||
import { RequestHandler } from 'express';
|
||||
import { OAuthRegisteredClientsStore } from '../clients.js';
|
||||
import { OAuthClientInformationFull } from '../../../shared/auth.js';
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { z } from 'zod';
|
||||
import { completable } from './completable.js';
|
||||
import * as z from 'zod/v4';
|
||||
import { completable, getCompleter } from './completable.js';
|
||||
|
||||
describe('completable', () => {
|
||||
it('preserves types and values of underlying schema', () => {
|
||||
|
|
@ -14,27 +14,35 @@ describe('completable', () => {
|
|||
const completions = ['foo', 'bar', 'baz'];
|
||||
const schema = completable(z.string(), () => completions);
|
||||
|
||||
expect(await schema._def.complete('')).toEqual(completions);
|
||||
const completer = getCompleter(schema);
|
||||
expect(completer).toBeDefined();
|
||||
expect(await completer!('')).toEqual(completions);
|
||||
});
|
||||
|
||||
it('allows async completion functions', async () => {
|
||||
const completions = ['foo', 'bar', 'baz'];
|
||||
const schema = completable(z.string(), async () => completions);
|
||||
|
||||
expect(await schema._def.complete('')).toEqual(completions);
|
||||
const completer = getCompleter(schema);
|
||||
expect(completer).toBeDefined();
|
||||
expect(await completer!('')).toEqual(completions);
|
||||
});
|
||||
|
||||
it('passes current value to completion function', async () => {
|
||||
const schema = completable(z.string(), value => [value + '!']);
|
||||
|
||||
expect(await schema._def.complete('test')).toEqual(['test!']);
|
||||
const completer = getCompleter(schema);
|
||||
expect(completer).toBeDefined();
|
||||
expect(await completer!('test')).toEqual(['test!']);
|
||||
});
|
||||
|
||||
it('works with number schemas', async () => {
|
||||
const schema = completable(z.number(), () => [1, 2, 3]);
|
||||
|
||||
expect(schema.parse(1)).toBe(1);
|
||||
expect(await schema._def.complete(0)).toEqual([1, 2, 3]);
|
||||
const completer = getCompleter(schema);
|
||||
expect(completer).toBeDefined();
|
||||
expect(await completer!(0)).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('preserves schema description', () => {
|
||||
|
|
|
|||
|
|
@ -1,79 +1,67 @@
|
|||
import { ZodTypeAny, ZodTypeDef, ZodType, ParseInput, ParseReturnType, RawCreateParams, ZodErrorMap, ProcessedCreateParams } from 'zod';
|
||||
import { AnySchema, SchemaInput } from './zod-compat.js';
|
||||
|
||||
export const COMPLETABLE_SYMBOL: unique symbol = Symbol.for('mcp.completable');
|
||||
|
||||
export type CompleteCallback<T extends AnySchema = AnySchema> = (
|
||||
value: SchemaInput<T>,
|
||||
context?: {
|
||||
arguments?: Record<string, string>;
|
||||
}
|
||||
) => SchemaInput<T>[] | Promise<SchemaInput<T>[]>;
|
||||
|
||||
export type CompletableMeta<T extends AnySchema = AnySchema> = {
|
||||
complete: CompleteCallback<T>;
|
||||
};
|
||||
|
||||
export type CompletableSchema<T extends AnySchema> = T & {
|
||||
[COMPLETABLE_SYMBOL]: CompletableMeta<T>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP.
|
||||
* Works with both Zod v3 and v4 schemas.
|
||||
*/
|
||||
export function completable<T extends AnySchema>(schema: T, complete: CompleteCallback<T>): CompletableSchema<T> {
|
||||
Object.defineProperty(schema as object, COMPLETABLE_SYMBOL, {
|
||||
value: { complete } as CompletableMeta<T>,
|
||||
enumerable: false,
|
||||
writable: false,
|
||||
configurable: false
|
||||
});
|
||||
return schema as CompletableSchema<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a schema is completable (has completion metadata).
|
||||
*/
|
||||
export function isCompletable(schema: unknown): schema is CompletableSchema<AnySchema> {
|
||||
return !!schema && typeof schema === 'object' && COMPLETABLE_SYMBOL in (schema as object);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the completer callback from a completable schema, if it exists.
|
||||
*/
|
||||
export function getCompleter<T extends AnySchema>(schema: T): CompleteCallback<T> | undefined {
|
||||
const meta = (schema as unknown as { [COMPLETABLE_SYMBOL]?: CompletableMeta<T> })[COMPLETABLE_SYMBOL];
|
||||
return meta?.complete as CompleteCallback<T> | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unwraps a completable schema to get the underlying schema.
|
||||
* For backward compatibility with code that called `.unwrap()`.
|
||||
*/
|
||||
export function unwrapCompletable<T extends AnySchema>(schema: CompletableSchema<T>): T {
|
||||
return schema;
|
||||
}
|
||||
|
||||
// Legacy exports for backward compatibility
|
||||
// These types are deprecated but kept for existing code
|
||||
export enum McpZodTypeKind {
|
||||
Completable = 'McpCompletable'
|
||||
}
|
||||
|
||||
export type CompleteCallback<T extends ZodTypeAny = ZodTypeAny> = (
|
||||
value: T['_input'],
|
||||
context?: {
|
||||
arguments?: Record<string, string>;
|
||||
}
|
||||
) => T['_input'][] | Promise<T['_input'][]>;
|
||||
|
||||
export interface CompletableDef<T extends ZodTypeAny = ZodTypeAny> extends ZodTypeDef {
|
||||
export interface CompletableDef<T extends AnySchema = AnySchema> {
|
||||
type: T;
|
||||
complete: CompleteCallback<T>;
|
||||
typeName: McpZodTypeKind.Completable;
|
||||
}
|
||||
|
||||
export class Completable<T extends ZodTypeAny> extends ZodType<T['_output'], CompletableDef<T>, T['_input']> {
|
||||
_parse(input: ParseInput): ParseReturnType<this['_output']> {
|
||||
const { ctx } = this._processInputParams(input);
|
||||
const data = ctx.data;
|
||||
return this._def.type._parse({
|
||||
data,
|
||||
path: ctx.path,
|
||||
parent: ctx
|
||||
});
|
||||
}
|
||||
|
||||
unwrap() {
|
||||
return this._def.type;
|
||||
}
|
||||
|
||||
static create = <T extends ZodTypeAny>(
|
||||
type: T,
|
||||
params: RawCreateParams & {
|
||||
complete: CompleteCallback<T>;
|
||||
}
|
||||
): Completable<T> => {
|
||||
return new Completable({
|
||||
type,
|
||||
typeName: McpZodTypeKind.Completable,
|
||||
complete: params.complete,
|
||||
...processCreateParams(params)
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP.
|
||||
*/
|
||||
export function completable<T extends ZodTypeAny>(schema: T, complete: CompleteCallback<T>): Completable<T> {
|
||||
return Completable.create(schema, { ...schema._def, complete });
|
||||
}
|
||||
|
||||
// Not sure why this isn't exported from Zod:
|
||||
// https://github.com/colinhacks/zod/blob/f7ad26147ba291cb3fb257545972a8e00e767470/src/types.ts#L130
|
||||
function processCreateParams(params: RawCreateParams): ProcessedCreateParams {
|
||||
if (!params) return {};
|
||||
const { errorMap, invalid_type_error, required_error, description } = params;
|
||||
if (errorMap && (invalid_type_error || required_error)) {
|
||||
throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
|
||||
}
|
||||
if (errorMap) return { errorMap: errorMap, description };
|
||||
const customMap: ZodErrorMap = (iss, ctx) => {
|
||||
const { message } = params;
|
||||
|
||||
if (iss.code === 'invalid_enum_value') {
|
||||
return { message: message ?? ctx.defaultError };
|
||||
}
|
||||
if (typeof ctx.data === 'undefined') {
|
||||
return { message: message ?? required_error ?? ctx.defaultError };
|
||||
}
|
||||
if (iss.code !== 'invalid_type') return { message: ctx.defaultError };
|
||||
return { message: message ?? invalid_type_error ?? ctx.defaultError };
|
||||
};
|
||||
return { errorMap: customMap, description };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
import { z } from 'zod';
|
||||
import * as z from 'zod/v4';
|
||||
import { Client } from '../client/index.js';
|
||||
import { InMemoryTransport } from '../inMemory.js';
|
||||
import type { Transport } from '../shared/transport.js';
|
||||
|
|
|
|||
|
|
@ -354,7 +354,7 @@ export class Server<
|
|||
params: LegacyElicitRequestFormParams | ElicitRequestFormParams | ElicitRequestURLParams,
|
||||
options?: RequestOptions
|
||||
): Promise<ElicitResult> {
|
||||
const mode = 'mode' in params ? params.mode : 'form';
|
||||
const mode = ('mode' in params ? params.mode : 'form') as 'form' | 'url';
|
||||
|
||||
switch (mode) {
|
||||
case 'url': {
|
||||
|
|
@ -370,7 +370,9 @@ export class Server<
|
|||
throw new Error('Client does not support form elicitation.');
|
||||
}
|
||||
const formParams: ElicitRequestFormParams =
|
||||
'mode' in params ? (params as ElicitRequestFormParams) : { ...(params as LegacyElicitRequestFormParams), mode: 'form' };
|
||||
'mode' in params
|
||||
? (params as ElicitRequestFormParams)
|
||||
: ({ ...(params as LegacyElicitRequestFormParams), mode: 'form' } as ElicitRequestFormParams);
|
||||
|
||||
const result = await this.request({ method: 'elicitation/create', params: formParams }, ElicitResultSchema, options);
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { z } from 'zod';
|
||||
import * as z from 'zod/v4';
|
||||
import { Client } from '../client/index.js';
|
||||
import { InMemoryTransport } from '../inMemory.js';
|
||||
import { getDisplayName } from '../shared/metadataUtils.js';
|
||||
|
|
|
|||
|
|
@ -1,6 +1,20 @@
|
|||
import { Server, ServerOptions } from './index.js';
|
||||
import { zodToJsonSchema } from 'zod-to-json-schema';
|
||||
import { z, ZodRawShape, ZodObject, ZodString, ZodTypeAny, ZodType, ZodTypeDef, ZodOptional } from 'zod';
|
||||
import {
|
||||
AnySchema,
|
||||
AnyObjectSchema,
|
||||
ZodRawShapeCompat,
|
||||
SchemaOutput,
|
||||
ShapeOutput,
|
||||
normalizeObjectSchema,
|
||||
safeParseAsync,
|
||||
getObjectShape,
|
||||
objectFromShape,
|
||||
getParseErrorMessage,
|
||||
getSchemaDescription,
|
||||
isSchemaOptional,
|
||||
getLiteralValue
|
||||
} from './zod-compat.js';
|
||||
import { toJsonSchemaCompat } from './zod-json-schema-compat.js';
|
||||
import {
|
||||
Implementation,
|
||||
Tool,
|
||||
|
|
@ -36,7 +50,7 @@ import {
|
|||
assertCompleteRequestPrompt,
|
||||
assertCompleteRequestResourceTemplate
|
||||
} from '../types.js';
|
||||
import { Completable, CompletableDef } from './completable.js';
|
||||
import { isCompletable, getCompleter } from './completable.js';
|
||||
import { UriTemplate, Variables } from '../shared/uriTemplate.js';
|
||||
import { RequestHandlerExtra } from '../shared/protocol.js';
|
||||
import { Transport } from '../shared/transport.js';
|
||||
|
|
@ -87,8 +101,8 @@ export class McpServer {
|
|||
return;
|
||||
}
|
||||
|
||||
this.server.assertCanSetRequestHandler(ListToolsRequestSchema.shape.method.value);
|
||||
this.server.assertCanSetRequestHandler(CallToolRequestSchema.shape.method.value);
|
||||
this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema));
|
||||
this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema));
|
||||
|
||||
this.server.registerCapabilities({
|
||||
tools: {
|
||||
|
|
@ -106,21 +120,27 @@ export class McpServer {
|
|||
name,
|
||||
title: tool.title,
|
||||
description: tool.description,
|
||||
inputSchema: tool.inputSchema
|
||||
? (zodToJsonSchema(tool.inputSchema, {
|
||||
strictUnions: true,
|
||||
pipeStrategy: 'input'
|
||||
}) as Tool['inputSchema'])
|
||||
: EMPTY_OBJECT_JSON_SCHEMA,
|
||||
inputSchema: (() => {
|
||||
const obj = normalizeObjectSchema(tool.inputSchema);
|
||||
return obj
|
||||
? (toJsonSchemaCompat(obj, {
|
||||
strictUnions: true,
|
||||
pipeStrategy: 'input'
|
||||
}) as Tool['inputSchema'])
|
||||
: EMPTY_OBJECT_JSON_SCHEMA;
|
||||
})(),
|
||||
annotations: tool.annotations,
|
||||
_meta: tool._meta
|
||||
};
|
||||
|
||||
if (tool.outputSchema) {
|
||||
toolDefinition.outputSchema = zodToJsonSchema(tool.outputSchema, {
|
||||
strictUnions: true,
|
||||
pipeStrategy: 'output'
|
||||
}) as Tool['outputSchema'];
|
||||
const obj = normalizeObjectSchema(tool.outputSchema);
|
||||
if (obj) {
|
||||
toolDefinition.outputSchema = toJsonSchemaCompat(obj, {
|
||||
strictUnions: true,
|
||||
pipeStrategy: 'output'
|
||||
}) as Tool['outputSchema'];
|
||||
}
|
||||
}
|
||||
|
||||
return toolDefinition;
|
||||
|
|
@ -143,12 +163,16 @@ export class McpServer {
|
|||
}
|
||||
|
||||
if (tool.inputSchema) {
|
||||
const cb = tool.callback as ToolCallback<ZodRawShape>;
|
||||
const parseResult = await tool.inputSchema.safeParseAsync(request.params.arguments);
|
||||
const cb = tool.callback as ToolCallback<ZodRawShapeCompat>;
|
||||
// Try to normalize to object schema first (for raw shapes and object schemas)
|
||||
// If that fails, use the schema directly (for union/intersection/etc)
|
||||
const inputObj = normalizeObjectSchema(tool.inputSchema);
|
||||
const schemaToParse = inputObj ?? (tool.inputSchema as AnySchema);
|
||||
const parseResult = await safeParseAsync(schemaToParse, request.params.arguments);
|
||||
if (!parseResult.success) {
|
||||
throw new McpError(
|
||||
ErrorCode.InvalidParams,
|
||||
`Input validation error: Invalid arguments for tool ${request.params.name}: ${parseResult.error.message}`
|
||||
`Input validation error: Invalid arguments for tool ${request.params.name}: ${getParseErrorMessage(parseResult.error)}`
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -169,11 +193,12 @@ export class McpServer {
|
|||
}
|
||||
|
||||
// if the tool has an output schema, validate structured content
|
||||
const parseResult = await tool.outputSchema.safeParseAsync(result.structuredContent);
|
||||
const outputObj = normalizeObjectSchema(tool.outputSchema) as AnyObjectSchema;
|
||||
const parseResult = await safeParseAsync(outputObj, result.structuredContent);
|
||||
if (!parseResult.success) {
|
||||
throw new McpError(
|
||||
ErrorCode.InvalidParams,
|
||||
`Output validation error: Invalid structured content for tool ${request.params.name}: ${parseResult.error.message}`
|
||||
`Output validation error: Invalid structured content for tool ${request.params.name}: ${getParseErrorMessage(parseResult.error)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -217,7 +242,7 @@ export class McpServer {
|
|||
return;
|
||||
}
|
||||
|
||||
this.server.assertCanSetRequestHandler(CompleteRequestSchema.shape.method.value);
|
||||
this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema));
|
||||
|
||||
this.server.registerCapabilities({
|
||||
completions: {}
|
||||
|
|
@ -255,13 +280,17 @@ export class McpServer {
|
|||
return EMPTY_COMPLETION_RESULT;
|
||||
}
|
||||
|
||||
const field = prompt.argsSchema.shape[request.params.argument.name];
|
||||
if (!(field instanceof Completable)) {
|
||||
const promptShape = getObjectShape(prompt.argsSchema);
|
||||
const field = promptShape?.[request.params.argument.name];
|
||||
if (!isCompletable(field)) {
|
||||
return EMPTY_COMPLETION_RESULT;
|
||||
}
|
||||
|
||||
const def: CompletableDef<ZodString> = field._def;
|
||||
const suggestions = await def.complete(request.params.argument.value, request.params.context);
|
||||
const completer = getCompleter(field);
|
||||
if (!completer) {
|
||||
return EMPTY_COMPLETION_RESULT;
|
||||
}
|
||||
const suggestions = await completer(request.params.argument.value, request.params.context);
|
||||
return createCompletionResult(suggestions);
|
||||
}
|
||||
|
||||
|
|
@ -296,9 +325,9 @@ export class McpServer {
|
|||
return;
|
||||
}
|
||||
|
||||
this.server.assertCanSetRequestHandler(ListResourcesRequestSchema.shape.method.value);
|
||||
this.server.assertCanSetRequestHandler(ListResourceTemplatesRequestSchema.shape.method.value);
|
||||
this.server.assertCanSetRequestHandler(ReadResourceRequestSchema.shape.method.value);
|
||||
this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema));
|
||||
this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema));
|
||||
this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema));
|
||||
|
||||
this.server.registerCapabilities({
|
||||
resources: {
|
||||
|
|
@ -379,8 +408,8 @@ export class McpServer {
|
|||
return;
|
||||
}
|
||||
|
||||
this.server.assertCanSetRequestHandler(ListPromptsRequestSchema.shape.method.value);
|
||||
this.server.assertCanSetRequestHandler(GetPromptRequestSchema.shape.method.value);
|
||||
this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema));
|
||||
this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema));
|
||||
|
||||
this.server.registerCapabilities({
|
||||
prompts: {
|
||||
|
|
@ -415,11 +444,12 @@ export class McpServer {
|
|||
}
|
||||
|
||||
if (prompt.argsSchema) {
|
||||
const parseResult = await prompt.argsSchema.safeParseAsync(request.params.arguments);
|
||||
const argsObj = normalizeObjectSchema(prompt.argsSchema) as AnyObjectSchema;
|
||||
const parseResult = await safeParseAsync(argsObj, request.params.arguments);
|
||||
if (!parseResult.success) {
|
||||
throw new McpError(
|
||||
ErrorCode.InvalidParams,
|
||||
`Invalid arguments for prompt ${request.params.name}: ${parseResult.error.message}`
|
||||
`Invalid arguments for prompt ${request.params.name}: ${getParseErrorMessage(parseResult.error)}`
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -637,7 +667,7 @@ export class McpServer {
|
|||
const registeredPrompt: RegisteredPrompt = {
|
||||
title,
|
||||
description,
|
||||
argsSchema: argsSchema === undefined ? undefined : z.object(argsSchema),
|
||||
argsSchema: argsSchema === undefined ? undefined : objectFromShape(argsSchema),
|
||||
callback,
|
||||
enabled: true,
|
||||
disable: () => registeredPrompt.update({ enabled: false }),
|
||||
|
|
@ -650,7 +680,7 @@ export class McpServer {
|
|||
}
|
||||
if (typeof updates.title !== 'undefined') registeredPrompt.title = updates.title;
|
||||
if (typeof updates.description !== 'undefined') registeredPrompt.description = updates.description;
|
||||
if (typeof updates.argsSchema !== 'undefined') registeredPrompt.argsSchema = z.object(updates.argsSchema);
|
||||
if (typeof updates.argsSchema !== 'undefined') registeredPrompt.argsSchema = objectFromShape(updates.argsSchema);
|
||||
if (typeof updates.callback !== 'undefined') registeredPrompt.callback = updates.callback;
|
||||
if (typeof updates.enabled !== 'undefined') registeredPrompt.enabled = updates.enabled;
|
||||
this.sendPromptListChanged();
|
||||
|
|
@ -664,11 +694,11 @@ export class McpServer {
|
|||
name: string,
|
||||
title: string | undefined,
|
||||
description: string | undefined,
|
||||
inputSchema: ZodRawShape | ZodType<object> | undefined,
|
||||
outputSchema: ZodRawShape | ZodType<object> | undefined,
|
||||
inputSchema: ZodRawShapeCompat | AnySchema | undefined,
|
||||
outputSchema: ZodRawShapeCompat | AnySchema | undefined,
|
||||
annotations: ToolAnnotations | undefined,
|
||||
_meta: Record<string, unknown> | undefined,
|
||||
callback: ToolCallback<ZodRawShape | undefined>
|
||||
callback: ToolCallback<ZodRawShapeCompat | undefined>
|
||||
): RegisteredTool {
|
||||
// Validate tool name according to SEP specification
|
||||
validateAndWarnToolName(name);
|
||||
|
|
@ -695,7 +725,7 @@ export class McpServer {
|
|||
}
|
||||
if (typeof updates.title !== 'undefined') registeredTool.title = updates.title;
|
||||
if (typeof updates.description !== 'undefined') registeredTool.description = updates.description;
|
||||
if (typeof updates.paramsSchema !== 'undefined') registeredTool.inputSchema = z.object(updates.paramsSchema);
|
||||
if (typeof updates.paramsSchema !== 'undefined') registeredTool.inputSchema = objectFromShape(updates.paramsSchema);
|
||||
if (typeof updates.callback !== 'undefined') registeredTool.callback = updates.callback;
|
||||
if (typeof updates.annotations !== 'undefined') registeredTool.annotations = updates.annotations;
|
||||
if (typeof updates._meta !== 'undefined') registeredTool._meta = updates._meta;
|
||||
|
|
@ -731,7 +761,11 @@ export class McpServer {
|
|||
* between ToolAnnotations and ZodRawShape during overload resolution, as both are plain object types.
|
||||
* @deprecated Use `registerTool` instead.
|
||||
*/
|
||||
tool<Args extends ZodRawShape>(name: string, paramsSchemaOrAnnotations: Args | ToolAnnotations, cb: ToolCallback<Args>): RegisteredTool;
|
||||
tool<Args extends ZodRawShapeCompat>(
|
||||
name: string,
|
||||
paramsSchemaOrAnnotations: Args | ToolAnnotations,
|
||||
cb: ToolCallback<Args>
|
||||
): RegisteredTool;
|
||||
|
||||
/**
|
||||
* Registers a tool `name` (with a description) taking either parameter schema or annotations.
|
||||
|
|
@ -742,7 +776,7 @@ export class McpServer {
|
|||
* between ToolAnnotations and ZodRawShape during overload resolution, as both are plain object types.
|
||||
* @deprecated Use `registerTool` instead.
|
||||
*/
|
||||
tool<Args extends ZodRawShape>(
|
||||
tool<Args extends ZodRawShapeCompat>(
|
||||
name: string,
|
||||
description: string,
|
||||
paramsSchemaOrAnnotations: Args | ToolAnnotations,
|
||||
|
|
@ -753,13 +787,18 @@ export class McpServer {
|
|||
* Registers a tool with both parameter schema and annotations.
|
||||
* @deprecated Use `registerTool` instead.
|
||||
*/
|
||||
tool<Args extends ZodRawShape>(name: string, paramsSchema: Args, annotations: ToolAnnotations, cb: ToolCallback<Args>): RegisteredTool;
|
||||
tool<Args extends ZodRawShapeCompat>(
|
||||
name: string,
|
||||
paramsSchema: Args,
|
||||
annotations: ToolAnnotations,
|
||||
cb: ToolCallback<Args>
|
||||
): RegisteredTool;
|
||||
|
||||
/**
|
||||
* Registers a tool with description, parameter schema, and annotations.
|
||||
* @deprecated Use `registerTool` instead.
|
||||
*/
|
||||
tool<Args extends ZodRawShape>(
|
||||
tool<Args extends ZodRawShapeCompat>(
|
||||
name: string,
|
||||
description: string,
|
||||
paramsSchema: Args,
|
||||
|
|
@ -776,8 +815,8 @@ export class McpServer {
|
|||
}
|
||||
|
||||
let description: string | undefined;
|
||||
let inputSchema: ZodRawShape | undefined;
|
||||
let outputSchema: ZodRawShape | undefined;
|
||||
let inputSchema: ZodRawShapeCompat | undefined;
|
||||
let outputSchema: ZodRawShapeCompat | undefined;
|
||||
let annotations: ToolAnnotations | undefined;
|
||||
|
||||
// Tool properties are passed as separate arguments, with omissions allowed.
|
||||
|
|
@ -795,7 +834,7 @@ export class McpServer {
|
|||
|
||||
if (isZodRawShape(firstArg)) {
|
||||
// We have a params schema as the first arg
|
||||
inputSchema = rest.shift() as ZodRawShape;
|
||||
inputSchema = rest.shift() as ZodRawShapeCompat;
|
||||
|
||||
// Check if the next arg is potentially annotations
|
||||
if (rest.length > 1 && typeof rest[0] === 'object' && rest[0] !== null && !isZodRawShape(rest[0])) {
|
||||
|
|
@ -810,7 +849,7 @@ export class McpServer {
|
|||
annotations = rest.shift() as ToolAnnotations;
|
||||
}
|
||||
}
|
||||
const callback = rest[0] as ToolCallback<ZodRawShape | undefined>;
|
||||
const callback = rest[0] as ToolCallback<ZodRawShapeCompat | undefined>;
|
||||
|
||||
return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, undefined, callback);
|
||||
}
|
||||
|
|
@ -818,7 +857,7 @@ export class McpServer {
|
|||
/**
|
||||
* Registers a tool with a config object and callback.
|
||||
*/
|
||||
registerTool<InputArgs extends ZodRawShape | ZodType<object>, OutputArgs extends ZodRawShape | ZodType<object>>(
|
||||
registerTool<InputArgs extends ZodRawShapeCompat | AnySchema, OutputArgs extends ZodRawShapeCompat | AnySchema>(
|
||||
name: string,
|
||||
config: {
|
||||
title?: string;
|
||||
|
|
@ -844,7 +883,7 @@ export class McpServer {
|
|||
outputSchema,
|
||||
annotations,
|
||||
_meta,
|
||||
cb as ToolCallback<ZodRawShape | undefined>
|
||||
cb as ToolCallback<ZodRawShapeCompat | undefined>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -1047,27 +1086,27 @@ export class ResourceTemplate {
|
|||
* - `content` if the tool does not have an outputSchema
|
||||
* - Both fields are optional but typically one should be provided
|
||||
*/
|
||||
export type ToolCallback<Args extends undefined | ZodRawShape | ZodType<object> = undefined> = Args extends ZodRawShape
|
||||
? (
|
||||
args: z.objectOutputType<Args, ZodTypeAny>,
|
||||
extra: RequestHandlerExtra<ServerRequest, ServerNotification>
|
||||
) => CallToolResult | Promise<CallToolResult>
|
||||
: Args extends ZodType<infer T>
|
||||
? (args: T, extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => CallToolResult | Promise<CallToolResult>
|
||||
export type ToolCallback<Args extends undefined | ZodRawShapeCompat | AnySchema = undefined> = Args extends ZodRawShapeCompat
|
||||
? (args: ShapeOutput<Args>, extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => CallToolResult | Promise<CallToolResult>
|
||||
: Args extends AnySchema
|
||||
? (
|
||||
args: SchemaOutput<Args>,
|
||||
extra: RequestHandlerExtra<ServerRequest, ServerNotification>
|
||||
) => CallToolResult | Promise<CallToolResult>
|
||||
: (extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => CallToolResult | Promise<CallToolResult>;
|
||||
|
||||
export type RegisteredTool = {
|
||||
title?: string;
|
||||
description?: string;
|
||||
inputSchema?: ZodType<object>;
|
||||
outputSchema?: ZodType<object>;
|
||||
inputSchema?: AnySchema;
|
||||
outputSchema?: AnySchema;
|
||||
annotations?: ToolAnnotations;
|
||||
_meta?: Record<string, unknown>;
|
||||
callback: ToolCallback<undefined | ZodRawShape>;
|
||||
callback: ToolCallback<undefined | ZodRawShapeCompat>;
|
||||
enabled: boolean;
|
||||
enable(): void;
|
||||
disable(): void;
|
||||
update<InputArgs extends ZodRawShape, OutputArgs extends ZodRawShape>(updates: {
|
||||
update<InputArgs extends ZodRawShapeCompat, OutputArgs extends ZodRawShapeCompat>(updates: {
|
||||
name?: string | null;
|
||||
title?: string;
|
||||
description?: string;
|
||||
|
|
@ -1086,8 +1125,8 @@ const EMPTY_OBJECT_JSON_SCHEMA = {
|
|||
properties: {}
|
||||
};
|
||||
|
||||
// Helper to check if an object is a Zod schema (ZodRawShape)
|
||||
function isZodRawShape(obj: unknown): obj is ZodRawShape {
|
||||
// Helper to check if an object is a Zod schema (ZodRawShapeCompat)
|
||||
function isZodRawShape(obj: unknown): obj is ZodRawShapeCompat {
|
||||
if (typeof obj !== 'object' || obj === null) return false;
|
||||
|
||||
const isEmptyObject = Object.keys(obj).length === 0;
|
||||
|
|
@ -1097,7 +1136,7 @@ function isZodRawShape(obj: unknown): obj is ZodRawShape {
|
|||
return isEmptyObject || Object.values(obj as object).some(isZodTypeLike);
|
||||
}
|
||||
|
||||
function isZodTypeLike(value: unknown): value is ZodType {
|
||||
function isZodTypeLike(value: unknown): value is AnySchema {
|
||||
return (
|
||||
value !== null &&
|
||||
typeof value === 'object' &&
|
||||
|
|
@ -1112,13 +1151,13 @@ function isZodTypeLike(value: unknown): value is ZodType {
|
|||
* Converts a provided Zod schema to a Zod object if it is a ZodRawShape,
|
||||
* otherwise returns the schema as is.
|
||||
*/
|
||||
function getZodSchemaObject(schema: ZodRawShape | ZodType<object> | undefined): ZodType<object> | undefined {
|
||||
function getZodSchemaObject(schema: ZodRawShapeCompat | AnySchema | undefined): AnySchema | undefined {
|
||||
if (!schema) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (isZodRawShape(schema)) {
|
||||
return z.object(schema);
|
||||
return objectFromShape(schema);
|
||||
}
|
||||
|
||||
return schema;
|
||||
|
|
@ -1191,21 +1230,16 @@ export type RegisteredResourceTemplate = {
|
|||
remove(): void;
|
||||
};
|
||||
|
||||
type PromptArgsRawShape = {
|
||||
[k: string]: ZodType<string, ZodTypeDef, string> | ZodOptional<ZodType<string, ZodTypeDef, string>>;
|
||||
};
|
||||
type PromptArgsRawShape = ZodRawShapeCompat;
|
||||
|
||||
export type PromptCallback<Args extends undefined | PromptArgsRawShape = undefined> = Args extends PromptArgsRawShape
|
||||
? (
|
||||
args: z.objectOutputType<Args, ZodTypeAny>,
|
||||
extra: RequestHandlerExtra<ServerRequest, ServerNotification>
|
||||
) => GetPromptResult | Promise<GetPromptResult>
|
||||
? (args: ShapeOutput<Args>, extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => GetPromptResult | Promise<GetPromptResult>
|
||||
: (extra: RequestHandlerExtra<ServerRequest, ServerNotification>) => GetPromptResult | Promise<GetPromptResult>;
|
||||
|
||||
export type RegisteredPrompt = {
|
||||
title?: string;
|
||||
description?: string;
|
||||
argsSchema?: ZodObject<PromptArgsRawShape>;
|
||||
argsSchema?: AnyObjectSchema;
|
||||
callback: PromptCallback<undefined | PromptArgsRawShape>;
|
||||
enabled: boolean;
|
||||
enable(): void;
|
||||
|
|
@ -1221,14 +1255,36 @@ export type RegisteredPrompt = {
|
|||
remove(): void;
|
||||
};
|
||||
|
||||
function promptArgumentsFromSchema(schema: ZodObject<PromptArgsRawShape>): PromptArgument[] {
|
||||
return Object.entries(schema.shape).map(
|
||||
([name, field]): PromptArgument => ({
|
||||
function promptArgumentsFromSchema(schema: AnyObjectSchema): PromptArgument[] {
|
||||
const shape = getObjectShape(schema);
|
||||
if (!shape) return [];
|
||||
return Object.entries(shape).map(([name, field]): PromptArgument => {
|
||||
// Get description - works for both v3 and v4
|
||||
const description = getSchemaDescription(field);
|
||||
// Check if optional - works for both v3 and v4
|
||||
const isOptional = isSchemaOptional(field);
|
||||
return {
|
||||
name,
|
||||
description: field.description,
|
||||
required: !field.isOptional()
|
||||
})
|
||||
);
|
||||
description,
|
||||
required: !isOptional
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function getMethodValue(schema: AnyObjectSchema): string {
|
||||
const shape = getObjectShape(schema);
|
||||
const methodSchema = shape?.method as AnySchema | undefined;
|
||||
if (!methodSchema) {
|
||||
throw new Error('Schema is missing a method literal');
|
||||
}
|
||||
|
||||
// Extract literal value - works for both v3 and v4
|
||||
const value = getLiteralValue(methodSchema);
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
|
||||
throw new Error('Schema method literal must be a string');
|
||||
}
|
||||
|
||||
function createCompletionResult(suggestions: string[]): CompleteResult {
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { SSEServerTransport } from './sse.js';
|
|||
import { McpServer } from './mcp.js';
|
||||
import { createServer, type Server } from 'node:http';
|
||||
import { AddressInfo } from 'node:net';
|
||||
import { z } from 'zod';
|
||||
import * as z from 'zod/v4';
|
||||
import { CallToolResult, JSONRPCMessage } from '../types.js';
|
||||
|
||||
const createMockResponse = () => {
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { randomUUID } from 'node:crypto';
|
|||
import { EventStore, StreamableHTTPServerTransport, EventId, StreamId } from './streamableHttp.js';
|
||||
import { McpServer } from './mcp.js';
|
||||
import { CallToolResult, JSONRPCMessage } from '../types.js';
|
||||
import { z } from 'zod';
|
||||
import * as z from 'zod/v4';
|
||||
import { AuthInfo } from './auth/types.js';
|
||||
|
||||
async function getFreePort() {
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { Server } from './index.js';
|
||||
import { Client } from '../client/index.js';
|
||||
import { InMemoryTransport } from '../inMemory.js';
|
||||
import { z } from 'zod';
|
||||
import * as z from 'zod/v4';
|
||||
import { McpServer, ResourceTemplate } from './mcp.js';
|
||||
|
||||
describe('Title field backwards compatibility', () => {
|
||||
|
|
|
|||
54
src/server/v3/completable.v3.test.ts
Normal file
54
src/server/v3/completable.v3.test.ts
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
import * as z from 'zod/v3';
|
||||
import { completable, getCompleter } from '../completable.js';
|
||||
|
||||
describe('completable', () => {
|
||||
it('preserves types and values of underlying schema', () => {
|
||||
const baseSchema = z.string();
|
||||
const schema = completable(baseSchema, () => []);
|
||||
|
||||
expect(schema.parse('test')).toBe('test');
|
||||
expect(() => schema.parse(123)).toThrow();
|
||||
});
|
||||
|
||||
it('provides access to completion function', async () => {
|
||||
const completions = ['foo', 'bar', 'baz'];
|
||||
const schema = completable(z.string(), () => completions);
|
||||
|
||||
const completer = getCompleter(schema);
|
||||
expect(completer).toBeDefined();
|
||||
expect(await completer!('')).toEqual(completions);
|
||||
});
|
||||
|
||||
it('allows async completion functions', async () => {
|
||||
const completions = ['foo', 'bar', 'baz'];
|
||||
const schema = completable(z.string(), async () => completions);
|
||||
|
||||
const completer = getCompleter(schema);
|
||||
expect(completer).toBeDefined();
|
||||
expect(await completer!('')).toEqual(completions);
|
||||
});
|
||||
|
||||
it('passes current value to completion function', async () => {
|
||||
const schema = completable(z.string(), value => [value + '!']);
|
||||
|
||||
const completer = getCompleter(schema);
|
||||
expect(completer).toBeDefined();
|
||||
expect(await completer!('test')).toEqual(['test!']);
|
||||
});
|
||||
|
||||
it('works with number schemas', async () => {
|
||||
const schema = completable(z.number(), () => [1, 2, 3]);
|
||||
|
||||
expect(schema.parse(1)).toBe(1);
|
||||
const completer = getCompleter(schema);
|
||||
expect(completer).toBeDefined();
|
||||
expect(await completer!(0)).toEqual([1, 2, 3]);
|
||||
});
|
||||
|
||||
it('preserves schema description', () => {
|
||||
const desc = 'test description';
|
||||
const schema = completable(z.string().describe(desc), () => []);
|
||||
|
||||
expect(schema.description).toBe(desc);
|
||||
});
|
||||
});
|
||||
964
src/server/v3/index.v3.test.ts
Normal file
964
src/server/v3/index.v3.test.ts
Normal file
|
|
@ -0,0 +1,964 @@
|
|||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
import * as z from 'zod/v3';
|
||||
import { Client } from '../../client/index.js';
|
||||
import { InMemoryTransport } from '../../inMemory.js';
|
||||
import type { Transport } from '../../shared/transport.js';
|
||||
import {
|
||||
CreateMessageRequestSchema,
|
||||
ElicitRequestSchema,
|
||||
ErrorCode,
|
||||
LATEST_PROTOCOL_VERSION,
|
||||
ListPromptsRequestSchema,
|
||||
ListResourcesRequestSchema,
|
||||
ListToolsRequestSchema,
|
||||
type LoggingMessageNotification,
|
||||
NotificationSchema,
|
||||
RequestSchema,
|
||||
ResultSchema,
|
||||
SetLevelRequestSchema,
|
||||
SUPPORTED_PROTOCOL_VERSIONS
|
||||
} from '../../types.js';
|
||||
import { Server } from '../index.js';
|
||||
import { AnyObjectSchema } from '../zod-compat.js';
|
||||
|
||||
test('should accept latest protocol version', async () => {
|
||||
let sendPromiseResolve: (value: unknown) => void;
|
||||
const sendPromise = new Promise(resolve => {
|
||||
sendPromiseResolve = resolve;
|
||||
});
|
||||
|
||||
const serverTransport: Transport = {
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
close: vi.fn().mockResolvedValue(undefined),
|
||||
send: vi.fn().mockImplementation(message => {
|
||||
if (message.id === 1 && message.result) {
|
||||
expect(message.result).toEqual({
|
||||
protocolVersion: LATEST_PROTOCOL_VERSION,
|
||||
capabilities: expect.any(Object),
|
||||
serverInfo: {
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
},
|
||||
instructions: 'Test instructions'
|
||||
});
|
||||
sendPromiseResolve(undefined);
|
||||
}
|
||||
return Promise.resolve();
|
||||
})
|
||||
};
|
||||
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
prompts: {},
|
||||
resources: {},
|
||||
tools: {},
|
||||
logging: {}
|
||||
},
|
||||
instructions: 'Test instructions'
|
||||
}
|
||||
);
|
||||
|
||||
await server.connect(serverTransport);
|
||||
|
||||
// Simulate initialize request with latest version
|
||||
serverTransport.onmessage?.({
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'initialize',
|
||||
params: {
|
||||
protocolVersion: LATEST_PROTOCOL_VERSION,
|
||||
capabilities: {},
|
||||
clientInfo: {
|
||||
name: 'test client',
|
||||
version: '1.0'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await expect(sendPromise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
test('should accept supported older protocol version', async () => {
|
||||
const OLD_VERSION = SUPPORTED_PROTOCOL_VERSIONS[1];
|
||||
let sendPromiseResolve: (value: unknown) => void;
|
||||
const sendPromise = new Promise(resolve => {
|
||||
sendPromiseResolve = resolve;
|
||||
});
|
||||
|
||||
const serverTransport: Transport = {
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
close: vi.fn().mockResolvedValue(undefined),
|
||||
send: vi.fn().mockImplementation(message => {
|
||||
if (message.id === 1 && message.result) {
|
||||
expect(message.result).toEqual({
|
||||
protocolVersion: OLD_VERSION,
|
||||
capabilities: expect.any(Object),
|
||||
serverInfo: {
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
}
|
||||
});
|
||||
sendPromiseResolve(undefined);
|
||||
}
|
||||
return Promise.resolve();
|
||||
})
|
||||
};
|
||||
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
prompts: {},
|
||||
resources: {},
|
||||
tools: {},
|
||||
logging: {}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
await server.connect(serverTransport);
|
||||
|
||||
// Simulate initialize request with older version
|
||||
serverTransport.onmessage?.({
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'initialize',
|
||||
params: {
|
||||
protocolVersion: OLD_VERSION,
|
||||
capabilities: {},
|
||||
clientInfo: {
|
||||
name: 'test client',
|
||||
version: '1.0'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await expect(sendPromise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
test('should handle unsupported protocol version', async () => {
|
||||
let sendPromiseResolve: (value: unknown) => void;
|
||||
const sendPromise = new Promise(resolve => {
|
||||
sendPromiseResolve = resolve;
|
||||
});
|
||||
|
||||
const serverTransport: Transport = {
|
||||
start: vi.fn().mockResolvedValue(undefined),
|
||||
close: vi.fn().mockResolvedValue(undefined),
|
||||
send: vi.fn().mockImplementation(message => {
|
||||
if (message.id === 1 && message.result) {
|
||||
expect(message.result).toEqual({
|
||||
protocolVersion: LATEST_PROTOCOL_VERSION,
|
||||
capabilities: expect.any(Object),
|
||||
serverInfo: {
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
}
|
||||
});
|
||||
sendPromiseResolve(undefined);
|
||||
}
|
||||
return Promise.resolve();
|
||||
})
|
||||
};
|
||||
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
prompts: {},
|
||||
resources: {},
|
||||
tools: {},
|
||||
logging: {}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
await server.connect(serverTransport);
|
||||
|
||||
// Simulate initialize request with unsupported version
|
||||
serverTransport.onmessage?.({
|
||||
jsonrpc: '2.0',
|
||||
id: 1,
|
||||
method: 'initialize',
|
||||
params: {
|
||||
protocolVersion: 'invalid-version',
|
||||
capabilities: {},
|
||||
clientInfo: {
|
||||
name: 'test client',
|
||||
version: '1.0'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
await expect(sendPromise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
test('should respect client capabilities', async () => {
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
prompts: {},
|
||||
resources: {},
|
||||
tools: {},
|
||||
logging: {}
|
||||
},
|
||||
enforceStrictCapabilities: true
|
||||
}
|
||||
);
|
||||
|
||||
const client = new Client(
|
||||
{
|
||||
name: 'test client',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
sampling: {}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Implement request handler for sampling/createMessage
|
||||
client.setRequestHandler(CreateMessageRequestSchema, async _request => {
|
||||
// Mock implementation of createMessage
|
||||
return {
|
||||
model: 'test-model',
|
||||
role: 'assistant',
|
||||
content: {
|
||||
type: 'text',
|
||||
text: 'This is a test response'
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]);
|
||||
|
||||
expect(server.getClientCapabilities()).toEqual({ sampling: {} });
|
||||
|
||||
// This should work because sampling is supported by the client
|
||||
await expect(
|
||||
server.createMessage({
|
||||
messages: [],
|
||||
maxTokens: 10
|
||||
})
|
||||
).resolves.not.toThrow();
|
||||
|
||||
// This should still throw because roots are not supported by the client
|
||||
await expect(server.listRoots()).rejects.toThrow(/^Client does not support/);
|
||||
});
|
||||
|
||||
test('should respect client elicitation capabilities', async () => {
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
prompts: {},
|
||||
resources: {},
|
||||
tools: {},
|
||||
logging: {}
|
||||
},
|
||||
enforceStrictCapabilities: true
|
||||
}
|
||||
);
|
||||
|
||||
const client = new Client(
|
||||
{
|
||||
name: 'test client',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
elicitation: {}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
client.setRequestHandler(ElicitRequestSchema, params => ({
|
||||
action: 'accept',
|
||||
content: {
|
||||
username: params.params.message.includes('username') ? 'test-user' : undefined,
|
||||
confirmed: true
|
||||
}
|
||||
}));
|
||||
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]);
|
||||
|
||||
expect(server.getClientCapabilities()).toEqual({ elicitation: { form: {} } });
|
||||
|
||||
// This should work because elicitation is supported by the client
|
||||
await expect(
|
||||
server.elicitInput({
|
||||
message: 'Please provide your username',
|
||||
requestedSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
username: {
|
||||
type: 'string',
|
||||
title: 'Username',
|
||||
description: 'Your username'
|
||||
},
|
||||
confirmed: {
|
||||
type: 'boolean',
|
||||
title: 'Confirm',
|
||||
description: 'Please confirm',
|
||||
default: false
|
||||
}
|
||||
},
|
||||
required: ['username']
|
||||
}
|
||||
})
|
||||
).resolves.toEqual({
|
||||
action: 'accept',
|
||||
content: {
|
||||
username: 'test-user',
|
||||
confirmed: true
|
||||
}
|
||||
});
|
||||
|
||||
// This should still throw because sampling is not supported by the client
|
||||
await expect(
|
||||
server.createMessage({
|
||||
messages: [],
|
||||
maxTokens: 10
|
||||
})
|
||||
).rejects.toThrow(/^Client does not support/);
|
||||
});
|
||||
|
||||
test('should validate elicitation response against requested schema', async () => {
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
prompts: {},
|
||||
resources: {},
|
||||
tools: {},
|
||||
logging: {}
|
||||
},
|
||||
enforceStrictCapabilities: true
|
||||
}
|
||||
);
|
||||
|
||||
const client = new Client(
|
||||
{
|
||||
name: 'test client',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
elicitation: {}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Set up client to return valid response
|
||||
client.setRequestHandler(ElicitRequestSchema, _request => ({
|
||||
action: 'accept',
|
||||
content: {
|
||||
name: 'John Doe',
|
||||
email: 'john@example.com',
|
||||
age: 30
|
||||
}
|
||||
}));
|
||||
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]);
|
||||
|
||||
// Test with valid response
|
||||
await expect(
|
||||
server.elicitInput({
|
||||
message: 'Please provide your information',
|
||||
requestedSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: {
|
||||
type: 'string',
|
||||
minLength: 1
|
||||
},
|
||||
email: {
|
||||
type: 'string',
|
||||
minLength: 1
|
||||
},
|
||||
age: {
|
||||
type: 'integer',
|
||||
minimum: 0,
|
||||
maximum: 150
|
||||
}
|
||||
},
|
||||
required: ['name', 'email']
|
||||
}
|
||||
})
|
||||
).resolves.toEqual({
|
||||
action: 'accept',
|
||||
content: {
|
||||
name: 'John Doe',
|
||||
email: 'john@example.com',
|
||||
age: 30
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
test('should reject elicitation response with invalid data', async () => {
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
prompts: {},
|
||||
resources: {},
|
||||
tools: {},
|
||||
logging: {}
|
||||
},
|
||||
enforceStrictCapabilities: true
|
||||
}
|
||||
);
|
||||
|
||||
const client = new Client(
|
||||
{
|
||||
name: 'test client',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
elicitation: {}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Set up client to return invalid response (missing required field, invalid age)
|
||||
client.setRequestHandler(ElicitRequestSchema, _request => ({
|
||||
action: 'accept',
|
||||
content: {
|
||||
email: '', // Invalid - too short
|
||||
age: -5 // Invalid age
|
||||
}
|
||||
}));
|
||||
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]);
|
||||
|
||||
// Test with invalid response
|
||||
await expect(
|
||||
server.elicitInput({
|
||||
message: 'Please provide your information',
|
||||
requestedSchema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: {
|
||||
type: 'string',
|
||||
minLength: 1
|
||||
},
|
||||
email: {
|
||||
type: 'string',
|
||||
minLength: 1
|
||||
},
|
||||
age: {
|
||||
type: 'integer',
|
||||
minimum: 0,
|
||||
maximum: 150
|
||||
}
|
||||
},
|
||||
required: ['name', 'email']
|
||||
}
|
||||
})
|
||||
).rejects.toThrow(/does not match requested schema/);
|
||||
});
|
||||
|
||||
test('should allow elicitation reject and cancel without validation', async () => {
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
prompts: {},
|
||||
resources: {},
|
||||
tools: {},
|
||||
logging: {}
|
||||
},
|
||||
enforceStrictCapabilities: true
|
||||
}
|
||||
);
|
||||
|
||||
const client = new Client(
|
||||
{
|
||||
name: 'test client',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
elicitation: {}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
let requestCount = 0;
|
||||
client.setRequestHandler(ElicitRequestSchema, _request => {
|
||||
requestCount++;
|
||||
if (requestCount === 1) {
|
||||
return { action: 'decline' };
|
||||
} else {
|
||||
return { action: 'cancel' };
|
||||
}
|
||||
});
|
||||
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]);
|
||||
|
||||
const schema = {
|
||||
type: 'object' as const,
|
||||
properties: {
|
||||
name: { type: 'string' as const }
|
||||
},
|
||||
required: ['name']
|
||||
};
|
||||
|
||||
// Test reject - should not validate
|
||||
await expect(
|
||||
server.elicitInput({
|
||||
message: 'Please provide your name',
|
||||
requestedSchema: schema
|
||||
})
|
||||
).resolves.toEqual({
|
||||
action: 'decline'
|
||||
});
|
||||
|
||||
// Test cancel - should not validate
|
||||
await expect(
|
||||
server.elicitInput({
|
||||
message: 'Please provide your name',
|
||||
requestedSchema: schema
|
||||
})
|
||||
).resolves.toEqual({
|
||||
action: 'cancel'
|
||||
});
|
||||
});
|
||||
|
||||
test('should respect server notification capabilities', async () => {
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
logging: {}
|
||||
},
|
||||
enforceStrictCapabilities: true
|
||||
}
|
||||
);
|
||||
|
||||
const [_clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
await server.connect(serverTransport);
|
||||
|
||||
// This should work because logging is supported by the server
|
||||
await expect(
|
||||
server.sendLoggingMessage({
|
||||
level: 'info',
|
||||
data: 'Test log message'
|
||||
})
|
||||
).resolves.not.toThrow();
|
||||
|
||||
// This should throw because resource notificaitons are not supported by the server
|
||||
await expect(server.sendResourceUpdated({ uri: 'test://resource' })).rejects.toThrow(/^Server does not support/);
|
||||
});
|
||||
|
||||
test('should only allow setRequestHandler for declared capabilities', () => {
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
prompts: {},
|
||||
resources: {}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// These should work because the capabilities are declared
|
||||
expect(() => {
|
||||
server.setRequestHandler(ListPromptsRequestSchema, () => ({ prompts: [] }));
|
||||
}).not.toThrow();
|
||||
|
||||
expect(() => {
|
||||
server.setRequestHandler(ListResourcesRequestSchema, () => ({
|
||||
resources: []
|
||||
}));
|
||||
}).not.toThrow();
|
||||
|
||||
// These should throw because the capabilities are not declared
|
||||
expect(() => {
|
||||
server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: [] }));
|
||||
}).toThrow(/^Server does not support tools/);
|
||||
|
||||
expect(() => {
|
||||
server.setRequestHandler(SetLevelRequestSchema, () => ({}));
|
||||
}).toThrow(/^Server does not support logging/);
|
||||
});
|
||||
|
||||
/*
|
||||
Test that custom request/notification/result schemas can be used with the Server class.
|
||||
*/
|
||||
test('should typecheck', () => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const GetWeatherRequestSchema = (RequestSchema as unknown as z.ZodObject<any>).extend({
|
||||
method: z.literal('weather/get'),
|
||||
params: z.object({
|
||||
city: z.string()
|
||||
})
|
||||
}) as AnyObjectSchema;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const GetForecastRequestSchema = (RequestSchema as unknown as z.ZodObject<any>).extend({
|
||||
method: z.literal('weather/forecast'),
|
||||
params: z.object({
|
||||
city: z.string(),
|
||||
days: z.number()
|
||||
})
|
||||
}) as AnyObjectSchema;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const WeatherForecastNotificationSchema = (NotificationSchema as unknown as z.ZodObject<any>).extend({
|
||||
method: z.literal('weather/alert'),
|
||||
params: z.object({
|
||||
severity: z.enum(['warning', 'watch']),
|
||||
message: z.string()
|
||||
})
|
||||
}) as AnyObjectSchema;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const WeatherRequestSchema = (GetWeatherRequestSchema as unknown as z.ZodObject<any>).or(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
GetForecastRequestSchema as unknown as z.ZodObject<any>
|
||||
) as AnyObjectSchema;
|
||||
const WeatherNotificationSchema = WeatherForecastNotificationSchema as AnyObjectSchema;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const WeatherResultSchema = (ResultSchema as unknown as z.ZodObject<any>).extend({
|
||||
temperature: z.number(),
|
||||
conditions: z.string()
|
||||
}) as AnyObjectSchema;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type InferSchema<T> = T extends z.ZodType<infer Output, any, any> ? Output : never;
|
||||
type WeatherRequest = InferSchema<typeof WeatherRequestSchema>;
|
||||
type WeatherNotification = InferSchema<typeof WeatherNotificationSchema>;
|
||||
type WeatherResult = InferSchema<typeof WeatherResultSchema>;
|
||||
|
||||
// Create a typed Server for weather data
|
||||
const weatherServer = new Server<WeatherRequest, WeatherNotification, WeatherResult>(
|
||||
{
|
||||
name: 'WeatherServer',
|
||||
version: '1.0.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
prompts: {},
|
||||
resources: {},
|
||||
tools: {},
|
||||
logging: {}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Typecheck that only valid weather requests/notifications/results are allowed
|
||||
weatherServer.setRequestHandler(GetWeatherRequestSchema, _request => {
|
||||
return {
|
||||
temperature: 72,
|
||||
conditions: 'sunny'
|
||||
};
|
||||
});
|
||||
|
||||
weatherServer.setNotificationHandler(WeatherForecastNotificationSchema, notification => {
|
||||
// Type assertion needed for v3/v4 schema mixing
|
||||
const params = notification.params as { message: string; severity: 'warning' | 'watch' };
|
||||
console.log(`Weather alert: ${params.message}`);
|
||||
});
|
||||
});
|
||||
|
||||
test('should handle server cancelling a request', async () => {
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {}
|
||||
}
|
||||
);
|
||||
|
||||
const client = new Client(
|
||||
{
|
||||
name: 'test client',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
sampling: {}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Set up client to delay responding to createMessage
|
||||
client.setRequestHandler(CreateMessageRequestSchema, async (_request, _extra) => {
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
return {
|
||||
model: 'test',
|
||||
role: 'assistant',
|
||||
content: {
|
||||
type: 'text',
|
||||
text: 'Test response'
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]);
|
||||
|
||||
// Set up abort controller
|
||||
const controller = new AbortController();
|
||||
|
||||
// Issue request but cancel it immediately
|
||||
const createMessagePromise = server.createMessage(
|
||||
{
|
||||
messages: [],
|
||||
maxTokens: 10
|
||||
},
|
||||
{
|
||||
signal: controller.signal
|
||||
}
|
||||
);
|
||||
controller.abort('Cancelled by test');
|
||||
|
||||
// Request should be rejected
|
||||
await expect(createMessagePromise).rejects.toBe('Cancelled by test');
|
||||
});
|
||||
|
||||
test('should handle request timeout', async () => {
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {}
|
||||
}
|
||||
);
|
||||
|
||||
// Set up client that delays responses
|
||||
const client = new Client(
|
||||
{
|
||||
name: 'test client',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
sampling: {}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
client.setRequestHandler(CreateMessageRequestSchema, async (_request, extra) => {
|
||||
await new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(resolve, 100);
|
||||
extra.signal.addEventListener('abort', () => {
|
||||
clearTimeout(timeout);
|
||||
reject(extra.signal.reason);
|
||||
});
|
||||
});
|
||||
|
||||
return {
|
||||
model: 'test',
|
||||
role: 'assistant',
|
||||
content: {
|
||||
type: 'text',
|
||||
text: 'Test response'
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]);
|
||||
|
||||
// Request with 0 msec timeout should fail immediately
|
||||
await expect(
|
||||
server.createMessage(
|
||||
{
|
||||
messages: [],
|
||||
maxTokens: 10
|
||||
},
|
||||
{ timeout: 0 }
|
||||
)
|
||||
).rejects.toMatchObject({
|
||||
code: ErrorCode.RequestTimeout
|
||||
});
|
||||
});
|
||||
|
||||
/*
|
||||
Test automatic log level handling for transports with and without sessionId
|
||||
*/
|
||||
test('should respect log level for transport without sessionId', async () => {
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
prompts: {},
|
||||
resources: {},
|
||||
tools: {},
|
||||
logging: {}
|
||||
},
|
||||
enforceStrictCapabilities: true
|
||||
}
|
||||
);
|
||||
|
||||
const client = new Client({
|
||||
name: 'test client',
|
||||
version: '1.0'
|
||||
});
|
||||
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]);
|
||||
|
||||
expect(clientTransport.sessionId).toEqual(undefined);
|
||||
|
||||
// Client sets logging level to warning
|
||||
await client.setLoggingLevel('warning');
|
||||
|
||||
// This one will make it through
|
||||
const warningParams: LoggingMessageNotification['params'] = {
|
||||
level: 'warning',
|
||||
logger: 'test server',
|
||||
data: 'Warning message'
|
||||
};
|
||||
|
||||
// This one will not
|
||||
const debugParams: LoggingMessageNotification['params'] = {
|
||||
level: 'debug',
|
||||
logger: 'test server',
|
||||
data: 'Debug message'
|
||||
};
|
||||
|
||||
// Test the one that makes it through
|
||||
clientTransport.onmessage = vi.fn().mockImplementation(message => {
|
||||
expect(message).toEqual({
|
||||
jsonrpc: '2.0',
|
||||
method: 'notifications/message',
|
||||
params: warningParams
|
||||
});
|
||||
});
|
||||
|
||||
// This one will not make it through
|
||||
await server.sendLoggingMessage(debugParams);
|
||||
expect(clientTransport.onmessage).not.toHaveBeenCalled();
|
||||
|
||||
// This one will, triggering the above test in clientTransport.onmessage
|
||||
await server.sendLoggingMessage(warningParams);
|
||||
expect(clientTransport.onmessage).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('should respect log level for transport with sessionId', async () => {
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test server',
|
||||
version: '1.0'
|
||||
},
|
||||
{
|
||||
capabilities: {
|
||||
prompts: {},
|
||||
resources: {},
|
||||
tools: {},
|
||||
logging: {}
|
||||
},
|
||||
enforceStrictCapabilities: true
|
||||
}
|
||||
);
|
||||
|
||||
const client = new Client({
|
||||
name: 'test client',
|
||||
version: '1.0'
|
||||
});
|
||||
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
// Add a session id to the transports
|
||||
const SESSION_ID = 'test-session-id';
|
||||
clientTransport.sessionId = SESSION_ID;
|
||||
serverTransport.sessionId = SESSION_ID;
|
||||
|
||||
expect(clientTransport.sessionId).toBeDefined();
|
||||
expect(serverTransport.sessionId).toBeDefined();
|
||||
|
||||
await Promise.all([client.connect(clientTransport), server.connect(serverTransport)]);
|
||||
|
||||
// Client sets logging level to warning
|
||||
await client.setLoggingLevel('warning');
|
||||
|
||||
// This one will make it through
|
||||
const warningParams: LoggingMessageNotification['params'] = {
|
||||
level: 'warning',
|
||||
logger: 'test server',
|
||||
data: 'Warning message'
|
||||
};
|
||||
|
||||
// This one will not
|
||||
const debugParams: LoggingMessageNotification['params'] = {
|
||||
level: 'debug',
|
||||
logger: 'test server',
|
||||
data: 'Debug message'
|
||||
};
|
||||
|
||||
// Test the one that makes it through
|
||||
clientTransport.onmessage = vi.fn().mockImplementation(message => {
|
||||
expect(message).toEqual({
|
||||
jsonrpc: '2.0',
|
||||
method: 'notifications/message',
|
||||
params: warningParams
|
||||
});
|
||||
});
|
||||
|
||||
// This one will not make it through
|
||||
await server.sendLoggingMessage(debugParams, SESSION_ID);
|
||||
expect(clientTransport.onmessage).not.toHaveBeenCalled();
|
||||
|
||||
// This one will, triggering the above test in clientTransport.onmessage
|
||||
await server.sendLoggingMessage(warningParams, SESSION_ID);
|
||||
expect(clientTransport.onmessage).toHaveBeenCalled();
|
||||
});
|
||||
4519
src/server/v3/mcp.v3.test.ts
Normal file
4519
src/server/v3/mcp.v3.test.ts
Normal file
File diff suppressed because it is too large
Load diff
711
src/server/v3/sse.v3.test.ts
Normal file
711
src/server/v3/sse.v3.test.ts
Normal file
|
|
@ -0,0 +1,711 @@
|
|||
import http from 'http';
|
||||
import { type Mocked } from 'vitest';
|
||||
|
||||
import { SSEServerTransport } from '../sse.js';
|
||||
import { McpServer } from '../mcp.js';
|
||||
import { createServer, type Server } from 'node:http';
|
||||
import { AddressInfo } from 'node:net';
|
||||
import * as z from 'zod/v3';
|
||||
import { CallToolResult, JSONRPCMessage } from '../../types.js';
|
||||
|
||||
const createMockResponse = () => {
|
||||
const res = {
|
||||
writeHead: vi.fn<http.ServerResponse['writeHead']>().mockReturnThis(),
|
||||
write: vi.fn<http.ServerResponse['write']>().mockReturnThis(),
|
||||
on: vi.fn<http.ServerResponse['on']>().mockReturnThis(),
|
||||
end: vi.fn<http.ServerResponse['end']>().mockReturnThis()
|
||||
};
|
||||
|
||||
return res as unknown as Mocked<http.ServerResponse>;
|
||||
};
|
||||
|
||||
const createMockRequest = ({ headers = {}, body }: { headers?: Record<string, string>; body?: string } = {}) => {
|
||||
const mockReq = {
|
||||
headers,
|
||||
body: body ? body : undefined,
|
||||
auth: {
|
||||
token: 'test-token'
|
||||
},
|
||||
on: vi.fn<http.IncomingMessage['on']>().mockImplementation((event, listener) => {
|
||||
const mockListener = listener as unknown as (...args: unknown[]) => void;
|
||||
if (event === 'data') {
|
||||
mockListener(Buffer.from(body || '') as unknown as Error);
|
||||
}
|
||||
if (event === 'error') {
|
||||
mockListener(new Error('test'));
|
||||
}
|
||||
if (event === 'end') {
|
||||
mockListener();
|
||||
}
|
||||
if (event === 'close') {
|
||||
setTimeout(listener, 100);
|
||||
}
|
||||
return mockReq;
|
||||
}),
|
||||
listeners: vi.fn<http.IncomingMessage['listeners']>(),
|
||||
removeListener: vi.fn<http.IncomingMessage['removeListener']>()
|
||||
} as unknown as http.IncomingMessage;
|
||||
|
||||
return mockReq;
|
||||
};
|
||||
|
||||
/**
|
||||
* Helper to create and start test HTTP server with MCP setup
|
||||
*/
|
||||
async function createTestServerWithSse(args: { mockRes: http.ServerResponse }): Promise<{
|
||||
server: Server;
|
||||
transport: SSEServerTransport;
|
||||
mcpServer: McpServer;
|
||||
baseUrl: URL;
|
||||
sessionId: string;
|
||||
serverPort: number;
|
||||
}> {
|
||||
const mcpServer = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: { logging: {} } });
|
||||
|
||||
mcpServer.tool(
|
||||
'greet',
|
||||
'A simple greeting tool',
|
||||
{ name: z.string().describe('Name to greet') },
|
||||
async ({ name }): Promise<CallToolResult> => {
|
||||
return { content: [{ type: 'text', text: `Hello, ${name}!` }] };
|
||||
}
|
||||
);
|
||||
|
||||
const endpoint = '/messages';
|
||||
|
||||
const transport = new SSEServerTransport(endpoint, args.mockRes);
|
||||
const sessionId = transport.sessionId;
|
||||
|
||||
await mcpServer.connect(transport);
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
await transport.handlePostMessage(req, res);
|
||||
} catch (error) {
|
||||
console.error('Error handling request:', error);
|
||||
if (!res.headersSent) res.writeHead(500).end();
|
||||
}
|
||||
});
|
||||
|
||||
const baseUrl = await new Promise<URL>(resolve => {
|
||||
server.listen(0, '127.0.0.1', () => {
|
||||
const addr = server.address() as AddressInfo;
|
||||
resolve(new URL(`http://127.0.0.1:${addr.port}`));
|
||||
});
|
||||
});
|
||||
|
||||
const port = (server.address() as AddressInfo).port;
|
||||
|
||||
return { server, transport, mcpServer, baseUrl, sessionId, serverPort: port };
|
||||
}
|
||||
|
||||
async function readAllSSEEvents(response: Response): Promise<string[]> {
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) throw new Error('No readable stream');
|
||||
|
||||
const events: string[] = [];
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
if (value) {
|
||||
events.push(decoder.decode(value));
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper to send JSON-RPC request
|
||||
*/
|
||||
async function sendSsePostRequest(
|
||||
baseUrl: URL,
|
||||
message: JSONRPCMessage | JSONRPCMessage[],
|
||||
sessionId?: string,
|
||||
extraHeaders?: Record<string, string>
|
||||
): Promise<Response> {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json, text/event-stream',
|
||||
...extraHeaders
|
||||
};
|
||||
|
||||
if (sessionId) {
|
||||
baseUrl.searchParams.set('sessionId', sessionId);
|
||||
}
|
||||
|
||||
return fetch(baseUrl, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(message)
|
||||
});
|
||||
}
|
||||
|
||||
describe('SSEServerTransport', () => {
|
||||
async function initializeServer(baseUrl: URL): Promise<void> {
|
||||
const response = await sendSsePostRequest(baseUrl, {
|
||||
jsonrpc: '2.0',
|
||||
method: 'initialize',
|
||||
params: {
|
||||
clientInfo: { name: 'test-client', version: '1.0' },
|
||||
protocolVersion: '2025-03-26',
|
||||
capabilities: {}
|
||||
},
|
||||
|
||||
id: 'init-1'
|
||||
} as JSONRPCMessage);
|
||||
|
||||
expect(response.status).toBe(202);
|
||||
|
||||
const text = await readAllSSEEvents(response);
|
||||
|
||||
expect(text).toHaveLength(1);
|
||||
expect(text[0]).toBe('Accepted');
|
||||
}
|
||||
|
||||
describe('start method', () => {
|
||||
it('should correctly append sessionId to a simple relative endpoint', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const endpoint = '/messages';
|
||||
const transport = new SSEServerTransport(endpoint, mockRes);
|
||||
const expectedSessionId = transport.sessionId;
|
||||
|
||||
await transport.start();
|
||||
|
||||
expect(mockRes.writeHead).toHaveBeenCalledWith(200, expect.any(Object));
|
||||
expect(mockRes.write).toHaveBeenCalledTimes(1);
|
||||
expect(mockRes.write).toHaveBeenCalledWith(`event: endpoint\ndata: /messages?sessionId=${expectedSessionId}\n\n`);
|
||||
});
|
||||
|
||||
it('should correctly append sessionId to an endpoint with existing query parameters', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const endpoint = '/messages?foo=bar&baz=qux';
|
||||
const transport = new SSEServerTransport(endpoint, mockRes);
|
||||
const expectedSessionId = transport.sessionId;
|
||||
|
||||
await transport.start();
|
||||
|
||||
expect(mockRes.writeHead).toHaveBeenCalledWith(200, expect.any(Object));
|
||||
expect(mockRes.write).toHaveBeenCalledTimes(1);
|
||||
expect(mockRes.write).toHaveBeenCalledWith(
|
||||
`event: endpoint\ndata: /messages?foo=bar&baz=qux&sessionId=${expectedSessionId}\n\n`
|
||||
);
|
||||
});
|
||||
|
||||
it('should correctly append sessionId to an endpoint with a hash fragment', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const endpoint = '/messages#section1';
|
||||
const transport = new SSEServerTransport(endpoint, mockRes);
|
||||
const expectedSessionId = transport.sessionId;
|
||||
|
||||
await transport.start();
|
||||
|
||||
expect(mockRes.writeHead).toHaveBeenCalledWith(200, expect.any(Object));
|
||||
expect(mockRes.write).toHaveBeenCalledTimes(1);
|
||||
expect(mockRes.write).toHaveBeenCalledWith(`event: endpoint\ndata: /messages?sessionId=${expectedSessionId}#section1\n\n`);
|
||||
});
|
||||
|
||||
it('should correctly append sessionId to an endpoint with query parameters and a hash fragment', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const endpoint = '/messages?key=value#section2';
|
||||
const transport = new SSEServerTransport(endpoint, mockRes);
|
||||
const expectedSessionId = transport.sessionId;
|
||||
|
||||
await transport.start();
|
||||
|
||||
expect(mockRes.writeHead).toHaveBeenCalledWith(200, expect.any(Object));
|
||||
expect(mockRes.write).toHaveBeenCalledTimes(1);
|
||||
expect(mockRes.write).toHaveBeenCalledWith(
|
||||
`event: endpoint\ndata: /messages?key=value&sessionId=${expectedSessionId}#section2\n\n`
|
||||
);
|
||||
});
|
||||
|
||||
it('should correctly handle the root path endpoint "/"', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const endpoint = '/';
|
||||
const transport = new SSEServerTransport(endpoint, mockRes);
|
||||
const expectedSessionId = transport.sessionId;
|
||||
|
||||
await transport.start();
|
||||
|
||||
expect(mockRes.writeHead).toHaveBeenCalledWith(200, expect.any(Object));
|
||||
expect(mockRes.write).toHaveBeenCalledTimes(1);
|
||||
expect(mockRes.write).toHaveBeenCalledWith(`event: endpoint\ndata: /?sessionId=${expectedSessionId}\n\n`);
|
||||
});
|
||||
|
||||
it('should correctly handle an empty string endpoint ""', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const endpoint = '';
|
||||
const transport = new SSEServerTransport(endpoint, mockRes);
|
||||
const expectedSessionId = transport.sessionId;
|
||||
|
||||
await transport.start();
|
||||
|
||||
expect(mockRes.writeHead).toHaveBeenCalledWith(200, expect.any(Object));
|
||||
expect(mockRes.write).toHaveBeenCalledTimes(1);
|
||||
expect(mockRes.write).toHaveBeenCalledWith(`event: endpoint\ndata: /?sessionId=${expectedSessionId}\n\n`);
|
||||
});
|
||||
|
||||
/**
|
||||
* Test: Tool With Request Info
|
||||
*/
|
||||
it('should pass request info to tool callback', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const { mcpServer, baseUrl, sessionId, serverPort } = await createTestServerWithSse({ mockRes });
|
||||
await initializeServer(baseUrl);
|
||||
|
||||
mcpServer.tool(
|
||||
'test-request-info',
|
||||
'A simple test tool with request info',
|
||||
{ name: z.string().describe('Name to greet') },
|
||||
async ({ name }, { requestInfo }): Promise<CallToolResult> => {
|
||||
return {
|
||||
content: [
|
||||
{ type: 'text', text: `Hello, ${name}!` },
|
||||
{ type: 'text', text: `${JSON.stringify(requestInfo)}` }
|
||||
]
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
const toolCallMessage: JSONRPCMessage = {
|
||||
jsonrpc: '2.0',
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'test-request-info',
|
||||
arguments: {
|
||||
name: 'Test User'
|
||||
}
|
||||
},
|
||||
id: 'call-1'
|
||||
};
|
||||
|
||||
const response = await sendSsePostRequest(baseUrl, toolCallMessage, sessionId);
|
||||
|
||||
expect(response.status).toBe(202);
|
||||
|
||||
expect(mockRes.write).toHaveBeenCalledWith(`event: endpoint\ndata: /messages?sessionId=${sessionId}\n\n`);
|
||||
|
||||
const expectedMessage = {
|
||||
result: {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: 'Hello, Test User!'
|
||||
},
|
||||
{
|
||||
type: 'text',
|
||||
text: JSON.stringify({
|
||||
headers: {
|
||||
host: `127.0.0.1:${serverPort}`,
|
||||
connection: 'keep-alive',
|
||||
'content-type': 'application/json',
|
||||
accept: 'application/json, text/event-stream',
|
||||
'accept-language': '*',
|
||||
'sec-fetch-mode': 'cors',
|
||||
'user-agent': 'node',
|
||||
'accept-encoding': 'gzip, deflate',
|
||||
'content-length': '124'
|
||||
}
|
||||
})
|
||||
}
|
||||
]
|
||||
},
|
||||
jsonrpc: '2.0',
|
||||
id: 'call-1'
|
||||
};
|
||||
expect(mockRes.write).toHaveBeenCalledWith(`event: message\ndata: ${JSON.stringify(expectedMessage)}\n\n`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('handlePostMessage method', () => {
|
||||
it('should return 500 if server has not started', async () => {
|
||||
const mockReq = createMockRequest();
|
||||
const mockRes = createMockResponse();
|
||||
const endpoint = '/messages';
|
||||
const transport = new SSEServerTransport(endpoint, mockRes);
|
||||
|
||||
const error = 'SSE connection not established';
|
||||
await expect(transport.handlePostMessage(mockReq, mockRes)).rejects.toThrow(error);
|
||||
expect(mockRes.writeHead).toHaveBeenCalledWith(500);
|
||||
expect(mockRes.end).toHaveBeenCalledWith(error);
|
||||
});
|
||||
|
||||
it('should return 400 if content-type is not application/json', async () => {
|
||||
const mockReq = createMockRequest({ headers: { 'content-type': 'text/plain' } });
|
||||
const mockRes = createMockResponse();
|
||||
const endpoint = '/messages';
|
||||
const transport = new SSEServerTransport(endpoint, mockRes);
|
||||
await transport.start();
|
||||
|
||||
transport.onerror = vi.fn();
|
||||
const error = 'Unsupported content-type: text/plain';
|
||||
await expect(transport.handlePostMessage(mockReq, mockRes)).resolves.toBe(undefined);
|
||||
expect(mockRes.writeHead).toHaveBeenCalledWith(400);
|
||||
expect(mockRes.end).toHaveBeenCalledWith(expect.stringContaining(error));
|
||||
expect(transport.onerror).toHaveBeenCalledWith(new Error(error));
|
||||
});
|
||||
|
||||
it('should return 400 if message has not a valid schema', async () => {
|
||||
const invalidMessage = JSON.stringify({
|
||||
// missing jsonrpc field
|
||||
method: 'call',
|
||||
params: [1, 2, 3],
|
||||
id: 1
|
||||
});
|
||||
const mockReq = createMockRequest({
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: invalidMessage
|
||||
});
|
||||
const mockRes = createMockResponse();
|
||||
const endpoint = '/messages';
|
||||
const transport = new SSEServerTransport(endpoint, mockRes);
|
||||
await transport.start();
|
||||
|
||||
transport.onmessage = vi.fn();
|
||||
await transport.handlePostMessage(mockReq, mockRes);
|
||||
expect(mockRes.writeHead).toHaveBeenCalledWith(400);
|
||||
expect(transport.onmessage).not.toHaveBeenCalled();
|
||||
expect(mockRes.end).toHaveBeenCalledWith(`Invalid message: ${invalidMessage}`);
|
||||
});
|
||||
|
||||
it('should return 202 if message has a valid schema', async () => {
|
||||
const validMessage = JSON.stringify({
|
||||
jsonrpc: '2.0',
|
||||
method: 'call',
|
||||
params: {
|
||||
a: 1,
|
||||
b: 2,
|
||||
c: 3
|
||||
},
|
||||
id: 1
|
||||
});
|
||||
const mockReq = createMockRequest({
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: validMessage
|
||||
});
|
||||
const mockRes = createMockResponse();
|
||||
const endpoint = '/messages';
|
||||
const transport = new SSEServerTransport(endpoint, mockRes);
|
||||
await transport.start();
|
||||
|
||||
transport.onmessage = vi.fn();
|
||||
await transport.handlePostMessage(mockReq, mockRes);
|
||||
expect(mockRes.writeHead).toHaveBeenCalledWith(202);
|
||||
expect(mockRes.end).toHaveBeenCalledWith('Accepted');
|
||||
expect(transport.onmessage).toHaveBeenCalledWith(
|
||||
{
|
||||
jsonrpc: '2.0',
|
||||
method: 'call',
|
||||
params: {
|
||||
a: 1,
|
||||
b: 2,
|
||||
c: 3
|
||||
},
|
||||
id: 1
|
||||
},
|
||||
{
|
||||
authInfo: {
|
||||
token: 'test-token'
|
||||
},
|
||||
requestInfo: {
|
||||
headers: {
|
||||
'content-type': 'application/json'
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('close method', () => {
|
||||
it('should call onclose', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const endpoint = '/messages';
|
||||
const transport = new SSEServerTransport(endpoint, mockRes);
|
||||
await transport.start();
|
||||
transport.onclose = vi.fn();
|
||||
await transport.close();
|
||||
expect(transport.onclose).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('send method', () => {
|
||||
it('should call onsend', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const endpoint = '/messages';
|
||||
const transport = new SSEServerTransport(endpoint, mockRes);
|
||||
await transport.start();
|
||||
expect(mockRes.write).toHaveBeenCalledTimes(1);
|
||||
expect(mockRes.write).toHaveBeenCalledWith(expect.stringContaining('event: endpoint'));
|
||||
expect(mockRes.write).toHaveBeenCalledWith(expect.stringContaining(`data: /messages?sessionId=${transport.sessionId}`));
|
||||
});
|
||||
});
|
||||
|
||||
describe('DNS rebinding protection', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('Host header validation', () => {
|
||||
it('should accept requests with allowed host headers', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const transport = new SSEServerTransport('/messages', mockRes, {
|
||||
allowedHosts: ['localhost:3000', 'example.com'],
|
||||
enableDnsRebindingProtection: true
|
||||
});
|
||||
await transport.start();
|
||||
|
||||
const mockReq = createMockRequest({
|
||||
headers: {
|
||||
host: 'localhost:3000',
|
||||
'content-type': 'application/json'
|
||||
}
|
||||
});
|
||||
const mockHandleRes = createMockResponse();
|
||||
|
||||
await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' });
|
||||
|
||||
expect(mockHandleRes.writeHead).toHaveBeenCalledWith(202);
|
||||
expect(mockHandleRes.end).toHaveBeenCalledWith('Accepted');
|
||||
});
|
||||
|
||||
it('should reject requests with disallowed host headers', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const transport = new SSEServerTransport('/messages', mockRes, {
|
||||
allowedHosts: ['localhost:3000'],
|
||||
enableDnsRebindingProtection: true
|
||||
});
|
||||
await transport.start();
|
||||
|
||||
const mockReq = createMockRequest({
|
||||
headers: {
|
||||
host: 'evil.com',
|
||||
'content-type': 'application/json'
|
||||
}
|
||||
});
|
||||
const mockHandleRes = createMockResponse();
|
||||
|
||||
await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' });
|
||||
|
||||
expect(mockHandleRes.writeHead).toHaveBeenCalledWith(403);
|
||||
expect(mockHandleRes.end).toHaveBeenCalledWith('Invalid Host header: evil.com');
|
||||
});
|
||||
|
||||
it('should reject requests without host header when allowedHosts is configured', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const transport = new SSEServerTransport('/messages', mockRes, {
|
||||
allowedHosts: ['localhost:3000'],
|
||||
enableDnsRebindingProtection: true
|
||||
});
|
||||
await transport.start();
|
||||
|
||||
const mockReq = createMockRequest({
|
||||
headers: {
|
||||
'content-type': 'application/json'
|
||||
}
|
||||
});
|
||||
const mockHandleRes = createMockResponse();
|
||||
|
||||
await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' });
|
||||
|
||||
expect(mockHandleRes.writeHead).toHaveBeenCalledWith(403);
|
||||
expect(mockHandleRes.end).toHaveBeenCalledWith('Invalid Host header: undefined');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Origin header validation', () => {
|
||||
it('should accept requests with allowed origin headers', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const transport = new SSEServerTransport('/messages', mockRes, {
|
||||
allowedOrigins: ['http://localhost:3000', 'https://example.com'],
|
||||
enableDnsRebindingProtection: true
|
||||
});
|
||||
await transport.start();
|
||||
|
||||
const mockReq = createMockRequest({
|
||||
headers: {
|
||||
origin: 'http://localhost:3000',
|
||||
'content-type': 'application/json'
|
||||
}
|
||||
});
|
||||
const mockHandleRes = createMockResponse();
|
||||
|
||||
await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' });
|
||||
|
||||
expect(mockHandleRes.writeHead).toHaveBeenCalledWith(202);
|
||||
expect(mockHandleRes.end).toHaveBeenCalledWith('Accepted');
|
||||
});
|
||||
|
||||
it('should reject requests with disallowed origin headers', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const transport = new SSEServerTransport('/messages', mockRes, {
|
||||
allowedOrigins: ['http://localhost:3000'],
|
||||
enableDnsRebindingProtection: true
|
||||
});
|
||||
await transport.start();
|
||||
|
||||
const mockReq = createMockRequest({
|
||||
headers: {
|
||||
origin: 'http://evil.com',
|
||||
'content-type': 'application/json'
|
||||
}
|
||||
});
|
||||
const mockHandleRes = createMockResponse();
|
||||
|
||||
await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' });
|
||||
|
||||
expect(mockHandleRes.writeHead).toHaveBeenCalledWith(403);
|
||||
expect(mockHandleRes.end).toHaveBeenCalledWith('Invalid Origin header: http://evil.com');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Content-Type validation', () => {
|
||||
it('should accept requests with application/json content-type', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const transport = new SSEServerTransport('/messages', mockRes);
|
||||
await transport.start();
|
||||
|
||||
const mockReq = createMockRequest({
|
||||
headers: {
|
||||
'content-type': 'application/json'
|
||||
}
|
||||
});
|
||||
const mockHandleRes = createMockResponse();
|
||||
|
||||
await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' });
|
||||
|
||||
expect(mockHandleRes.writeHead).toHaveBeenCalledWith(202);
|
||||
expect(mockHandleRes.end).toHaveBeenCalledWith('Accepted');
|
||||
});
|
||||
|
||||
it('should accept requests with application/json with charset', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const transport = new SSEServerTransport('/messages', mockRes);
|
||||
await transport.start();
|
||||
|
||||
const mockReq = createMockRequest({
|
||||
headers: {
|
||||
'content-type': 'application/json; charset=utf-8'
|
||||
}
|
||||
});
|
||||
const mockHandleRes = createMockResponse();
|
||||
|
||||
await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' });
|
||||
|
||||
expect(mockHandleRes.writeHead).toHaveBeenCalledWith(202);
|
||||
expect(mockHandleRes.end).toHaveBeenCalledWith('Accepted');
|
||||
});
|
||||
|
||||
it('should reject requests with non-application/json content-type when protection is enabled', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const transport = new SSEServerTransport('/messages', mockRes);
|
||||
await transport.start();
|
||||
|
||||
const mockReq = createMockRequest({
|
||||
headers: {
|
||||
'content-type': 'text/plain'
|
||||
}
|
||||
});
|
||||
const mockHandleRes = createMockResponse();
|
||||
|
||||
await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' });
|
||||
|
||||
expect(mockHandleRes.writeHead).toHaveBeenCalledWith(400);
|
||||
expect(mockHandleRes.end).toHaveBeenCalledWith('Error: Unsupported content-type: text/plain');
|
||||
});
|
||||
});
|
||||
|
||||
describe('enableDnsRebindingProtection option', () => {
|
||||
it('should skip all validations when enableDnsRebindingProtection is false', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const transport = new SSEServerTransport('/messages', mockRes, {
|
||||
allowedHosts: ['localhost:3000'],
|
||||
allowedOrigins: ['http://localhost:3000'],
|
||||
enableDnsRebindingProtection: false
|
||||
});
|
||||
await transport.start();
|
||||
|
||||
const mockReq = createMockRequest({
|
||||
headers: {
|
||||
host: 'evil.com',
|
||||
origin: 'http://evil.com',
|
||||
'content-type': 'text/plain'
|
||||
}
|
||||
});
|
||||
const mockHandleRes = createMockResponse();
|
||||
|
||||
await transport.handlePostMessage(mockReq, mockHandleRes, { jsonrpc: '2.0', method: 'test' });
|
||||
|
||||
// Should pass even with invalid headers because protection is disabled
|
||||
expect(mockHandleRes.writeHead).toHaveBeenCalledWith(400);
|
||||
// The error should be from content-type parsing, not DNS rebinding protection
|
||||
expect(mockHandleRes.end).toHaveBeenCalledWith('Error: Unsupported content-type: text/plain');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Combined validations', () => {
|
||||
it('should validate both host and origin when both are configured', async () => {
|
||||
const mockRes = createMockResponse();
|
||||
const transport = new SSEServerTransport('/messages', mockRes, {
|
||||
allowedHosts: ['localhost:3000'],
|
||||
allowedOrigins: ['http://localhost:3000'],
|
||||
enableDnsRebindingProtection: true
|
||||
});
|
||||
await transport.start();
|
||||
|
||||
// Valid host, invalid origin
|
||||
const mockReq1 = createMockRequest({
|
||||
headers: {
|
||||
host: 'localhost:3000',
|
||||
origin: 'http://evil.com',
|
||||
'content-type': 'application/json'
|
||||
}
|
||||
});
|
||||
const mockHandleRes1 = createMockResponse();
|
||||
|
||||
await transport.handlePostMessage(mockReq1, mockHandleRes1, { jsonrpc: '2.0', method: 'test' });
|
||||
|
||||
expect(mockHandleRes1.writeHead).toHaveBeenCalledWith(403);
|
||||
expect(mockHandleRes1.end).toHaveBeenCalledWith('Invalid Origin header: http://evil.com');
|
||||
|
||||
// Invalid host, valid origin
|
||||
const mockReq2 = createMockRequest({
|
||||
headers: {
|
||||
host: 'evil.com',
|
||||
origin: 'http://localhost:3000',
|
||||
'content-type': 'application/json'
|
||||
}
|
||||
});
|
||||
const mockHandleRes2 = createMockResponse();
|
||||
|
||||
await transport.handlePostMessage(mockReq2, mockHandleRes2, { jsonrpc: '2.0', method: 'test' });
|
||||
|
||||
expect(mockHandleRes2.writeHead).toHaveBeenCalledWith(403);
|
||||
expect(mockHandleRes2.end).toHaveBeenCalledWith('Invalid Host header: evil.com');
|
||||
|
||||
// Both valid
|
||||
const mockReq3 = createMockRequest({
|
||||
headers: {
|
||||
host: 'localhost:3000',
|
||||
origin: 'http://localhost:3000',
|
||||
'content-type': 'application/json'
|
||||
}
|
||||
});
|
||||
const mockHandleRes3 = createMockResponse();
|
||||
|
||||
await transport.handlePostMessage(mockReq3, mockHandleRes3, { jsonrpc: '2.0', method: 'test' });
|
||||
|
||||
expect(mockHandleRes3.writeHead).toHaveBeenCalledWith(202);
|
||||
expect(mockHandleRes3.end).toHaveBeenCalledWith('Accepted');
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
2151
src/server/v3/streamableHttp.v3.test.ts
Normal file
2151
src/server/v3/streamableHttp.v3.test.ts
Normal file
File diff suppressed because it is too large
Load diff
224
src/server/v3/title.v3.test.ts
Normal file
224
src/server/v3/title.v3.test.ts
Normal file
|
|
@ -0,0 +1,224 @@
|
|||
import { Server } from '../index.js';
|
||||
import { Client } from '../../client/index.js';
|
||||
import { InMemoryTransport } from '../../inMemory.js';
|
||||
import * as z from 'zod/v3';
|
||||
import { McpServer, ResourceTemplate } from '../mcp.js';
|
||||
|
||||
describe('Title field backwards compatibility', () => {
|
||||
it('should work with tools that have title', async () => {
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
const server = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: {} });
|
||||
|
||||
// Register tool with title
|
||||
server.registerTool(
|
||||
'test-tool',
|
||||
{
|
||||
title: 'Test Tool Display Name',
|
||||
description: 'A test tool',
|
||||
inputSchema: {
|
||||
value: z.string()
|
||||
}
|
||||
},
|
||||
async () => ({ content: [{ type: 'text', text: 'result' }] })
|
||||
);
|
||||
|
||||
const client = new Client({ name: 'test-client', version: '1.0.0' });
|
||||
|
||||
await server.server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const tools = await client.listTools();
|
||||
expect(tools.tools).toHaveLength(1);
|
||||
expect(tools.tools[0].name).toBe('test-tool');
|
||||
expect(tools.tools[0].title).toBe('Test Tool Display Name');
|
||||
expect(tools.tools[0].description).toBe('A test tool');
|
||||
});
|
||||
|
||||
it('should work with tools without title', async () => {
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
const server = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: {} });
|
||||
|
||||
// Register tool without title
|
||||
server.tool('test-tool', 'A test tool', { value: z.string() }, async () => ({ content: [{ type: 'text', text: 'result' }] }));
|
||||
|
||||
const client = new Client({ name: 'test-client', version: '1.0.0' });
|
||||
|
||||
await server.server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const tools = await client.listTools();
|
||||
expect(tools.tools).toHaveLength(1);
|
||||
expect(tools.tools[0].name).toBe('test-tool');
|
||||
expect(tools.tools[0].title).toBeUndefined();
|
||||
expect(tools.tools[0].description).toBe('A test tool');
|
||||
});
|
||||
|
||||
it('should work with prompts that have title using update', async () => {
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
const server = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: {} });
|
||||
|
||||
// Register prompt with title by updating after creation
|
||||
const prompt = server.prompt('test-prompt', 'A test prompt', async () => ({
|
||||
messages: [{ role: 'user', content: { type: 'text', text: 'test' } }]
|
||||
}));
|
||||
prompt.update({ title: 'Test Prompt Display Name' });
|
||||
|
||||
const client = new Client({ name: 'test-client', version: '1.0.0' });
|
||||
|
||||
await server.server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const prompts = await client.listPrompts();
|
||||
expect(prompts.prompts).toHaveLength(1);
|
||||
expect(prompts.prompts[0].name).toBe('test-prompt');
|
||||
expect(prompts.prompts[0].title).toBe('Test Prompt Display Name');
|
||||
expect(prompts.prompts[0].description).toBe('A test prompt');
|
||||
});
|
||||
|
||||
it('should work with prompts using registerPrompt', async () => {
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
const server = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: {} });
|
||||
|
||||
// Register prompt with title using registerPrompt
|
||||
server.registerPrompt(
|
||||
'test-prompt',
|
||||
{
|
||||
title: 'Test Prompt Display Name',
|
||||
description: 'A test prompt',
|
||||
argsSchema: { input: z.string() }
|
||||
},
|
||||
async ({ input }) => ({
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: { type: 'text', text: `test: ${input}` }
|
||||
}
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
const client = new Client({ name: 'test-client', version: '1.0.0' });
|
||||
|
||||
await server.server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const prompts = await client.listPrompts();
|
||||
expect(prompts.prompts).toHaveLength(1);
|
||||
expect(prompts.prompts[0].name).toBe('test-prompt');
|
||||
expect(prompts.prompts[0].title).toBe('Test Prompt Display Name');
|
||||
expect(prompts.prompts[0].description).toBe('A test prompt');
|
||||
expect(prompts.prompts[0].arguments).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('should work with resources using registerResource', async () => {
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
const server = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: {} });
|
||||
|
||||
// Register resource with title using registerResource
|
||||
server.registerResource(
|
||||
'test-resource',
|
||||
'https://example.com/test',
|
||||
{
|
||||
title: 'Test Resource Display Name',
|
||||
description: 'A test resource',
|
||||
mimeType: 'text/plain'
|
||||
},
|
||||
async () => ({
|
||||
contents: [
|
||||
{
|
||||
uri: 'https://example.com/test',
|
||||
text: 'test content'
|
||||
}
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
const client = new Client({ name: 'test-client', version: '1.0.0' });
|
||||
|
||||
await server.server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const resources = await client.listResources();
|
||||
expect(resources.resources).toHaveLength(1);
|
||||
expect(resources.resources[0].name).toBe('test-resource');
|
||||
expect(resources.resources[0].title).toBe('Test Resource Display Name');
|
||||
expect(resources.resources[0].description).toBe('A test resource');
|
||||
expect(resources.resources[0].mimeType).toBe('text/plain');
|
||||
});
|
||||
|
||||
it('should work with dynamic resources using registerResource', async () => {
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
const server = new McpServer({ name: 'test-server', version: '1.0.0' }, { capabilities: {} });
|
||||
|
||||
// Register dynamic resource with title using registerResource
|
||||
server.registerResource(
|
||||
'user-profile',
|
||||
new ResourceTemplate('users://{userId}/profile', { list: undefined }),
|
||||
{
|
||||
title: 'User Profile',
|
||||
description: 'User profile information'
|
||||
},
|
||||
async (uri, { userId }, _extra) => ({
|
||||
contents: [
|
||||
{
|
||||
uri: uri.href,
|
||||
text: `Profile data for user ${userId}`
|
||||
}
|
||||
]
|
||||
})
|
||||
);
|
||||
|
||||
const client = new Client({ name: 'test-client', version: '1.0.0' });
|
||||
|
||||
await server.server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const resourceTemplates = await client.listResourceTemplates();
|
||||
expect(resourceTemplates.resourceTemplates).toHaveLength(1);
|
||||
expect(resourceTemplates.resourceTemplates[0].name).toBe('user-profile');
|
||||
expect(resourceTemplates.resourceTemplates[0].title).toBe('User Profile');
|
||||
expect(resourceTemplates.resourceTemplates[0].description).toBe('User profile information');
|
||||
expect(resourceTemplates.resourceTemplates[0].uriTemplate).toBe('users://{userId}/profile');
|
||||
|
||||
// Test reading the resource
|
||||
const readResult = await client.readResource({ uri: 'users://123/profile' });
|
||||
expect(readResult.contents).toHaveLength(1);
|
||||
expect(readResult.contents).toEqual(
|
||||
expect.arrayContaining([
|
||||
{
|
||||
text: expect.stringContaining('Profile data for user 123'),
|
||||
uri: 'users://123/profile'
|
||||
}
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it('should support serverInfo with title', async () => {
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
|
||||
const server = new Server(
|
||||
{
|
||||
name: 'test-server',
|
||||
version: '1.0.0',
|
||||
title: 'Test Server Display Name'
|
||||
},
|
||||
{ capabilities: {} }
|
||||
);
|
||||
|
||||
const client = new Client({ name: 'test-client', version: '1.0.0' });
|
||||
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const serverInfo = client.getServerVersion();
|
||||
expect(serverInfo?.name).toBe('test-server');
|
||||
expect(serverInfo?.version).toBe('1.0.0');
|
||||
expect(serverInfo?.title).toBe('Test Server Display Name');
|
||||
});
|
||||
});
|
||||
280
src/server/zod-compat.ts
Normal file
280
src/server/zod-compat.ts
Normal file
|
|
@ -0,0 +1,280 @@
|
|||
// zod-compat.ts
|
||||
// ----------------------------------------------------
|
||||
// Unified types + helpers to accept Zod v3 and v4 (Mini)
|
||||
// ----------------------------------------------------
|
||||
|
||||
import type * as z3 from 'zod/v3';
|
||||
import type * as z4 from 'zod/v4/core';
|
||||
|
||||
import * as z3rt from 'zod/v3';
|
||||
import * as z4mini from 'zod/v4-mini';
|
||||
|
||||
// --- Unified schema types ---
|
||||
export type AnySchema = z3.ZodTypeAny | z4.$ZodType;
|
||||
export type AnyObjectSchema = z3.AnyZodObject | z4.$ZodObject | AnySchema;
|
||||
export type ZodRawShapeCompat = Record<string, AnySchema>;
|
||||
|
||||
// --- Internal property access helpers ---
|
||||
// These types help us safely access internal properties that differ between v3 and v4
|
||||
export interface ZodV3Internal {
|
||||
_def?: {
|
||||
typeName?: string;
|
||||
value?: unknown;
|
||||
values?: unknown[];
|
||||
shape?: Record<string, AnySchema> | (() => Record<string, AnySchema>);
|
||||
description?: string;
|
||||
};
|
||||
shape?: Record<string, AnySchema> | (() => Record<string, AnySchema>);
|
||||
value?: unknown;
|
||||
}
|
||||
|
||||
export interface ZodV4Internal {
|
||||
_zod?: {
|
||||
def?: {
|
||||
typeName?: string;
|
||||
value?: unknown;
|
||||
values?: unknown[];
|
||||
shape?: Record<string, AnySchema> | (() => Record<string, AnySchema>);
|
||||
description?: string;
|
||||
};
|
||||
};
|
||||
value?: unknown;
|
||||
}
|
||||
|
||||
// --- Type inference helpers ---
|
||||
export type SchemaOutput<S> = S extends z3.ZodTypeAny ? z3.infer<S> : S extends z4.$ZodType ? z4.output<S> : never;
|
||||
|
||||
export type SchemaInput<S> = S extends z3.ZodTypeAny ? z3.input<S> : S extends z4.$ZodType ? z4.input<S> : never;
|
||||
|
||||
/**
|
||||
* Infers the output type from a ZodRawShapeCompat (raw shape object).
|
||||
* Maps over each key in the shape and infers the output type from each schema.
|
||||
*/
|
||||
export type ShapeOutput<Shape extends ZodRawShapeCompat> = {
|
||||
[K in keyof Shape]: SchemaOutput<Shape[K]>;
|
||||
};
|
||||
|
||||
// --- Runtime detection ---
|
||||
export function isZ4Schema(s: AnySchema): s is z4.$ZodType {
|
||||
// Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3
|
||||
const schema = s as unknown as ZodV4Internal;
|
||||
return !!schema._zod;
|
||||
}
|
||||
|
||||
// --- Schema construction ---
|
||||
export function objectFromShape(shape: ZodRawShapeCompat): AnyObjectSchema {
|
||||
const values = Object.values(shape);
|
||||
if (values.length === 0) return z4mini.object({}); // default to v4 Mini
|
||||
|
||||
const allV4 = values.every(isZ4Schema);
|
||||
const allV3 = values.every(s => !isZ4Schema(s));
|
||||
|
||||
if (allV4) return z4mini.object(shape as Record<string, z4.$ZodType>);
|
||||
if (allV3) return z3rt.object(shape as Record<string, z3.ZodTypeAny>);
|
||||
|
||||
throw new Error('Mixed Zod versions detected in object shape.');
|
||||
}
|
||||
|
||||
// --- Unified parsing ---
|
||||
export function safeParse<S extends AnySchema>(
|
||||
schema: S,
|
||||
data: unknown
|
||||
): { success: true; data: SchemaOutput<S> } | { success: false; error: unknown } {
|
||||
if (isZ4Schema(schema)) {
|
||||
// Mini exposes top-level safeParse
|
||||
const result = z4mini.safeParse(schema, data);
|
||||
return result as { success: true; data: SchemaOutput<S> } | { success: false; error: unknown };
|
||||
}
|
||||
const v3Schema = schema as z3.ZodTypeAny;
|
||||
const result = v3Schema.safeParse(data);
|
||||
return result as { success: true; data: SchemaOutput<S> } | { success: false; error: unknown };
|
||||
}
|
||||
|
||||
export async function safeParseAsync<S extends AnySchema>(
|
||||
schema: S,
|
||||
data: unknown
|
||||
): Promise<{ success: true; data: SchemaOutput<S> } | { success: false; error: unknown }> {
|
||||
if (isZ4Schema(schema)) {
|
||||
// Mini exposes top-level safeParseAsync
|
||||
const result = await z4mini.safeParseAsync(schema, data);
|
||||
return result as { success: true; data: SchemaOutput<S> } | { success: false; error: unknown };
|
||||
}
|
||||
const v3Schema = schema as z3.ZodTypeAny;
|
||||
const result = await v3Schema.safeParseAsync(data);
|
||||
return result as { success: true; data: SchemaOutput<S> } | { success: false; error: unknown };
|
||||
}
|
||||
|
||||
// --- Shape extraction ---
|
||||
export function getObjectShape(schema: AnyObjectSchema | undefined): Record<string, AnySchema> | undefined {
|
||||
if (!schema) return undefined;
|
||||
|
||||
// Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape`
|
||||
let rawShape: Record<string, AnySchema> | (() => Record<string, AnySchema>) | undefined;
|
||||
|
||||
if (isZ4Schema(schema)) {
|
||||
const v4Schema = schema as unknown as ZodV4Internal;
|
||||
rawShape = v4Schema._zod?.def?.shape;
|
||||
} else {
|
||||
const v3Schema = schema as unknown as ZodV3Internal;
|
||||
rawShape = v3Schema.shape;
|
||||
}
|
||||
|
||||
if (!rawShape) return undefined;
|
||||
|
||||
if (typeof rawShape === 'function') {
|
||||
try {
|
||||
return rawShape();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
return rawShape;
|
||||
}
|
||||
|
||||
// --- Schema normalization ---
|
||||
/**
|
||||
* Normalizes a schema to an object schema. Handles both:
|
||||
* - Already-constructed object schemas (v3 or v4)
|
||||
* - Raw shapes that need to be wrapped into object schemas
|
||||
*/
|
||||
export function normalizeObjectSchema(schema: AnySchema | ZodRawShapeCompat | undefined): AnyObjectSchema | undefined {
|
||||
if (!schema) return undefined;
|
||||
|
||||
// First check if it's a raw shape (Record<string, AnySchema>)
|
||||
// Raw shapes don't have _def or _zod properties and aren't schemas themselves
|
||||
if (typeof schema === 'object') {
|
||||
// Check if it's actually a ZodRawShapeCompat (not a schema instance)
|
||||
// by checking if it lacks schema-like internal properties
|
||||
const asV3 = schema as unknown as ZodV3Internal;
|
||||
const asV4 = schema as unknown as ZodV4Internal;
|
||||
|
||||
// If it's not a schema instance (no _def or _zod), it might be a raw shape
|
||||
if (!asV3._def && !asV4._zod) {
|
||||
// Check if all values are schemas (heuristic to confirm it's a raw shape)
|
||||
const values = Object.values(schema);
|
||||
if (
|
||||
values.length > 0 &&
|
||||
values.every(
|
||||
v =>
|
||||
typeof v === 'object' &&
|
||||
v !== null &&
|
||||
((v as unknown as ZodV3Internal)._def !== undefined ||
|
||||
(v as unknown as ZodV4Internal)._zod !== undefined ||
|
||||
typeof (v as { parse?: unknown }).parse === 'function')
|
||||
)
|
||||
) {
|
||||
return objectFromShape(schema as ZodRawShapeCompat);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we get here, it should be an AnySchema (not a raw shape)
|
||||
// Check if it's already an object schema
|
||||
if (isZ4Schema(schema as AnySchema)) {
|
||||
// Check if it's a v4 object
|
||||
const v4Schema = schema as unknown as ZodV4Internal;
|
||||
const def = v4Schema._zod?.def;
|
||||
if (def && (def.typeName === 'object' || def.shape !== undefined)) {
|
||||
return schema as AnyObjectSchema;
|
||||
}
|
||||
} else {
|
||||
// Check if it's a v3 object
|
||||
const v3Schema = schema as unknown as ZodV3Internal;
|
||||
if (v3Schema.shape !== undefined) {
|
||||
return schema as AnyObjectSchema;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// --- Error message extraction ---
|
||||
/**
|
||||
* Safely extracts an error message from a parse result error.
|
||||
* Zod errors can have different structures, so we handle various cases.
|
||||
*/
|
||||
export function getParseErrorMessage(error: unknown): string {
|
||||
if (error && typeof error === 'object') {
|
||||
// Try common error structures
|
||||
if ('message' in error && typeof error.message === 'string') {
|
||||
return error.message;
|
||||
}
|
||||
if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) {
|
||||
const firstIssue = error.issues[0];
|
||||
if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) {
|
||||
return String(firstIssue.message);
|
||||
}
|
||||
}
|
||||
// Fallback: try to stringify the error
|
||||
try {
|
||||
return JSON.stringify(error);
|
||||
} catch {
|
||||
return String(error);
|
||||
}
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
|
||||
// --- Schema metadata access ---
|
||||
/**
|
||||
* Gets the description from a schema, if available.
|
||||
* Works with both Zod v3 and v4.
|
||||
*/
|
||||
export function getSchemaDescription(schema: AnySchema): string | undefined {
|
||||
if (isZ4Schema(schema)) {
|
||||
const v4Schema = schema as unknown as ZodV4Internal;
|
||||
return v4Schema._zod?.def?.description;
|
||||
}
|
||||
const v3Schema = schema as unknown as ZodV3Internal;
|
||||
// v3 may have description on the schema itself or in _def
|
||||
return (schema as { description?: string }).description ?? v3Schema._def?.description;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a schema is optional.
|
||||
* Works with both Zod v3 and v4.
|
||||
*/
|
||||
export function isSchemaOptional(schema: AnySchema): boolean {
|
||||
if (isZ4Schema(schema)) {
|
||||
const v4Schema = schema as unknown as ZodV4Internal;
|
||||
return v4Schema._zod?.def?.typeName === 'ZodOptional';
|
||||
}
|
||||
const v3Schema = schema as unknown as ZodV3Internal;
|
||||
// v3 has isOptional() method
|
||||
if (typeof (schema as { isOptional?: () => boolean }).isOptional === 'function') {
|
||||
return (schema as { isOptional: () => boolean }).isOptional();
|
||||
}
|
||||
return v3Schema._def?.typeName === 'ZodOptional';
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the literal value from a schema, if it's a literal schema.
|
||||
* Works with both Zod v3 and v4.
|
||||
* Returns undefined if the schema is not a literal or the value cannot be determined.
|
||||
*/
|
||||
export function getLiteralValue(schema: AnySchema): unknown {
|
||||
if (isZ4Schema(schema)) {
|
||||
const v4Schema = schema as unknown as ZodV4Internal;
|
||||
const def = v4Schema._zod?.def;
|
||||
if (def) {
|
||||
// Try various ways to get the literal value
|
||||
if (def.value !== undefined) return def.value;
|
||||
if (Array.isArray(def.values) && def.values.length > 0) {
|
||||
return def.values[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
const v3Schema = schema as unknown as ZodV3Internal;
|
||||
const def = v3Schema._def;
|
||||
if (def) {
|
||||
if (def.value !== undefined) return def.value;
|
||||
if (Array.isArray(def.values) && def.values.length > 0) {
|
||||
return def.values[0];
|
||||
}
|
||||
}
|
||||
// Fallback: check for direct value property (some Zod versions)
|
||||
const directValue = (schema as { value?: unknown }).value;
|
||||
if (directValue !== undefined) return directValue;
|
||||
return undefined;
|
||||
}
|
||||
68
src/server/zod-json-schema-compat.ts
Normal file
68
src/server/zod-json-schema-compat.ts
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
// zod-json-schema-compat.ts
|
||||
// ----------------------------------------------------
|
||||
// JSON Schema conversion for both Zod v3 and Zod v4 (Mini)
|
||||
// v3 uses your vendored converter; v4 uses Mini's toJSONSchema
|
||||
// ----------------------------------------------------
|
||||
|
||||
import type * as z3 from 'zod/v3';
|
||||
import type * as z4c from 'zod/v4/core';
|
||||
|
||||
import * as z4mini from 'zod/v4-mini';
|
||||
|
||||
import { AnySchema, AnyObjectSchema, getObjectShape, safeParse, isZ4Schema, getLiteralValue } from './zod-compat.js';
|
||||
import { zodToJsonSchema } from 'zod-to-json-schema';
|
||||
|
||||
type JsonSchema = Record<string, unknown>;
|
||||
|
||||
// Options accepted by call sites; we map them appropriately
|
||||
type CommonOpts = {
|
||||
strictUnions?: boolean;
|
||||
pipeStrategy?: 'input' | 'output';
|
||||
target?: 'jsonSchema7' | 'draft-7' | 'jsonSchema2019-09' | 'draft-2020-12';
|
||||
};
|
||||
|
||||
function mapMiniTarget(t: CommonOpts['target'] | undefined): 'draft-7' | 'draft-2020-12' {
|
||||
if (!t) return 'draft-7';
|
||||
if (t === 'jsonSchema7' || t === 'draft-7') return 'draft-7';
|
||||
if (t === 'jsonSchema2019-09' || t === 'draft-2020-12') return 'draft-2020-12';
|
||||
return 'draft-7'; // fallback
|
||||
}
|
||||
|
||||
export function toJsonSchemaCompat(schema: AnyObjectSchema, opts?: CommonOpts): JsonSchema {
|
||||
if (isZ4Schema(schema)) {
|
||||
// v4 branch — use Mini's built-in toJSONSchema
|
||||
return z4mini.toJSONSchema(schema as z4c.$ZodType, {
|
||||
target: mapMiniTarget(opts?.target),
|
||||
io: opts?.pipeStrategy ?? 'input'
|
||||
}) as JsonSchema;
|
||||
}
|
||||
|
||||
// v3 branch — use vendored converter
|
||||
return zodToJsonSchema(schema as z3.ZodTypeAny, {
|
||||
strictUnions: opts?.strictUnions ?? true,
|
||||
pipeStrategy: opts?.pipeStrategy ?? 'input'
|
||||
}) as JsonSchema;
|
||||
}
|
||||
|
||||
export function getMethodLiteral(schema: AnyObjectSchema): string {
|
||||
const shape = getObjectShape(schema);
|
||||
const methodSchema = shape?.method as AnySchema | undefined;
|
||||
if (!methodSchema) {
|
||||
throw new Error('Schema is missing a method literal');
|
||||
}
|
||||
|
||||
const value = getLiteralValue(methodSchema);
|
||||
if (typeof value !== 'string') {
|
||||
throw new Error('Schema method literal must be a string');
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export function parseWithCompat(schema: AnySchema, data: unknown): unknown {
|
||||
const result = safeParse(schema, data);
|
||||
if (!result.success) {
|
||||
throw result.error;
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
Loading…
Reference in a new issue