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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ export default {
"/node_modules/(?!eventsource)/"
],
testPathIgnorePatterns: ["/node_modules/", "/dist/"],
modulePathIgnorePatterns: ["<rootDir>/dist"],
};
18 changes: 4 additions & 14 deletions package-lock.json

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

5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,7 @@
"express-rate-limit": "^7.5.0",
"pkce-challenge": "^5.0.0",
"raw-body": "^3.0.0",
"zod": "^3.23.8",
"zod-to-json-schema": "^3.24.1"
"zod": "^4.1.9"
},
"devDependencies": {
"@eslint/js": "^9.8.0",
Expand All @@ -100,4 +99,4 @@
"resolutions": {
"strip-ansi": "6.0.1"
}
}
}
2 changes: 1 addition & 1 deletion src/client/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
/* eslint-disable no-constant-binary-expression */
/* eslint-disable @typescript-eslint/no-unused-expressions */
import { Client } from "./index.js";
import { z } from "zod";
import { z } from "zod/v4";
import {
RequestSchema,
NotificationSchema,
Expand Down
2 changes: 1 addition & 1 deletion src/examples/server/jsonResponseStreamableHttp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import express, { Request, Response } from 'express';
import { randomUUID } from 'node:crypto';
import { McpServer } from '../../server/mcp.js';
import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js';
import { z } from 'zod';
import { z } from 'zod/v4';
import { CallToolResult, isInitializeRequest } from '../../types.js';
import cors from 'cors';

Expand Down
2 changes: 1 addition & 1 deletion src/examples/server/mcpServerOutputSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import { McpServer } from "../../server/mcp.js";
import { StdioServerTransport } from "../../server/stdio.js";
import { z } from "zod";
import { z } from "zod/v4";

const server = new McpServer(
{
Expand Down
2 changes: 1 addition & 1 deletion src/examples/server/simpleSseServer.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import express, { Request, Response } from 'express';
import { McpServer } from '../../server/mcp.js';
import { SSEServerTransport } from '../../server/sse.js';
import { z } from 'zod';
import { z } from 'zod/v4';
import { CallToolResult } from '../../types.js';

/**
Expand Down
2 changes: 1 addition & 1 deletion src/examples/server/simpleStatelessStreamableHttp.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import express, { Request, Response } from 'express';
import { McpServer } from '../../server/mcp.js';
import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js';
import { z } from 'zod';
import { z } from 'zod/v4';
import { CallToolResult, GetPromptResult, ReadResourceResult } from '../../types.js';
import cors from 'cors';

Expand Down
2 changes: 1 addition & 1 deletion src/examples/server/simpleStreamableHttp.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import express, { Request, Response } from 'express';
import { randomUUID } from 'node:crypto';
import { z } from 'zod';
import { z } from 'zod/v4';
import { McpServer } from '../../server/mcp.js';
import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js';
import { getOAuthProtectedResourceMetadataUrl, mcpAuthMetadataRouter } from '../../server/auth/router.js';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { randomUUID } from "node:crypto";
import { McpServer } from '../../server/mcp.js';
import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js';
import { SSEServerTransport } from '../../server/sse.js';
import { z } from 'zod';
import { z } from 'zod/v4';
import { CallToolResult, isInitializeRequest } from '../../types.js';
import { InMemoryEventStore } from '../shared/inMemoryEventStore.js';
import cors from 'cors';
Expand Down
2 changes: 1 addition & 1 deletion src/examples/server/toolWithSampleServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

import { McpServer } from "../../server/mcp.js";
import { StdioServerTransport } from "../../server/stdio.js";
import { z } from "zod";
import { z } from "zod/v4";

const mcpServer = new McpServer({
name: "tools-with-sample-server",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { StreamableHTTPClientTransport } from '../client/streamableHttp.js';
import { McpServer } from '../server/mcp.js';
import { StreamableHTTPServerTransport } from '../server/streamableHttp.js';
import { CallToolResultSchema, ListToolsResultSchema, ListResourcesResultSchema, ListPromptsResultSchema, LATEST_PROTOCOL_VERSION } from '../types.js';
import { z } from 'zod';
import { z } from 'zod/v4';

describe('Streamable HTTP Transport Session Management', () => {
// Function to set up the server with optional session management
Expand Down
2 changes: 1 addition & 1 deletion src/integration-tests/taskResumability.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { StreamableHTTPClientTransport } from '../client/streamableHttp.js';
import { McpServer } from '../server/mcp.js';
import { StreamableHTTPServerTransport } from '../server/streamableHttp.js';
import { CallToolResultSchema, LoggingMessageNotificationSchema } from '../types.js';
import { z } from 'zod';
import { z } from 'zod/v4';
import { InMemoryEventStore } from '../examples/shared/inMemoryEventStore.js';


Expand Down
8 changes: 5 additions & 3 deletions src/server/auth/handlers/authorize.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { RequestHandler } from "express";
import { z } from "zod";
import { z } from "zod/v4";
import express from "express";
import { OAuthServerProvider } from "../provider.js";
import { rateLimit, Options as RateLimitOptions } from "express-rate-limit";
Expand All @@ -25,7 +25,9 @@ export type AuthorizationHandlerOptions = {
// Parameters that must be validated in order to issue redirects.
const ClientAuthorizationParamsSchema = z.object({
client_id: z.string(),
redirect_uri: z.string().optional().refine((value) => value === undefined || URL.canParse(value), { message: "redirect_uri must be a valid URL" }),
redirect_uri: z.string().optional().refine((value) => value === undefined || URL.canParse(value), {
error: "redirect_uri must be a valid URL"
}),
});

// Parameters that must be validated for a successful authorization request. Failure can be reported to the redirect URI.
Expand All @@ -35,7 +37,7 @@ const RequestAuthorizationParamsSchema = z.object({
code_challenge_method: z.literal("S256"),
scope: z.string().optional(),
state: z.string().optional(),
resource: z.string().url().optional(),
resource: z.url().optional(),
});

export function authorizationHandler({ provider, rateLimit: rateLimitConfig }: AuthorizationHandlerOptions): RequestHandler {
Expand Down
6 changes: 3 additions & 3 deletions src/server/auth/handlers/token.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { z } from "zod";
import { z } from "zod/v4";
import express, { RequestHandler } from "express";
import { OAuthServerProvider } from "../provider.js";
import cors from "cors";
Expand Down Expand Up @@ -32,13 +32,13 @@ const AuthorizationCodeGrantSchema = z.object({
code: z.string(),
code_verifier: z.string(),
redirect_uri: z.string().optional(),
resource: z.string().url().optional(),
resource: z.url().optional(),
});

const RefreshTokenGrantSchema = z.object({
refresh_token: z.string(),
scope: z.string().optional(),
resource: z.string().url().optional(),
resource: z.url().optional(),
});

export function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHandlerOptions): RequestHandler {
Expand Down
2 changes: 1 addition & 1 deletion src/server/auth/middleware/clientAuth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { z } from "zod";
import { z } from "zod/v4";
import { RequestHandler } from "express";
import { OAuthRegisteredClientsStore } from "../clients.js";
import { OAuthClientInformationFull } from "../../../shared/auth.js";
Expand Down
2 changes: 1 addition & 1 deletion src/server/completable.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { z } from "zod";
import { z } from "zod/v4";
import { completable } from "./completable.js";

describe("completable", () => {
Expand Down
95 changes: 21 additions & 74 deletions src/server/completable.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,4 @@
import {
ZodTypeAny,
ZodTypeDef,
ZodType,
ParseInput,
ParseReturnType,
RawCreateParams,
ZodErrorMap,
ProcessedCreateParams,
} from "zod";
import { ZodTypeAny } from "zod/v4";

export enum McpZodTypeKind {
Completable = "McpCompletable",
Expand All @@ -17,82 +8,38 @@ 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 ZodTypeAny = ZodTypeAny> {
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.`,
);
complete: CompleteCallback<T>
): T & {
_def: (T extends { _def: infer D } ? D : unknown) & CompletableDef<T>;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

first of all I want to claim that I am not a part of the mcp organization so I hope I am not a blocking phase for this feature. I really am anticipating for the SDK to support zod v4 and I want to thank you for your time and effort!

I took a little more time to further learn about zod and the SDK so I can provide some meaningful insights if possible

according to https://zod.dev/library-authors?id=how-to-support-zod-3-and-zod-4-simultaneously you can support both z3 and z4 which can make this feature (in case that the maintainers of this repo are willing) a non-breaking change so it can be part of sdk v1 rather than v2. I suggest asking the maintainers before re-implementing the whole PR of course!

besides backward compatibility, it looks like _def is a zod v3 style whereas in zod v4 it should be ._zod.def. I really am not sure about that, I assume you already stumbled upon this and I just am missing something but I'd love to hear what you have to say about this.

one thing that I am not sure about is your choice to as unknown as and the usage as in general. I suggest adding a comment that explains why this kind of type manipulation is required rather than using type guards (using simple conditions/ custom type predicates with is or maybe using zod) that will explain intentions better

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also am not sure about the completable feature and have never used it before

} {
const target = schema as unknown as { _def?: Record<string, unknown> };
const originalDef = (target._def ?? {}) as Record<string, unknown>;
// Only mutate the existing _def object to respect read-only property semantics
if (
(originalDef as { typeName?: unknown }).typeName !==
McpZodTypeKind.Completable
) {
(originalDef as { typeName?: McpZodTypeKind; type?: ZodTypeAny }).typeName =
McpZodTypeKind.Completable;
(originalDef as { typeName?: McpZodTypeKind; type?: ZodTypeAny }).type =
schema;
}
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 };
(originalDef as { complete?: CompleteCallback<T> }).complete = complete;
return schema as unknown as T & {
_def: (T extends { _def: infer D } ? D : unknown) & CompletableDef<T>;
};
return { errorMap: customMap, description };
}
2 changes: 1 addition & 1 deletion src/server/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
/* eslint-disable no-constant-binary-expression */
/* eslint-disable @typescript-eslint/no-unused-expressions */
import { Server } from "./index.js";
import { z } from "zod";
import { z } from "zod/v4";
import {
RequestSchema,
NotificationSchema,
Expand Down
Loading