From 43a7a1eb9403ed9e70876647cd15271c8238ea0c Mon Sep 17 00:00:00 2001 From: ihrpr Date: Sun, 20 Jul 2025 20:40:02 +0100 Subject: [PATCH 1/6] add strip types --- .github/workflows/main.yml | 1 + CONTRIBUTING.md | 7 +- README.md | 63 ++ package.json | 2 + scripts/generateStrictTypes.ts | 69 ++ src/examples/strictTypesExample.ts | 57 + src/strictTypes.ts | 1662 ++++++++++++++++++++++++++++ src/types.ts | 17 + 8 files changed, 1875 insertions(+), 3 deletions(-) create mode 100755 scripts/generateStrictTypes.ts create mode 100644 src/examples/strictTypesExample.ts create mode 100644 src/strictTypes.ts diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 04ba17c90..962591e69 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -22,6 +22,7 @@ jobs: cache: npm - run: npm ci + - run: npm run check:strict-types - run: npm run build - run: npm test - run: npm run lint diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ace9542db..e8ceed77a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -14,9 +14,10 @@ We welcome contributions to the Model Context Protocol TypeScript SDK! This docu 1. Create a new branch for your changes 2. Make your changes -3. Run `npm run lint` to ensure code style compliance -4. Run `npm test` to verify all tests pass -5. Submit a pull request +3. If you modify `src/types.ts`, run `npm run generate:strict-types` to update strict types +4. Run `npm run lint` to ensure code style compliance +5. Run `npm test` to verify all tests pass +6. Submit a pull request ## Pull Request Guidelines diff --git a/README.md b/README.md index 4684c67c7..32527d464 100644 --- a/README.md +++ b/README.md @@ -950,6 +950,69 @@ server.registerTool("tool3", ...).disable(); // Only one 'notifications/tools/list_changed' is sent. ``` +### Type Safety + +The SDK provides type-safe definitions that validate schemas while maintaining protocol compatibility. + +```typescript +// Recommended: Use safe types that strip unknown fields +import { ToolSchema } from "@modelcontextprotocol/sdk/strictTypes.js"; + +// ⚠️ Deprecated: Extensible types will be removed in a future version +import { ToolSchema } from "@modelcontextprotocol/sdk/types.js"; +``` + +**Safe types with .strip():** +```typescript +import { ToolSchema } from "@modelcontextprotocol/sdk/strictTypes.js"; + +// Unknown fields are automatically removed, not rejected +const tool = ToolSchema.parse({ + name: "get-weather", + description: "Get weather", + inputSchema: { type: "object", properties: {} }, + customField: "this will be stripped" // ✓ No error, field is removed +}); + +console.log(tool.customField); // undefined - field was stripped +console.log(tool.name); // "get-weather" - known fields are preserved +``` + +**Benefits:** +- **Type safety**: Only known fields are included in results +- **Protocol compatibility**: Works seamlessly with extended servers/clients +- **No runtime errors**: Unknown fields are silently removed +- **Forward compatibility**: Your code won't break when servers add new fields + +**Migration Guide:** + +If you're currently using types.js and need extensibility: +1. Switch to importing from `strictTypes.js` +2. Add any additional fields you need explicitly to your schemas +3. For true extensibility needs, create wrapper schemas that extend the base types + +Example migration: +```typescript +// Before (deprecated) +import { ToolSchema } from "@modelcontextprotocol/sdk/types.js"; +const tool = { ...baseFields, customField: "value" }; + +// After (recommended) +import { ToolSchema } from "@modelcontextprotocol/sdk/strictTypes.js"; +import { z } from "zod"; + +// Create your own extended schema +const ExtendedToolSchema = ToolSchema.extend({ + customField: z.string() +}); +const tool = ExtendedToolSchema.parse({ ...baseFields, customField: "value" }); +``` + +Note: The following fields remain extensible for protocol compatibility: +- `experimental`: For protocol extensions +- `_meta`: For arbitrary metadata +- `properties`: For JSON Schema objects + ### Low-Level Server For more control, you can use the low-level Server class directly: diff --git a/package.json b/package.json index 1bd2cea91..ef5f5d103 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,8 @@ ], "scripts": { "fetch:spec-types": "curl -o spec.types.ts https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/refs/heads/main/schema/draft/schema.ts", + "generate:strict-types": "tsx scripts/generateStrictTypes.ts", + "check:strict-types": "npm run generate:strict-types && git diff --exit-code src/strictTypes.ts || (echo 'Error: strictTypes.ts is out of date. Run npm run generate:strict-types' && exit 1)", "build": "npm run build:esm && npm run build:cjs", "build:esm": "mkdir -p dist/esm && echo '{\"type\": \"module\"}' > dist/esm/package.json && tsc -p tsconfig.prod.json", "build:esm:w": "npm run build:esm -- -w", diff --git a/scripts/generateStrictTypes.ts b/scripts/generateStrictTypes.ts new file mode 100755 index 000000000..3f0a5924e --- /dev/null +++ b/scripts/generateStrictTypes.ts @@ -0,0 +1,69 @@ +#!/usr/bin/env node +import { readFileSync, writeFileSync } from 'fs'; +import { join, dirname } from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +// Read the original types.ts file +const typesPath = join(__dirname, '../src/types.ts'); +const strictTypesPath = join(__dirname, '../src/strictTypes.ts'); + +let content = readFileSync(typesPath, 'utf-8'); + +// Add header comment +const header = `/** + * Types remove unknown + * properties to maintaining compatibility with protocol extensions. + * + * - Protocol compatoble: Unknown fields from extended implementations are removed, not rejected + * - Forward compatibility: Works with servers/clients that have additional fields + * + * @generated by scripts/generateStrictTypes.ts + */ + +`; + +// Replace all .passthrough() with .strip() +content = content.replace(/\.passthrough\(\)/g, '.strip()'); + +// Special handling for experimental and capabilities that should remain open +// These are explicitly designed to be extensible +const patternsToKeepOpen = [ + // Keep experimental fields open as they're meant for extensions + /experimental: z\.optional\(z\.object\(\{\}\)\.strip\(\)\)/g, + // Keep _meta fields open as they're meant for arbitrary metadata + /_meta: z\.optional\(z\.object\(\{\}\)\.strip\(\)\)/g, + // Keep JSON Schema properties open as they can have arbitrary fields + /properties: z\.optional\(z\.object\(\{\}\)\.strip\(\)\)/g, +]; + +// Revert strip back to passthrough for these special cases +patternsToKeepOpen.forEach(pattern => { + content = content.replace(pattern, (match) => + match.replace('.strip()', '.passthrough()') + ); +}); + +// Add a comment explaining the difference +const explanation = ` +/** + * Note: The following fields remain open (using .passthrough()): + * - experimental: Designed for protocol extensions + * - _meta: Designed for arbitrary metadata + * - properties: JSON Schema properties that can have arbitrary fields + * + * All other objects use .strip() to remove unknown properties while + * maintaining compatibility with extended protocols. + */ +`; + +// Insert the explanation after the imports +const importEndIndex = content.lastIndexOf('import'); +const importEndLineIndex = content.indexOf('\n', importEndIndex); +content = content.slice(0, importEndLineIndex + 1) + explanation + content.slice(importEndLineIndex + 1); + +// Write the strict types file +writeFileSync(strictTypesPath, header + content); + +console.log('Generated strictTypes.ts successfully!'); diff --git a/src/examples/strictTypesExample.ts b/src/examples/strictTypesExample.ts new file mode 100644 index 000000000..898ec3943 --- /dev/null +++ b/src/examples/strictTypesExample.ts @@ -0,0 +1,57 @@ +/** + * Example showing the difference between regular types and strict types + */ + +import { ToolSchema as OpenToolSchema } from "../types.js"; +import { ToolSchema as StrictToolSchema } from "../strictTypes.js"; + +// With regular (open) types - this is valid +const openTool = OpenToolSchema.parse({ + name: "get-weather", + description: "Get weather for a location", + inputSchema: { + type: "object", + properties: { + location: { type: "string" } + } + }, + // Extra properties are allowed + customField: "This is allowed in open types", + anotherExtra: 123 +}); + +console.log("Open tool accepts extra properties:", openTool); + +// With strict types - this would throw an error +try { + StrictToolSchema.parse({ + name: "get-weather", + description: "Get weather for a location", + inputSchema: { + type: "object", + properties: { + location: { type: "string" } + } + }, + // Extra properties cause validation to fail + customField: "This is NOT allowed in strict types", + anotherExtra: 123 + }); +} catch (error) { + console.log("Strict tool rejects extra properties:", error instanceof Error ? error.message : String(error)); +} + +// Correct usage with strict types +const strictToolCorrect = StrictToolSchema.parse({ + name: "get-weather", + description: "Get weather for a location", + inputSchema: { + type: "object", + properties: { + location: { type: "string" } + } + } + // No extra properties +}); + +console.log("Strict tool with no extra properties:", strictToolCorrect); \ No newline at end of file diff --git a/src/strictTypes.ts b/src/strictTypes.ts new file mode 100644 index 000000000..81510be78 --- /dev/null +++ b/src/strictTypes.ts @@ -0,0 +1,1662 @@ +/** + * Types remove unknown + * properties to maintaining compatibility with protocol extensions. + * + * - Protocol compatoble: Unknown fields from extended implementations are removed, not rejected + * - Forward compatibility: Works with servers/clients that have additional fields + * + * @generated by scripts/generateStrictTypes.ts + */ + +/** + * @deprecated These extensible types with .strip() will be removed in a future version. + * + * For better type safety, use the types from "./strictTypes.js" instead. + * Those types use .strip() which provides compatibility with protocol extensions + * while ensuring type safety by removing unknown fields. + * + * Benefits of strictTypes.js: + * - Type safety: Only known fields are included in the result + * - No runtime errors: Unknown fields are silently stripped, not rejected + * - Protocol compatible: Works with extended servers/clients + * + * Migration guide: + * - Change: import { ToolSchema } from "@modelcontextprotocol/sdk/types.js" + * - To: import { ToolSchema } from "@modelcontextprotocol/sdk/strictTypes.js" + */ + +import { z, ZodTypeAny } from "zod"; +import { AuthInfo } from "./server/auth/types.js"; + +/** + * Note: The following fields remain open (using .passthrough()): + * - experimental: Designed for protocol extensions + * - _meta: Designed for arbitrary metadata + * - properties: JSON Schema properties that can have arbitrary fields + * + * All other objects use .strip() to remove unknown properties while + * maintaining compatibility with extended protocols. + */ + +export const LATEST_PROTOCOL_VERSION = "2025-06-18"; +export const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; +export const SUPPORTED_PROTOCOL_VERSIONS = [ + LATEST_PROTOCOL_VERSION, + "2025-03-26", + "2024-11-05", + "2024-10-07", +]; + +/* JSON-RPC types */ +export const JSONRPC_VERSION = "2.0"; + +/** + * A progress token, used to associate progress notifications with the original request. + */ +export const ProgressTokenSchema = z.union([z.string(), z.number().int()]); + +/** + * An opaque token used to represent a cursor for pagination. + */ +export const CursorSchema = z.string(); + +const RequestMetaSchema = z + .object({ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: z.optional(ProgressTokenSchema), + }) + .strip(); + +const BaseRequestParamsSchema = z + .object({ + _meta: z.optional(RequestMetaSchema), + }) + .strip(); + +export const RequestSchema = z.object({ + method: z.string(), + params: z.optional(BaseRequestParamsSchema), +}); + +const BaseNotificationParamsSchema = z + .object({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()), + }) + .strip(); + +export const NotificationSchema = z.object({ + method: z.string(), + params: z.optional(BaseNotificationParamsSchema), +}); + +export const ResultSchema = z + .object({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()), + }) + .strip(); + +/** + * A uniquely identifying ID for a request in JSON-RPC. + */ +export const RequestIdSchema = z.union([z.string(), z.number().int()]); + +/** + * A request that expects a response. + */ +export const JSONRPCRequestSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + id: RequestIdSchema, + }) + .merge(RequestSchema) + .strict(); + +export const isJSONRPCRequest = (value: unknown): value is JSONRPCRequest => + JSONRPCRequestSchema.safeParse(value).success; + +/** + * A notification which does not expect a response. + */ +export const JSONRPCNotificationSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + }) + .merge(NotificationSchema) + .strict(); + +export const isJSONRPCNotification = ( + value: unknown +): value is JSONRPCNotification => + JSONRPCNotificationSchema.safeParse(value).success; + +/** + * A successful (non-error) response to a request. + */ +export const JSONRPCResponseSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema, + }) + .strict(); + +export const isJSONRPCResponse = (value: unknown): value is JSONRPCResponse => + JSONRPCResponseSchema.safeParse(value).success; + +/** + * Error codes defined by the JSON-RPC specification. + */ +export enum ErrorCode { + // SDK error codes + ConnectionClosed = -32000, + RequestTimeout = -32001, + + // Standard JSON-RPC error codes + ParseError = -32700, + InvalidRequest = -32600, + MethodNotFound = -32601, + InvalidParams = -32602, + InternalError = -32603, +} + +/** + * A response to a request that indicates an error occurred. + */ +export const JSONRPCErrorSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + id: RequestIdSchema, + error: z.object({ + /** + * The error type that occurred. + */ + code: z.number().int(), + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: z.string(), + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data: z.optional(z.unknown()), + }), + }) + .strict(); + +export const isJSONRPCError = (value: unknown): value is JSONRPCError => + JSONRPCErrorSchema.safeParse(value).success; + +export const JSONRPCMessageSchema = z.union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResponseSchema, + JSONRPCErrorSchema, +]); + +/* Empty result */ +/** + * A response that indicates success but carries no data. + */ +export const EmptyResultSchema = ResultSchema.strict(); + +/* Cancellation */ +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + */ +export const CancelledNotificationSchema = NotificationSchema.extend({ + method: z.literal("notifications/cancelled"), + params: BaseNotificationParamsSchema.extend({ + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestIdSchema, + + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason: z.string().optional(), + }), +}); + +/* Base Metadata */ +/** + * Base metadata interface for common properties across resources, tools, prompts, and implementations. + */ +export const BaseMetadataSchema = z + .object({ + /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ + name: z.string(), + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title: z.optional(z.string()), + }) + .strip(); + +/* Initialization */ +/** + * Describes the name and version of an MCP implementation. + */ +export const ImplementationSchema = BaseMetadataSchema.extend({ + version: z.string(), +}); + +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ +export const ClientCapabilitiesSchema = z + .object({ + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental: z.optional(z.object({}).passthrough()), + /** + * Present if the client supports sampling from an LLM. + */ + sampling: z.optional(z.object({}).strip()), + /** + * Present if the client supports eliciting user input. + */ + elicitation: z.optional(z.object({}).strip()), + /** + * Present if the client supports listing roots. + */ + roots: z.optional( + z + .object({ + /** + * Whether the client supports issuing notifications for changes to the roots list. + */ + listChanged: z.optional(z.boolean()), + }) + .strip(), + ), + }) + .strip(); + +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ +export const InitializeRequestSchema = RequestSchema.extend({ + method: z.literal("initialize"), + params: BaseRequestParamsSchema.extend({ + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: z.string(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema, + }), +}); + +export const isInitializeRequest = (value: unknown): value is InitializeRequest => + InitializeRequestSchema.safeParse(value).success; + + +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ +export const ServerCapabilitiesSchema = z + .object({ + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental: z.optional(z.object({}).passthrough()), + /** + * Present if the server supports sending log messages to the client. + */ + logging: z.optional(z.object({}).strip()), + /** + * Present if the server supports sending completions to the client. + */ + completions: z.optional(z.object({}).strip()), + /** + * Present if the server offers any prompt templates. + */ + prompts: z.optional( + z + .object({ + /** + * Whether this server supports issuing notifications for changes to the prompt list. + */ + listChanged: z.optional(z.boolean()), + }) + .strip(), + ), + /** + * Present if the server offers any resources to read. + */ + resources: z.optional( + z + .object({ + /** + * Whether this server supports clients subscribing to resource updates. + */ + subscribe: z.optional(z.boolean()), + + /** + * Whether this server supports issuing notifications for changes to the resource list. + */ + listChanged: z.optional(z.boolean()), + }) + .strip(), + ), + /** + * Present if the server offers any tools to call. + */ + tools: z.optional( + z + .object({ + /** + * Whether this server supports issuing notifications for changes to the tool list. + */ + listChanged: z.optional(z.boolean()), + }) + .strip(), + ), + }) + .strip(); + +/** + * After receiving an initialize request from the client, the server sends this response. + */ +export const InitializeResultSchema = ResultSchema.extend({ + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: z.string(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions: z.optional(z.string()), +}); + +/** + * This notification is sent from the client to the server after initialization has finished. + */ +export const InitializedNotificationSchema = NotificationSchema.extend({ + method: z.literal("notifications/initialized"), +}); + +export const isInitializedNotification = (value: unknown): value is InitializedNotification => + InitializedNotificationSchema.safeParse(value).success; + +/* Ping */ +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ +export const PingRequestSchema = RequestSchema.extend({ + method: z.literal("ping"), +}); + +/* Progress notifications */ +export const ProgressSchema = z + .object({ + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + */ + progress: z.number(), + /** + * Total number of items to process (or total progress required), if known. + */ + total: z.optional(z.number()), + /** + * An optional message describing the current progress. + */ + message: z.optional(z.string()), + }) + .strip(); + +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + */ +export const ProgressNotificationSchema = NotificationSchema.extend({ + method: z.literal("notifications/progress"), + params: BaseNotificationParamsSchema.merge(ProgressSchema).extend({ + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressTokenSchema, + }), +}); + +/* Pagination */ +export const PaginatedRequestSchema = RequestSchema.extend({ + params: BaseRequestParamsSchema.extend({ + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor: z.optional(CursorSchema), + }).optional(), +}); + +export const PaginatedResultSchema = ResultSchema.extend({ + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor: z.optional(CursorSchema), +}); + +/* Resources */ +/** + * The contents of a specific resource or sub-resource. + */ +export const ResourceContentsSchema = z + .object({ + /** + * The URI of this resource. + */ + uri: z.string(), + /** + * The MIME type of this resource, if known. + */ + mimeType: z.optional(z.string()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()), + }) + .strip(); + +export const TextResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: z.string(), +}); + +export const BlobResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * A base64-encoded string representing the binary data of the item. + */ + blob: z.string().base64(), +}); + +/** + * A known resource that the server is capable of reading. + */ +export const ResourceSchema = BaseMetadataSchema.extend({ + /** + * The URI of this resource. + */ + uri: z.string(), + + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: z.optional(z.string()), + + /** + * The MIME type of this resource, if known. + */ + mimeType: z.optional(z.string()), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()), +}); + +/** + * A template description for resources available on the server. + */ +export const ResourceTemplateSchema = BaseMetadataSchema.extend({ + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + */ + uriTemplate: z.string(), + + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: z.optional(z.string()), + + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType: z.optional(z.string()), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()), +}); + +/** + * Sent from the client to request a list of resources the server has. + */ +export const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal("resources/list"), +}); + +/** + * The server's response to a resources/list request from the client. + */ +export const ListResourcesResultSchema = PaginatedResultSchema.extend({ + resources: z.array(ResourceSchema), +}); + +/** + * Sent from the client to request a list of resource templates the server has. + */ +export const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend( + { + method: z.literal("resources/templates/list"), + }, +); + +/** + * The server's response to a resources/templates/list request from the client. + */ +export const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ + resourceTemplates: z.array(ResourceTemplateSchema), +}); + +/** + * Sent from the client to the server, to read a specific resource URI. + */ +export const ReadResourceRequestSchema = RequestSchema.extend({ + method: z.literal("resources/read"), + params: BaseRequestParamsSchema.extend({ + /** + * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. + */ + uri: z.string(), + }), +}); + +/** + * The server's response to a resources/read request from the client. + */ +export const ReadResourceResultSchema = ResultSchema.extend({ + contents: z.array( + z.union([TextResourceContentsSchema, BlobResourceContentsSchema]), + ), +}); + +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ +export const ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal("notifications/resources/list_changed"), +}); + +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + */ +export const SubscribeRequestSchema = RequestSchema.extend({ + method: z.literal("resources/subscribe"), + params: BaseRequestParamsSchema.extend({ + /** + * The URI of the resource to subscribe to. The URI can use any protocol; it is up to the server how to interpret it. + */ + uri: z.string(), + }), +}); + +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + */ +export const UnsubscribeRequestSchema = RequestSchema.extend({ + method: z.literal("resources/unsubscribe"), + params: BaseRequestParamsSchema.extend({ + /** + * The URI of the resource to unsubscribe from. + */ + uri: z.string(), + }), +}); + +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + */ +export const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: z.literal("notifications/resources/updated"), + params: BaseNotificationParamsSchema.extend({ + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + */ + uri: z.string(), + }), +}); + +/* Prompts */ +/** + * Describes an argument that a prompt can accept. + */ +export const PromptArgumentSchema = z + .object({ + /** + * The name of the argument. + */ + name: z.string(), + /** + * A human-readable description of the argument. + */ + description: z.optional(z.string()), + /** + * Whether this argument must be provided. + */ + required: z.optional(z.boolean()), + }) + .strip(); + +/** + * A prompt or prompt template that the server offers. + */ +export const PromptSchema = BaseMetadataSchema.extend({ + /** + * An optional description of what this prompt provides + */ + description: z.optional(z.string()), + /** + * A list of arguments to use for templating the prompt. + */ + arguments: z.optional(z.array(PromptArgumentSchema)), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()), +}); + +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ +export const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal("prompts/list"), +}); + +/** + * The server's response to a prompts/list request from the client. + */ +export const ListPromptsResultSchema = PaginatedResultSchema.extend({ + prompts: z.array(PromptSchema), +}); + +/** + * Used by the client to get a prompt provided by the server. + */ +export const GetPromptRequestSchema = RequestSchema.extend({ + method: z.literal("prompts/get"), + params: BaseRequestParamsSchema.extend({ + /** + * The name of the prompt or prompt template. + */ + name: z.string(), + /** + * Arguments to use for templating the prompt. + */ + arguments: z.optional(z.record(z.string())), + }), +}); + +/** + * Text provided to or from an LLM. + */ +export const TextContentSchema = z + .object({ + type: z.literal("text"), + /** + * The text content of the message. + */ + text: z.string(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()), + }) + .strip(); + +/** + * An image provided to or from an LLM. + */ +export const ImageContentSchema = z + .object({ + type: z.literal("image"), + /** + * The base64-encoded image data. + */ + data: z.string().base64(), + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: z.string(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()), + }) + .strip(); + +/** + * An Audio provided to or from an LLM. + */ +export const AudioContentSchema = z + .object({ + type: z.literal("audio"), + /** + * The base64-encoded audio data. + */ + data: z.string().base64(), + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: z.string(), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()), + }) + .strip(); + +/** + * The contents of a resource, embedded into a prompt or tool call result. + */ +export const EmbeddedResourceSchema = z + .object({ + type: z.literal("resource"), + resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()), + }) + .strip(); + +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + */ +export const ResourceLinkSchema = ResourceSchema.extend({ + type: z.literal("resource_link"), +}); + +/** + * A content block that can be used in prompts and tool results. + */ +export const ContentBlockSchema = z.union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema, +]); + +/** + * Describes a message returned as part of a prompt. + */ +export const PromptMessageSchema = z + .object({ + role: z.enum(["user", "assistant"]), + content: ContentBlockSchema, + }) + .strip(); + +/** + * The server's response to a prompts/get request from the client. + */ +export const GetPromptResultSchema = ResultSchema.extend({ + /** + * An optional description for the prompt. + */ + description: z.optional(z.string()), + messages: z.array(PromptMessageSchema), +}); + +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export const PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal("notifications/prompts/list_changed"), +}); + +/* Tools */ +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + */ +export const ToolAnnotationsSchema = z + .object({ + /** + * A human-readable title for the tool. + */ + title: z.optional(z.string()), + + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint: z.optional(z.boolean()), + + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint: z.optional(z.boolean()), + + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on the its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint: z.optional(z.boolean()), + + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint: z.optional(z.boolean()), + }) + .strip(); + +/** + * Definition for a tool the client can call. + */ +export const ToolSchema = BaseMetadataSchema.extend({ + /** + * A human-readable description of the tool. + */ + description: z.optional(z.string()), + /** + * A JSON Schema object defining the expected parameters for the tool. + */ + inputSchema: z + .object({ + type: z.literal("object"), + properties: z.optional(z.object({}).passthrough()), + required: z.optional(z.array(z.string())), + }) + .strip(), + /** + * An optional JSON Schema object defining the structure of the tool's output returned in + * the structuredContent field of a CallToolResult. + */ + outputSchema: z.optional( + z.object({ + type: z.literal("object"), + properties: z.optional(z.object({}).passthrough()), + required: z.optional(z.array(z.string())), + }) + .strip() + ), + /** + * Optional additional tool information. + */ + annotations: z.optional(ToolAnnotationsSchema), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()), +}); + +/** + * Sent from the client to request a list of tools the server has. + */ +export const ListToolsRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal("tools/list"), +}); + +/** + * The server's response to a tools/list request from the client. + */ +export const ListToolsResultSchema = PaginatedResultSchema.extend({ + tools: z.array(ToolSchema), +}); + +/** + * The server's response to a tool call. + */ +export const CallToolResultSchema = ResultSchema.extend({ + /** + * A list of content objects that represent the result of the tool call. + * + * If the Tool does not define an outputSchema, this field MUST be present in the result. + * For backwards compatibility, this field is always present, but it may be empty. + */ + content: z.array(ContentBlockSchema).default([]), + + /** + * An object containing structured tool output. + * + * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. + */ + structuredContent: z.object({}).strip().optional(), + + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError: z.optional(z.boolean()), +}); + +/** + * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. + */ +export const CompatibilityCallToolResultSchema = CallToolResultSchema.or( + ResultSchema.extend({ + toolResult: z.unknown(), + }), +); + +/** + * Used by the client to invoke a tool provided by the server. + */ +export const CallToolRequestSchema = RequestSchema.extend({ + method: z.literal("tools/call"), + params: BaseRequestParamsSchema.extend({ + name: z.string(), + arguments: z.optional(z.record(z.unknown())), + }), +}); + +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export const ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal("notifications/tools/list_changed"), +}); + +/* Logging */ +/** + * The severity of a log message. + */ +export const LoggingLevelSchema = z.enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency", +]); + +/** + * A request from the client to the server, to enable or adjust logging. + */ +export const SetLevelRequestSchema = RequestSchema.extend({ + method: z.literal("logging/setLevel"), + params: BaseRequestParamsSchema.extend({ + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. + */ + level: LoggingLevelSchema, + }), +}); + +/** + * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + */ +export const LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: z.literal("notifications/message"), + params: BaseNotificationParamsSchema.extend({ + /** + * The severity of this log message. + */ + level: LoggingLevelSchema, + /** + * An optional name of the logger issuing this message. + */ + logger: z.optional(z.string()), + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: z.unknown(), + }), +}); + +/* Sampling */ +/** + * Hints to use for model selection. + */ +export const ModelHintSchema = z + .object({ + /** + * A hint for a model name. + */ + name: z.string().optional(), + }) + .strip(); + +/** + * The server's preferences for model selection, requested of the client during sampling. + */ +export const ModelPreferencesSchema = z + .object({ + /** + * Optional hints to use for model selection. + */ + hints: z.optional(z.array(ModelHintSchema)), + /** + * How much to prioritize cost when selecting a model. + */ + costPriority: z.optional(z.number().min(0).max(1)), + /** + * How much to prioritize sampling speed (latency) when selecting a model. + */ + speedPriority: z.optional(z.number().min(0).max(1)), + /** + * How much to prioritize intelligence and capabilities when selecting a model. + */ + intelligencePriority: z.optional(z.number().min(0).max(1)), + }) + .strip(); + +/** + * Describes a message issued to or received from an LLM API. + */ +export const SamplingMessageSchema = z + .object({ + role: z.enum(["user", "assistant"]), + content: z.union([TextContentSchema, ImageContentSchema, AudioContentSchema]), + }) + .strip(); + +/** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + */ +export const CreateMessageRequestSchema = RequestSchema.extend({ + method: z.literal("sampling/createMessage"), + params: BaseRequestParamsSchema.extend({ + messages: z.array(SamplingMessageSchema), + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt: z.optional(z.string()), + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. The client MAY ignore this request. + */ + includeContext: z.optional(z.enum(["none", "thisServer", "allServers"])), + temperature: z.optional(z.number()), + /** + * The maximum number of tokens to sample, as requested by the server. The client MAY choose to sample fewer tokens than requested. + */ + maxTokens: z.number().int(), + stopSequences: z.optional(z.array(z.string())), + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata: z.optional(z.object({}).strip()), + /** + * The server's preferences for which model to select. + */ + modelPreferences: z.optional(ModelPreferencesSchema), + }), +}); + +/** + * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. + */ +export const CreateMessageResultSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: z.string(), + /** + * The reason why sampling stopped. + */ + stopReason: z.optional( + z.enum(["endTurn", "stopSequence", "maxTokens"]).or(z.string()), + ), + role: z.enum(["user", "assistant"]), + content: z.discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema + ]), +}); + +/* Elicitation */ +/** + * Primitive schema definition for boolean fields. + */ +export const BooleanSchemaSchema = z + .object({ + type: z.literal("boolean"), + title: z.optional(z.string()), + description: z.optional(z.string()), + default: z.optional(z.boolean()), + }) + .strip(); + +/** + * Primitive schema definition for string fields. + */ +export const StringSchemaSchema = z + .object({ + type: z.literal("string"), + title: z.optional(z.string()), + description: z.optional(z.string()), + minLength: z.optional(z.number()), + maxLength: z.optional(z.number()), + format: z.optional(z.enum(["email", "uri", "date", "date-time"])), + }) + .strip(); + +/** + * Primitive schema definition for number fields. + */ +export const NumberSchemaSchema = z + .object({ + type: z.enum(["number", "integer"]), + title: z.optional(z.string()), + description: z.optional(z.string()), + minimum: z.optional(z.number()), + maximum: z.optional(z.number()), + }) + .strip(); + +/** + * Primitive schema definition for enum fields. + */ +export const EnumSchemaSchema = z + .object({ + type: z.literal("string"), + title: z.optional(z.string()), + description: z.optional(z.string()), + enum: z.array(z.string()), + enumNames: z.optional(z.array(z.string())), + }) + .strip(); + +/** + * Union of all primitive schema definitions. + */ +export const PrimitiveSchemaDefinitionSchema = z.union([ + BooleanSchemaSchema, + StringSchemaSchema, + NumberSchemaSchema, + EnumSchemaSchema, +]); + +/** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user. + */ +export const ElicitRequestSchema = RequestSchema.extend({ + method: z.literal("elicitation/create"), + params: BaseRequestParamsSchema.extend({ + /** + * The message to present to the user. + */ + message: z.string(), + /** + * The schema for the requested user input. + */ + requestedSchema: z + .object({ + type: z.literal("object"), + properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema), + required: z.optional(z.array(z.string())), + }) + .strip(), + }), +}); + +/** + * The client's response to an elicitation/create request from the server. + */ +export const ElicitResultSchema = ResultSchema.extend({ + /** + * The user's response action. + */ + action: z.enum(["accept", "decline", "cancel"]), + /** + * The collected user input content (only present if action is "accept"). + */ + content: z.optional(z.record(z.string(), z.unknown())), +}); + +/* Autocomplete */ +/** + * A reference to a resource or resource template definition. + */ +export const ResourceTemplateReferenceSchema = z + .object({ + type: z.literal("ref/resource"), + /** + * The URI or URI template of the resource. + */ + uri: z.string(), + }) + .strip(); + +/** + * @deprecated Use ResourceTemplateReferenceSchema instead + */ +export const ResourceReferenceSchema = ResourceTemplateReferenceSchema; + +/** + * Identifies a prompt. + */ +export const PromptReferenceSchema = z + .object({ + type: z.literal("ref/prompt"), + /** + * The name of the prompt or prompt template + */ + name: z.string(), + }) + .strip(); + +/** + * A request from the client to the server, to ask for completion options. + */ +export const CompleteRequestSchema = RequestSchema.extend({ + method: z.literal("completion/complete"), + params: BaseRequestParamsSchema.extend({ + ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + /** + * The argument's information + */ + argument: z + .object({ + /** + * The name of the argument + */ + name: z.string(), + /** + * The value of the argument to use for completion matching. + */ + value: z.string(), + }) + .strip(), + context: z.optional( + z.object({ + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments: z.optional(z.record(z.string(), z.string())), + }) + ), + }), +}); + +/** + * The server's response to a completion/complete request + */ +export const CompleteResultSchema = ResultSchema.extend({ + completion: z + .object({ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.array(z.string()).max(100), + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.optional(z.number().int()), + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.optional(z.boolean()), + }) + .strip(), +}); + +/* Roots */ +/** + * Represents a root directory or file that the server can operate on. + */ +export const RootSchema = z + .object({ + /** + * The URI identifying the root. This *must* start with file:// for now. + */ + uri: z.string().startsWith("file://"), + /** + * An optional name for the root. + */ + name: z.optional(z.string()), + + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()), + }) + .strip(); + +/** + * Sent from the server to request a list of root URIs from the client. + */ +export const ListRootsRequestSchema = RequestSchema.extend({ + method: z.literal("roots/list"), +}); + +/** + * The client's response to a roots/list request from the server. + */ +export const ListRootsResultSchema = ResultSchema.extend({ + roots: z.array(RootSchema), +}); + +/** + * A notification from the client to the server, informing it that the list of roots has changed. + */ +export const RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal("notifications/roots/list_changed"), +}); + +/* Client messages */ +export const ClientRequestSchema = z.union([ + PingRequestSchema, + InitializeRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema, +]); + +export const ClientNotificationSchema = z.union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + InitializedNotificationSchema, + RootsListChangedNotificationSchema, +]); + +export const ClientResultSchema = z.union([ + EmptyResultSchema, + CreateMessageResultSchema, + ElicitResultSchema, + ListRootsResultSchema, +]); + +/* Server messages */ +export const ServerRequestSchema = z.union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema, +]); + +export const ServerNotificationSchema = z.union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, +]); + +export const ServerResultSchema = z.union([ + EmptyResultSchema, + InitializeResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + CallToolResultSchema, + ListToolsResultSchema, +]); + +export class McpError extends Error { + constructor( + public readonly code: number, + message: string, + public readonly data?: unknown, + ) { + super(`MCP error ${code}: ${message}`); + this.name = "McpError"; + } +} + +type Primitive = string | number | boolean | bigint | null | undefined; +type Flatten = T extends Primitive + ? T + : T extends Array + ? Array> + : T extends Set + ? Set> + : T extends Map + ? Map, Flatten> + : T extends object + ? { [K in keyof T]: Flatten } + : T; + +type Infer = Flatten>; + +/** + * Headers that are compatible with both Node.js and the browser. + */ +export type IsomorphicHeaders = Record; + +/** + * Information about the incoming request. + */ +export interface RequestInfo { + /** + * The headers of the request. + */ + headers: IsomorphicHeaders; +} + +/** + * Extra information about a message. + */ +export interface MessageExtraInfo { + /** + * The request information. + */ + requestInfo?: RequestInfo; + + /** + * The authentication information. + */ + authInfo?: AuthInfo; +} + +/* JSON-RPC types */ +export type ProgressToken = Infer; +export type Cursor = Infer; +export type Request = Infer; +export type RequestMeta = Infer; +export type Notification = Infer; +export type Result = Infer; +export type RequestId = Infer; +export type JSONRPCRequest = Infer; +export type JSONRPCNotification = Infer; +export type JSONRPCResponse = Infer; +export type JSONRPCError = Infer; +export type JSONRPCMessage = Infer; + +/* Empty result */ +export type EmptyResult = Infer; + +/* Cancellation */ +export type CancelledNotification = Infer; + +/* Base Metadata */ +export type BaseMetadata = Infer; + +/* Initialization */ +export type Implementation = Infer; +export type ClientCapabilities = Infer; +export type InitializeRequest = Infer; +export type ServerCapabilities = Infer; +export type InitializeResult = Infer; +export type InitializedNotification = Infer; + +/* Ping */ +export type PingRequest = Infer; + +/* Progress notifications */ +export type Progress = Infer; +export type ProgressNotification = Infer; + +/* Pagination */ +export type PaginatedRequest = Infer; +export type PaginatedResult = Infer; + +/* Resources */ +export type ResourceContents = Infer; +export type TextResourceContents = Infer; +export type BlobResourceContents = Infer; +export type Resource = Infer; +export type ResourceTemplate = Infer; +export type ListResourcesRequest = Infer; +export type ListResourcesResult = Infer; +export type ListResourceTemplatesRequest = Infer; +export type ListResourceTemplatesResult = Infer; +export type ReadResourceRequest = Infer; +export type ReadResourceResult = Infer; +export type ResourceListChangedNotification = Infer; +export type SubscribeRequest = Infer; +export type UnsubscribeRequest = Infer; +export type ResourceUpdatedNotification = Infer; + +/* Prompts */ +export type PromptArgument = Infer; +export type Prompt = Infer; +export type ListPromptsRequest = Infer; +export type ListPromptsResult = Infer; +export type GetPromptRequest = Infer; +export type TextContent = Infer; +export type ImageContent = Infer; +export type AudioContent = Infer; +export type EmbeddedResource = Infer; +export type ResourceLink = Infer; +export type ContentBlock = Infer; +export type PromptMessage = Infer; +export type GetPromptResult = Infer; +export type PromptListChangedNotification = Infer; + +/* Tools */ +export type ToolAnnotations = Infer; +export type Tool = Infer; +export type ListToolsRequest = Infer; +export type ListToolsResult = Infer; +export type CallToolResult = Infer; +export type CompatibilityCallToolResult = Infer; +export type CallToolRequest = Infer; +export type ToolListChangedNotification = Infer; + +/* Logging */ +export type LoggingLevel = Infer; +export type SetLevelRequest = Infer; +export type LoggingMessageNotification = Infer; + +/* Sampling */ +export type SamplingMessage = Infer; +export type CreateMessageRequest = Infer; +export type CreateMessageResult = Infer; + +/* Elicitation */ +export type BooleanSchema = Infer; +export type StringSchema = Infer; +export type NumberSchema = Infer; +export type EnumSchema = Infer; +export type PrimitiveSchemaDefinition = Infer; +export type ElicitRequest = Infer; +export type ElicitResult = Infer; + +/* Autocomplete */ +export type ResourceTemplateReference = Infer; +/** + * @deprecated Use ResourceTemplateReference instead + */ +export type ResourceReference = ResourceTemplateReference; +export type PromptReference = Infer; +export type CompleteRequest = Infer; +export type CompleteResult = Infer; + +/* Roots */ +export type Root = Infer; +export type ListRootsRequest = Infer; +export type ListRootsResult = Infer; +export type RootsListChangedNotification = Infer; + +/* Client messages */ +export type ClientRequest = Infer; +export type ClientNotification = Infer; +export type ClientResult = Infer; + +/* Server messages */ +export type ServerRequest = Infer; +export type ServerNotification = Infer; +export type ServerResult = Infer; diff --git a/src/types.ts b/src/types.ts index b96ab0500..ce3027f9e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,20 @@ +/** + * @deprecated These extensible types with .passthrough() will be removed in a future version. + * + * For better type safety, use the types from "./strictTypes.js" instead. + * Those types use .strip() which provides compatibility with protocol extensions + * while ensuring type safety by removing unknown fields. + * + * Benefits of strictTypes.js: + * - Type safety: Only known fields are included in the result + * - No runtime errors: Unknown fields are silently stripped, not rejected + * - Protocol compatible: Works with extended servers/clients + * + * Migration guide: + * - Change: import { ToolSchema } from "@modelcontextprotocol/sdk/types.js" + * - To: import { ToolSchema } from "@modelcontextprotocol/sdk/strictTypes.js" + */ + import { z, ZodTypeAny } from "zod"; import { AuthInfo } from "./server/auth/types.js"; From 33f69eb35b31303d9a56db445fcef9ee055e5214 Mon Sep 17 00:00:00 2001 From: ihrpr Date: Mon, 21 Jul 2025 10:19:05 +0100 Subject: [PATCH 2/6] improve example --- src/examples/strictTypesExample.ts | 60 ++++++++++-------------------- 1 file changed, 19 insertions(+), 41 deletions(-) diff --git a/src/examples/strictTypesExample.ts b/src/examples/strictTypesExample.ts index 898ec3943..0f9c1cc1a 100644 --- a/src/examples/strictTypesExample.ts +++ b/src/examples/strictTypesExample.ts @@ -1,12 +1,14 @@ /** - * Example showing the difference between regular types and strict types + * Example showing the difference between extensible types and safe types + * + * - Extensible types (types.js): Use .passthrough() - keep all fields + * - Safe types (strictTypes.js): Use .strip() - remove unknown fields */ -import { ToolSchema as OpenToolSchema } from "../types.js"; -import { ToolSchema as StrictToolSchema } from "../strictTypes.js"; +import { ToolSchema as ExtensibleToolSchema } from "../types.js"; +import { ToolSchema } from "../strictTypes.js"; -// With regular (open) types - this is valid -const openTool = OpenToolSchema.parse({ +const toolData = { name: "get-weather", description: "Get weather for a location", inputSchema: { @@ -15,43 +17,19 @@ const openTool = OpenToolSchema.parse({ location: { type: "string" } } }, - // Extra properties are allowed - customField: "This is allowed in open types", - anotherExtra: 123 -}); + // Extra properties that aren't in the schema + customField: "This is an extension", +}; -console.log("Open tool accepts extra properties:", openTool); +// With extensible types - ALL fields are preserved +const extensibleTool = ExtensibleToolSchema.parse(toolData); -// With strict types - this would throw an error -try { - StrictToolSchema.parse({ - name: "get-weather", - description: "Get weather for a location", - inputSchema: { - type: "object", - properties: { - location: { type: "string" } - } - }, - // Extra properties cause validation to fail - customField: "This is NOT allowed in strict types", - anotherExtra: 123 - }); -} catch (error) { - console.log("Strict tool rejects extra properties:", error instanceof Error ? error.message : String(error)); -} +console.log("Extensible tool keeps ALL properties:"); +console.log("- name:", extensibleTool.name); +console.log("- customField:", (extensibleTool as any).customField); // "This is an extension" -// Correct usage with strict types -const strictToolCorrect = StrictToolSchema.parse({ - name: "get-weather", - description: "Get weather for a location", - inputSchema: { - type: "object", - properties: { - location: { type: "string" } - } - } - // No extra properties -}); +// With safe types - unknown fields are silently stripped +const safeTool = ToolSchema.parse(toolData); -console.log("Strict tool with no extra properties:", strictToolCorrect); \ No newline at end of file +console.log("\nSafe tool strips unknown properties:"); +console.log("- customField:", (safeTool as any).customField); // undefined (stripped) From 47c91b2e8982eddd2d03ceea128c64889a0fd28c Mon Sep 17 00:00:00 2001 From: ihrpr Date: Mon, 21 Jul 2025 10:26:38 +0100 Subject: [PATCH 3/6] merge --- src/strictTypes.ts | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/src/strictTypes.ts b/src/strictTypes.ts index 81510be78..e614925fa 100644 --- a/src/strictTypes.ts +++ b/src/strictTypes.ts @@ -495,11 +495,31 @@ export const TextResourceContentsSchema = ResourceContentsSchema.extend({ text: z.string(), }); + +/** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ +const Base64Schema = z.string().refine( + (val) => { + try { + // atob throws a DOMException if the string contains characters + // that are not part of the Base64 character set. + atob(val); + return true; + } catch { + return false; + } + }, + { message: "Invalid Base64 string" }, +); + export const BlobResourceContentsSchema = ResourceContentsSchema.extend({ /** * A base64-encoded string representing the binary data of the item. */ - blob: z.string().base64(), + blob: Base64Schema, }); /** @@ -755,7 +775,7 @@ export const ImageContentSchema = z /** * The base64-encoded image data. */ - data: z.string().base64(), + data: Base64Schema, /** * The MIME type of the image. Different providers may support different image types. */ @@ -778,7 +798,7 @@ export const AudioContentSchema = z /** * The base64-encoded audio data. */ - data: z.string().base64(), + data: Base64Schema, /** * The MIME type of the audio. Different providers may support different audio types. */ @@ -931,7 +951,7 @@ export const ToolSchema = BaseMetadataSchema.extend({ }) .strip(), /** - * An optional JSON Schema object defining the structure of the tool's output returned in + * An optional JSON Schema object defining the structure of the tool's output returned in * the structuredContent field of a CallToolResult. */ outputSchema: z.optional( From c3cf0f87d9c840bbce2036d135d7ae53a122825f Mon Sep 17 00:00:00 2001 From: ihrpr Date: Mon, 21 Jul 2025 10:32:47 +0100 Subject: [PATCH 4/6] lint --- src/examples/strictTypesExample.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/examples/strictTypesExample.ts b/src/examples/strictTypesExample.ts index 0f9c1cc1a..8315bfc2a 100644 --- a/src/examples/strictTypesExample.ts +++ b/src/examples/strictTypesExample.ts @@ -26,10 +26,12 @@ const extensibleTool = ExtensibleToolSchema.parse(toolData); console.log("Extensible tool keeps ALL properties:"); console.log("- name:", extensibleTool.name); -console.log("- customField:", (extensibleTool as any).customField); // "This is an extension" +// Type assertion to access the extra field +console.log("- customField:", (extensibleTool as Record).customField); // "This is an extension" // With safe types - unknown fields are silently stripped const safeTool = ToolSchema.parse(toolData); console.log("\nSafe tool strips unknown properties:"); -console.log("- customField:", (safeTool as any).customField); // undefined (stripped) +// Type assertion to check the field was removed +console.log("- customField:", (safeTool as Record).customField); // undefined (stripped) From 7b6060fd2989614b895a33485966f33a4a4eaf3b Mon Sep 17 00:00:00 2001 From: ihrpr Date: Tue, 22 Jul 2025 13:24:41 +0100 Subject: [PATCH 5/6] BaseRequestParamsSchema, BaseNotificationParamsSchema, RequestMetaSchema, structuredContent and metadata to have passthrough --- scripts/generateStrictTypes.ts | 17 +++++++++++++- src/strictTypes.ts | 17 +++++++++----- src/types.test.ts | 41 ++++++++++++++++++++++++++++++++-- 3 files changed, 66 insertions(+), 9 deletions(-) diff --git a/scripts/generateStrictTypes.ts b/scripts/generateStrictTypes.ts index 3f0a5924e..6c9ec2097 100755 --- a/scripts/generateStrictTypes.ts +++ b/scripts/generateStrictTypes.ts @@ -36,6 +36,16 @@ const patternsToKeepOpen = [ /_meta: z\.optional\(z\.object\(\{\}\)\.strip\(\)\)/g, // Keep JSON Schema properties open as they can have arbitrary fields /properties: z\.optional\(z\.object\(\{\}\)\.strip\(\)\)/g, + // Keep BaseRequestParamsSchema passthrough for JSON-RPC param compatibility + /const BaseRequestParamsSchema = z\s*\n\s*\.object\([\s\S]*?\)\s*\n\s*\.strip\(\)/g, + // Keep BaseNotificationParamsSchema passthrough for JSON-RPC param compatibility + /const BaseNotificationParamsSchema = z\s*\n\s*\.object\([\s\S]*?\)\s*\n\s*\.strip\(\)/g, + // Keep RequestMetaSchema passthrough for extensibility + /const RequestMetaSchema = z\s*\n\s*\.object\([\s\S]*?\)\s*\n\s*\.strip\(\)/g, + // Keep structuredContent passthrough for tool-specific output + /structuredContent: z\.object\(\{\}\)\.strip\(\)\.optional\(\)/g, + // Keep metadata passthrough for provider-specific data in sampling + /metadata: z\.optional\(z\.object\(\{\}\)\.strip\(\)\)/g, ]; // Revert strip back to passthrough for these special cases @@ -48,10 +58,15 @@ patternsToKeepOpen.forEach(pattern => { // Add a comment explaining the difference const explanation = ` /** - * Note: The following fields remain open (using .passthrough()): + * Note: The following remain open (using .passthrough()): * - experimental: Designed for protocol extensions * - _meta: Designed for arbitrary metadata * - properties: JSON Schema properties that can have arbitrary fields + * - BaseRequestParamsSchema: Required for JSON-RPC param compatibility + * - BaseNotificationParamsSchema: Required for JSON-RPC param compatibility + * - RequestMetaSchema: Required for protocol extensibility + * - structuredContent: Tool-specific output that can have arbitrary fields + * - metadata: Provider-specific metadata in sampling requests * * All other objects use .strip() to remove unknown properties while * maintaining compatibility with extended protocols. diff --git a/src/strictTypes.ts b/src/strictTypes.ts index e614925fa..b59cfae0e 100644 --- a/src/strictTypes.ts +++ b/src/strictTypes.ts @@ -29,10 +29,15 @@ import { z, ZodTypeAny } from "zod"; import { AuthInfo } from "./server/auth/types.js"; /** - * Note: The following fields remain open (using .passthrough()): + * Note: The following remain open (using .passthrough()): * - experimental: Designed for protocol extensions * - _meta: Designed for arbitrary metadata * - properties: JSON Schema properties that can have arbitrary fields + * - BaseRequestParamsSchema: Required for JSON-RPC param compatibility + * - BaseNotificationParamsSchema: Required for JSON-RPC param compatibility + * - RequestMetaSchema: Required for protocol extensibility + * - structuredContent: Tool-specific output that can have arbitrary fields + * - metadata: Provider-specific metadata in sampling requests * * All other objects use .strip() to remove unknown properties while * maintaining compatibility with extended protocols. @@ -67,13 +72,13 @@ const RequestMetaSchema = z */ progressToken: z.optional(ProgressTokenSchema), }) - .strip(); + .passthrough(); const BaseRequestParamsSchema = z .object({ _meta: z.optional(RequestMetaSchema), }) - .strip(); + .passthrough(); export const RequestSchema = z.object({ method: z.string(), @@ -88,7 +93,7 @@ const BaseNotificationParamsSchema = z */ _meta: z.optional(z.object({}).passthrough()), }) - .strip(); + .passthrough(); export const NotificationSchema = z.object({ method: z.string(), @@ -1005,7 +1010,7 @@ export const CallToolResultSchema = ResultSchema.extend({ * * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. */ - structuredContent: z.object({}).strip().optional(), + structuredContent: z.object({}).passthrough().optional(), /** * Whether the tool call ended in an error. @@ -1171,7 +1176,7 @@ export const CreateMessageRequestSchema = RequestSchema.extend({ /** * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. */ - metadata: z.optional(z.object({}).strip()), + metadata: z.optional(z.object({}).passthrough()), /** * The server's preferences for which model to select. */ diff --git a/src/types.test.ts b/src/types.test.ts index 0aee62a93..b7ef1d3de 100644 --- a/src/types.test.ts +++ b/src/types.test.ts @@ -5,8 +5,10 @@ import { ContentBlockSchema, PromptMessageSchema, CallToolResultSchema, - CompleteRequestSchema -} from "./types.js"; + CompleteRequestSchema, + JSONRPCRequestSchema, + ReadResourceRequestSchema +} from "./strictTypes.js"; describe("Types", () => { @@ -312,4 +314,39 @@ describe("Types", () => { } }); }); + + describe("JSONRPCRequest validation", () => { + test("should preserve method-specific params for later validation", () => { + // This test verifies that JSONRPCRequestSchema preserves method-specific + // parameters (like 'uri' for resources/read) so they can be validated + // by the specific request schema later in the processing pipeline. + + const jsonRpcRequest = { + jsonrpc: "2.0", + id: 1, + method: "resources/read", + params: { + uri: "file:///test.txt", + _meta: { progressToken: "token" } + } + }; + + // Step 1: Validate as a generic JSON-RPC request + const jsonRpcResult = JSONRPCRequestSchema.safeParse(jsonRpcRequest); + expect(jsonRpcResult.success).toBe(true); + + if (jsonRpcResult.success) { + // The params should still contain method-specific fields like 'uri' + // even though they're not defined in the base schema + expect(jsonRpcResult.data.params).toBeDefined(); + const params = jsonRpcResult.data.params as { uri: string; _meta?: { progressToken?: string } }; + expect(params.uri).toBe("file:///test.txt"); + expect(params._meta?.progressToken).toBe("token"); + } + + // Step 2: The same request should also validate as ReadResourceRequest + const readResourceResult = ReadResourceRequestSchema.safeParse(jsonRpcRequest); + expect(readResourceResult.success).toBe(true); + }); + }); }); From 360738504a358d471c4cc7d0e4ca99ad6f7907c6 Mon Sep 17 00:00:00 2001 From: bhosmer-ant Date: Thu, 24 Jul 2025 04:36:39 -0400 Subject: [PATCH 6/6] Tweak strict types setup, fix type errors under strictTypes.ts (#806) --- package.json | 3 +- scripts/generateStrictTypes.ts | 33 ++++--- scripts/test-strict-types.js | 93 +++++++++++++++++++ scripts/test-strict-types.sh | 35 +++++++ src/client/index.test.ts | 46 +++++++-- src/client/index.ts | 43 ++++++--- .../taskResumability.test.ts | 12 +-- src/server/index.test.ts | 10 -- src/server/index.ts | 27 +++--- src/server/mcp.test.ts | 28 ++++-- src/server/mcp.ts | 2 +- src/server/title.test.ts | 8 +- src/strictTypes.ts | 91 ++++++++---------- 13 files changed, 297 insertions(+), 134 deletions(-) create mode 100644 scripts/test-strict-types.js create mode 100755 scripts/test-strict-types.sh diff --git a/package.json b/package.json index ef5f5d103..3a741fc84 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "fetch:spec-types": "curl -o spec.types.ts https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/refs/heads/main/schema/draft/schema.ts", "generate:strict-types": "tsx scripts/generateStrictTypes.ts", "check:strict-types": "npm run generate:strict-types && git diff --exit-code src/strictTypes.ts || (echo 'Error: strictTypes.ts is out of date. Run npm run generate:strict-types' && exit 1)", + "test:strict-types": "node scripts/test-strict-types.js", "build": "npm run build:esm && npm run build:cjs", "build:esm": "mkdir -p dist/esm && echo '{\"type\": \"module\"}' > dist/esm/package.json && tsc -p tsconfig.prod.json", "build:esm:w": "npm run build:esm -- -w", @@ -46,7 +47,7 @@ "examples:simple-server:w": "tsx --watch src/examples/server/simpleStreamableHttp.ts --oauth", "prepack": "npm run build:esm && npm run build:cjs", "lint": "eslint src/", - "test": "npm run fetch:spec-types && jest", + "test": "npm run fetch:spec-types && jest && npm run test:strict-types", "start": "npm run server", "server": "tsx watch --clear-screen=false src/cli.ts server", "client": "tsx src/cli.ts client" diff --git a/scripts/generateStrictTypes.ts b/scripts/generateStrictTypes.ts index 6c9ec2097..6bfa29d2e 100755 --- a/scripts/generateStrictTypes.ts +++ b/scripts/generateStrictTypes.ts @@ -11,6 +11,10 @@ const strictTypesPath = join(__dirname, '../src/strictTypes.ts'); let content = readFileSync(typesPath, 'utf-8'); +// Remove the @deprecated comment block +const deprecatedCommentPattern = /\/\*\*\s*\n\s*\*\s*@deprecated[\s\S]*?\*\/\s*\n/; +content = content.replace(deprecatedCommentPattern, ''); + // Add header comment const header = `/** * Types remove unknown @@ -24,37 +28,40 @@ const header = `/** `; -// Replace all .passthrough() with .strip() -content = content.replace(/\.passthrough\(\)/g, '.strip()'); +// Replace all .passthrough() with a temporary marker +content = content.replace(/\.passthrough\(\)/g, '.__TEMP_MARKED_FOR_REMOVAL__()'); // Special handling for experimental and capabilities that should remain open // These are explicitly designed to be extensible const patternsToKeepOpen = [ // Keep experimental fields open as they're meant for extensions - /experimental: z\.optional\(z\.object\(\{\}\)\.strip\(\)\)/g, + /experimental: z\.optional\(z\.object\(\{\}\)\.__TEMP_MARKED_FOR_REMOVAL__\(\)\)/g, // Keep _meta fields open as they're meant for arbitrary metadata - /_meta: z\.optional\(z\.object\(\{\}\)\.strip\(\)\)/g, + /_meta: z\.optional\(z\.object\(\{\}\)\.__TEMP_MARKED_FOR_REMOVAL__\(\)\)/g, // Keep JSON Schema properties open as they can have arbitrary fields - /properties: z\.optional\(z\.object\(\{\}\)\.strip\(\)\)/g, + /properties: z\.optional\(z\.object\(\{\}\)\.__TEMP_MARKED_FOR_REMOVAL__\(\)\)/g, // Keep BaseRequestParamsSchema passthrough for JSON-RPC param compatibility - /const BaseRequestParamsSchema = z\s*\n\s*\.object\([\s\S]*?\)\s*\n\s*\.strip\(\)/g, + /const BaseRequestParamsSchema = z\s*\n\s*\.object\([\s\S]*?\)\s*\n\s*\.__TEMP_MARKED_FOR_REMOVAL__\(\)/g, // Keep BaseNotificationParamsSchema passthrough for JSON-RPC param compatibility - /const BaseNotificationParamsSchema = z\s*\n\s*\.object\([\s\S]*?\)\s*\n\s*\.strip\(\)/g, + /const BaseNotificationParamsSchema = z\s*\n\s*\.object\([\s\S]*?\)\s*\n\s*\.__TEMP_MARKED_FOR_REMOVAL__\(\)/g, // Keep RequestMetaSchema passthrough for extensibility - /const RequestMetaSchema = z\s*\n\s*\.object\([\s\S]*?\)\s*\n\s*\.strip\(\)/g, + /const RequestMetaSchema = z\s*\n\s*\.object\([\s\S]*?\)\s*\n\s*\.__TEMP_MARKED_FOR_REMOVAL__\(\)/g, // Keep structuredContent passthrough for tool-specific output - /structuredContent: z\.object\(\{\}\)\.strip\(\)\.optional\(\)/g, + /structuredContent: z\.object\(\{\}\)\.__TEMP_MARKED_FOR_REMOVAL__\(\)\.optional\(\)/g, // Keep metadata passthrough for provider-specific data in sampling - /metadata: z\.optional\(z\.object\(\{\}\)\.strip\(\)\)/g, + /metadata: z\.optional\(z\.object\(\{\}\)\.__TEMP_MARKED_FOR_REMOVAL__\(\)\)/g, ]; -// Revert strip back to passthrough for these special cases +// Revert marker back to passthrough for these special cases patternsToKeepOpen.forEach(pattern => { content = content.replace(pattern, (match) => - match.replace('.strip()', '.passthrough()') + match.replace('.__TEMP_MARKED_FOR_REMOVAL__()', '.passthrough()') ); }); +// Remove the temporary marker from all remaining locations (these become no modifier) +content = content.replace(/\.__TEMP_MARKED_FOR_REMOVAL__\(\)/g, ''); + // Add a comment explaining the difference const explanation = ` /** @@ -68,7 +75,7 @@ const explanation = ` * - structuredContent: Tool-specific output that can have arbitrary fields * - metadata: Provider-specific metadata in sampling requests * - * All other objects use .strip() to remove unknown properties while + * All other objects use default behavior (no modifier) to remove unknown properties while * maintaining compatibility with extended protocols. */ `; diff --git a/scripts/test-strict-types.js b/scripts/test-strict-types.js new file mode 100644 index 000000000..bad99ee17 --- /dev/null +++ b/scripts/test-strict-types.js @@ -0,0 +1,93 @@ +#!/usr/bin/env node + +import { execSync } from 'child_process'; +import { readFileSync, writeFileSync, existsSync } from 'fs'; +import { join, dirname } from 'path'; +import { fileURLToPath } from 'url'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const rootDir = join(__dirname, '..'); + +const files = [ + 'src/client/index.ts', + 'src/server/index.ts', + 'src/server/mcp.ts' +]; + +console.log('Testing strict types compatibility...'); +console.log('======================================\n'); + +// Backup original files +const backups = {}; +files.forEach(file => { + const fullPath = join(rootDir, file); + if (existsSync(fullPath)) { + backups[file] = readFileSync(fullPath, 'utf8'); + + // Replace imports + const content = backups[file]; + const newContent = content.replace(/from "\.\.\/types\.js"/g, 'from "../strictTypes.js"'); + writeFileSync(fullPath, newContent); + console.log(`✓ Replaced imports in ${file}`); + } +}); + +console.log('\nRunning TypeScript compilation...\n'); + +try { + // Run TypeScript compilation + execSync('npm run build', { cwd: rootDir, stdio: 'pipe' }); + console.log('✓ No type errors found!'); +} catch (error) { + // Extract and format type errors + const output = error.stdout?.toString() || error.stderr?.toString() || ''; + const lines = output.split('\n'); + + const errors = []; + let currentError = null; + + lines.forEach((line, i) => { + if (line.includes('error TS')) { + if (currentError) { + errors.push(currentError); + } + currentError = { + file: line.split('(')[0], + location: line.match(/\((\d+),(\d+)\)/)?.[0] || '', + code: line.match(/error (TS\d+)/)?.[1] || '', + message: line.split(/error TS\d+:/)[1]?.trim() || '', + context: [] + }; + } else if (currentError && line.trim() && !line.startsWith('npm ')) { + currentError.context.push(line); + } + }); + + if (currentError) { + errors.push(currentError); + } + + // Display errors + console.log(`Found ${errors.length} type error(s):\n`); + + errors.forEach((error, index) => { + console.log(`${index + 1}. ${error.file}${error.location}`); + console.log(` Error ${error.code}: ${error.message}`); + if (error.context.length > 0) { + console.log(` Context:`); + error.context.slice(0, 3).forEach(line => { + console.log(` ${line.trim()}`); + }); + } + console.log(''); + }); +} + +// Restore original files +console.log('Restoring original files...'); +Object.entries(backups).forEach(([file, content]) => { + const fullPath = join(rootDir, file); + writeFileSync(fullPath, content); +}); + +console.log('✓ Original files restored.'); \ No newline at end of file diff --git a/scripts/test-strict-types.sh b/scripts/test-strict-types.sh new file mode 100755 index 000000000..c9f2ce320 --- /dev/null +++ b/scripts/test-strict-types.sh @@ -0,0 +1,35 @@ +#!/bin/bash + +# Script to test strict types by replacing imports and running tests + +echo "Testing strict types compatibility..." +echo "======================================" + +# Save original files +cp src/client/index.ts src/client/index.ts.bak +cp src/server/index.ts src/server/index.ts.bak +cp src/server/mcp.ts src/server/mcp.ts.bak + +# Replace imports +sed -i '' 's/from "\.\.\/types\.js"/from "..\/strictTypes.js"/g' src/client/index.ts +sed -i '' 's/from "\.\.\/types\.js"/from "..\/strictTypes.js"/g' src/server/index.ts +sed -i '' 's/from "\.\.\/types\.js"/from "..\/strictTypes.js"/g' src/server/mcp.ts + +echo "Replaced imports in:" +echo " - src/client/index.ts" +echo " - src/server/index.ts" +echo " - src/server/mcp.ts" +echo "" + +# Run TypeScript compilation to get type errors +echo "Running TypeScript compilation..." +echo "" +npm run build 2>&1 | grep -E "(error TS|src/)" | grep -B1 "error TS" || true + +# Restore original files +mv src/client/index.ts.bak src/client/index.ts +mv src/server/index.ts.bak src/server/index.ts +mv src/server/mcp.ts.bak src/server/mcp.ts + +echo "" +echo "Original files restored." \ No newline at end of file diff --git a/src/client/index.test.ts b/src/client/index.test.ts index abd0c34e4..0fe5c29d8 100644 --- a/src/client/index.test.ts +++ b/src/client/index.test.ts @@ -217,11 +217,11 @@ test("should connect new client to old, supported server version", async () => { const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + // Client initialization automatically uses LATEST_PROTOCOL_VERSION in the current SDK const client = new Client( { name: "new client", version: "1.0", - protocolVersion: LATEST_PROTOCOL_VERSION, }, { capabilities: { @@ -287,7 +287,6 @@ test("should negotiate version when client is old, and newer server supports its { name: "old client", version: "1.0", - protocolVersion: OLD_VERSION, }, { capabilities: { @@ -297,6 +296,17 @@ test("should negotiate version when client is old, and newer server supports its }, ); + // Mock the request method to simulate an old client sending OLD_VERSION + const originalRequest = client.request.bind(client); + client.request = jest.fn(async (request, schema, options) => { + // If this is the initialize request, modify the protocol version to simulate old client + if (request.method === "initialize" && request.params) { + request.params.protocolVersion = OLD_VERSION; + } + // Call the original request method with the potentially modified request + return originalRequest(request, schema, options); + }); + await Promise.all([ client.connect(clientTransport), server.connect(serverTransport), @@ -350,11 +360,13 @@ test("should throw when client is old, and server doesn't support its version", const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + // Client uses LATEST_PROTOCOL_VERSION by default, which is sufficient for this test + // The error occurs because the server returns FUTURE_VERSION (unsupported), + // not because of the client's version. Any client version would fail here. const client = new Client( { name: "old client", version: "1.0", - protocolVersion: OLD_VERSION, }, { capabilities: { @@ -880,6 +892,7 @@ describe('outputSchema validation', () => { server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name === 'test-tool') { return { + content: [], // Required field for CallToolResult structuredContent: { result: 'success', count: 42 }, }; } @@ -903,7 +916,11 @@ describe('outputSchema validation', () => { // Call the tool - should validate successfully const result = await client.callTool({ name: 'test-tool' }); - expect(result.structuredContent).toEqual({ result: 'success', count: 42 }); + // Type narrowing: check if structuredContent exists before accessing + expect('structuredContent' in result).toBe(true); + if ('structuredContent' in result) { + expect(result.structuredContent).toEqual({ result: 'success', count: 42 }); + } }); /*** @@ -955,6 +972,7 @@ describe('outputSchema validation', () => { if (request.params.name === 'test-tool') { // Return invalid structured content (count is string instead of number) return { + content: [], // Required field for CallToolResult structuredContent: { result: 'success', count: 'not a number' }, }; } @@ -1120,7 +1138,11 @@ describe('outputSchema validation', () => { // Call the tool - should work normally without validation const result = await client.callTool({ name: 'test-tool' }); - expect(result.content).toEqual([{ type: 'text', text: 'Normal response' }]); + // Type narrowing: check if content exists before accessing + expect('content' in result).toBe(true); + if ('content' in result) { + expect(result.content).toEqual([{ type: 'text', text: 'Normal response' }]); + } }); /*** @@ -1184,6 +1206,7 @@ describe('outputSchema validation', () => { server.setRequestHandler(CallToolRequestSchema, async (request) => { if (request.params.name === 'complex-tool') { return { + content: [], // Required field for CallToolResult structuredContent: { name: 'John Doe', age: 30, @@ -1215,10 +1238,14 @@ describe('outputSchema validation', () => { // Call the tool - should validate successfully const result = await client.callTool({ name: 'complex-tool' }); - expect(result.structuredContent).toBeDefined(); - const structuredContent = result.structuredContent as { name: string; age: number }; - expect(structuredContent.name).toBe('John Doe'); - expect(structuredContent.age).toBe(30); + // Type narrowing: check if structuredContent exists before accessing + expect('structuredContent' in result).toBe(true); + if ('structuredContent' in result) { + expect(result.structuredContent).toBeDefined(); + const structuredContent = result.structuredContent as { name: string; age: number }; + expect(structuredContent.name).toBe('John Doe'); + expect(structuredContent.age).toBe(30); + } }); /*** @@ -1269,6 +1296,7 @@ describe('outputSchema validation', () => { if (request.params.name === 'strict-tool') { // Return structured content with extra property return { + content: [], // Required field for CallToolResult structuredContent: { name: 'John', extraField: 'not allowed', diff --git a/src/client/index.ts b/src/client/index.ts index 3e8d8ec80..10ad35b53 100644 --- a/src/client/index.ts +++ b/src/client/index.ts @@ -42,6 +42,16 @@ import { Tool, ErrorCode, McpError, + EmptyResult, + CompleteResult, + GetPromptResult, + ListPromptsResult, + ListResourcesResult, + ListResourceTemplatesResult, + ReadResourceResult, + CompatibilityCallToolResult, + CallToolResult, + ListToolsResult, } from "../types.js"; import Ajv from "ajv"; import type { ValidateFunction } from "ajv"; @@ -329,11 +339,11 @@ export class Client< } } - async ping(options?: RequestOptions) { + async ping(options?: RequestOptions): Promise { return this.request({ method: "ping" }, EmptyResultSchema, options); } - async complete(params: CompleteRequest["params"], options?: RequestOptions) { + async complete(params: CompleteRequest["params"], options?: RequestOptions): Promise { return this.request( { method: "completion/complete", params }, CompleteResultSchema, @@ -341,7 +351,7 @@ export class Client< ); } - async setLoggingLevel(level: LoggingLevel, options?: RequestOptions) { + async setLoggingLevel(level: LoggingLevel, options?: RequestOptions): Promise { return this.request( { method: "logging/setLevel", params: { level } }, EmptyResultSchema, @@ -352,7 +362,7 @@ export class Client< async getPrompt( params: GetPromptRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "prompts/get", params }, GetPromptResultSchema, @@ -363,7 +373,7 @@ export class Client< async listPrompts( params?: ListPromptsRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "prompts/list", params }, ListPromptsResultSchema, @@ -374,7 +384,7 @@ export class Client< async listResources( params?: ListResourcesRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "resources/list", params }, ListResourcesResultSchema, @@ -385,7 +395,7 @@ export class Client< async listResourceTemplates( params?: ListResourceTemplatesRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "resources/templates/list", params }, ListResourceTemplatesResultSchema, @@ -396,7 +406,7 @@ export class Client< async readResource( params: ReadResourceRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "resources/read", params }, ReadResourceResultSchema, @@ -407,7 +417,7 @@ export class Client< async subscribeResource( params: SubscribeRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "resources/subscribe", params }, EmptyResultSchema, @@ -418,7 +428,7 @@ export class Client< async unsubscribeResource( params: UnsubscribeRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "resources/unsubscribe", params }, EmptyResultSchema, @@ -432,7 +442,8 @@ export class Client< | typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema = CallToolResultSchema, options?: RequestOptions, - ) { + ): Promise { + // Ensure the tool name is provided const result = await this.request( { method: "tools/call", params }, resultSchema, @@ -443,7 +454,11 @@ export class Client< const validator = this.getToolOutputValidator(params.name); if (validator) { // If tool has outputSchema, it MUST return structuredContent (unless it's an error) - if (!result.structuredContent && !result.isError) { + // Use property presence checks for union type compatibility + const hasStructuredContent = 'structuredContent' in result && result.structuredContent !== undefined; + const hasError = 'isError' in result && result.isError; + + if (!hasStructuredContent && !hasError) { throw new McpError( ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content` @@ -451,7 +466,7 @@ export class Client< } // Only validate structured content if present (not when there's an error) - if (result.structuredContent) { + if (hasStructuredContent) { try { // Validate the structured content (which is already an object) against the schema const isValid = validator(result.structuredContent); @@ -500,7 +515,7 @@ export class Client< async listTools( params?: ListToolsRequest["params"], options?: RequestOptions, - ) { + ): Promise { const result = await this.request( { method: "tools/list", params }, ListToolsResultSchema, diff --git a/src/integration-tests/taskResumability.test.ts b/src/integration-tests/taskResumability.test.ts index efd2611f8..fbd39a1ab 100644 --- a/src/integration-tests/taskResumability.test.ts +++ b/src/integration-tests/taskResumability.test.ts @@ -149,15 +149,14 @@ describe('Transport resumability', () => { // This test demonstrates the capability to resume long-running tools // across client disconnection/reconnection it('should resume long-running notifications with lastEventId', async () => { - // Create unique client ID for this test - const clientId = 'test-client-long-running'; + // Create unique client name for this test + const clientName = 'test-client-long-running'; const notifications = []; let lastEventId: string | undefined; // Create first client const client1 = new Client({ - id: clientId, - name: 'test-client', + name: clientName, version: '1.0.0' }); @@ -225,10 +224,9 @@ describe('Transport resumability', () => { await catchPromise; - // Create second client with same client ID + // Create second client with same client name const client2 = new Client({ - id: clientId, - name: 'test-client', + name: clientName, version: '1.0.0' }); diff --git a/src/server/index.test.ts b/src/server/index.test.ts index 46205d726..912f84a15 100644 --- a/src/server/index.test.ts +++ b/src/server/index.test.ts @@ -730,11 +730,6 @@ test("should handle server cancelling a request", async () => { name: "test server", version: "1.0", }, - { - capabilities: { - sampling: {}, - }, - }, ); const client = new Client( @@ -798,11 +793,6 @@ test("should handle request timeout", async () => { name: "test server", version: "1.0", }, - { - capabilities: { - sampling: {}, - }, - }, ); // Set up client that delays responses diff --git a/src/server/index.ts b/src/server/index.ts index 10ae2fadc..8e76aaf77 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -7,10 +7,12 @@ import { import { ClientCapabilities, CreateMessageRequest, + CreateMessageResult, CreateMessageResultSchema, ElicitRequest, ElicitResult, ElicitResultSchema, + EmptyResult, EmptyResultSchema, Implementation, InitializedNotificationSchema, @@ -19,6 +21,7 @@ import { InitializeResult, LATEST_PROTOCOL_VERSION, ListRootsRequest, + ListRootsResult, ListRootsResultSchema, LoggingMessageNotification, McpError, @@ -206,14 +209,6 @@ export class Server< protected assertRequestHandlerCapability(method: string): void { switch (method) { - case "sampling/createMessage": - if (!this._capabilities.sampling) { - throw new Error( - `Server does not support sampling (required for ${method})`, - ); - } - break; - case "logging/setLevel": if (!this._capabilities.logging) { throw new Error( @@ -295,14 +290,14 @@ export class Server< return this._capabilities; } - async ping() { + async ping(): Promise { return this.request({ method: "ping" }, EmptyResultSchema); } async createMessage( params: CreateMessageRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "sampling/createMessage", params }, CreateMessageResultSchema, @@ -351,7 +346,7 @@ export class Server< async listRoots( params?: ListRootsRequest["params"], options?: RequestOptions, - ) { + ): Promise { return this.request( { method: "roots/list", params }, ListRootsResultSchema, @@ -359,28 +354,28 @@ export class Server< ); } - async sendLoggingMessage(params: LoggingMessageNotification["params"]) { + async sendLoggingMessage(params: LoggingMessageNotification["params"]): Promise { return this.notification({ method: "notifications/message", params }); } - async sendResourceUpdated(params: ResourceUpdatedNotification["params"]) { + async sendResourceUpdated(params: ResourceUpdatedNotification["params"]): Promise { return this.notification({ method: "notifications/resources/updated", params, }); } - async sendResourceListChanged() { + async sendResourceListChanged(): Promise { return this.notification({ method: "notifications/resources/list_changed", }); } - async sendToolListChanged() { + async sendToolListChanged(): Promise { return this.notification({ method: "notifications/tools/list_changed" }); } - async sendPromptListChanged() { + async sendPromptListChanged(): Promise { return this.notification({ method: "notifications/prompts/list_changed" }); } } diff --git a/src/server/mcp.test.ts b/src/server/mcp.test.ts index 10e550df4..16b02a886 100644 --- a/src/server/mcp.test.ts +++ b/src/server/mcp.test.ts @@ -3626,11 +3626,10 @@ describe("prompt()", () => { }), }), { - name: "Template Name", description: "Template description", mimeType: "application/json", }, - async (uri) => ({ + async (uri: URL) => ({ contents: [ { uri: uri.href, @@ -4210,10 +4209,15 @@ describe("elicitInput()", () => { expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); expect(findAlternatives).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2, "same_week"); - expect(result.content).toEqual([{ - type: "text", - text: "Found these alternatives: 2024-12-26, 2024-12-27, 2024-12-28" - }]); + + // Type narrowing for union type + expect('content' in result).toBe(true); + if ('content' in result) { + expect(result.content).toEqual([{ + type: "text", + text: "Found these alternatives: 2024-12-26, 2024-12-27, 2024-12-28" + }]); + } }); test("should handle user declining to elicitation request", async () => { @@ -4249,10 +4253,14 @@ describe("elicitInput()", () => { expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); expect(findAlternatives).not.toHaveBeenCalled(); - expect(result.content).toEqual([{ + // Type narrowing for union type + expect('content' in result).toBe(true); + if ('content' in result) { + expect(result.content).toEqual([{ type: "text", text: "No booking made. Original date not available." }]); + } }); test("should handle user cancelling the elicitation", async () => { @@ -4285,9 +4293,13 @@ describe("elicitInput()", () => { expect(checkAvailability).toHaveBeenCalledWith("ABC Restaurant", "2024-12-25", 2); expect(findAlternatives).not.toHaveBeenCalled(); - expect(result.content).toEqual([{ + // Type narrowing for union type + expect('content' in result).toBe(true); + if ('content' in result) { + expect(result.content).toEqual([{ type: "text", text: "No booking made. Original date not available." }]); + } }); }); diff --git a/src/server/mcp.ts b/src/server/mcp.ts index 791facef1..69897ac3c 100644 --- a/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -313,7 +313,7 @@ export class McpServer { throw new McpError( ErrorCode.InvalidParams, - `Resource template ${request.params.ref.uri} not found`, + `Resource template ${'uri' in request.params.ref ? request.params.ref.uri : 'unknown'} not found`, ); } diff --git a/src/server/title.test.ts b/src/server/title.test.ts index 3f64570b8..3a9352dc4 100644 --- a/src/server/title.test.ts +++ b/src/server/title.test.ts @@ -208,7 +208,13 @@ describe("Title field backwards compatibility", () => { // Test reading the resource const readResult = await client.readResource({ uri: "users://123/profile" }); expect(readResult.contents).toHaveLength(1); - expect(readResult.contents[0].text).toBe("Profile data for user 123"); + + // Type narrowing for union type (text vs blob content) + const content = readResult.contents[0]; + expect('text' in content).toBe(true); + if ('text' in content) { + expect(content.text).toBe("Profile data for user 123"); + } }); it("should support serverInfo with title", async () => { diff --git a/src/strictTypes.ts b/src/strictTypes.ts index b59cfae0e..b13c43229 100644 --- a/src/strictTypes.ts +++ b/src/strictTypes.ts @@ -8,23 +8,6 @@ * @generated by scripts/generateStrictTypes.ts */ -/** - * @deprecated These extensible types with .strip() will be removed in a future version. - * - * For better type safety, use the types from "./strictTypes.js" instead. - * Those types use .strip() which provides compatibility with protocol extensions - * while ensuring type safety by removing unknown fields. - * - * Benefits of strictTypes.js: - * - Type safety: Only known fields are included in the result - * - No runtime errors: Unknown fields are silently stripped, not rejected - * - Protocol compatible: Works with extended servers/clients - * - * Migration guide: - * - Change: import { ToolSchema } from "@modelcontextprotocol/sdk/types.js" - * - To: import { ToolSchema } from "@modelcontextprotocol/sdk/strictTypes.js" - */ - import { z, ZodTypeAny } from "zod"; import { AuthInfo } from "./server/auth/types.js"; @@ -39,7 +22,7 @@ import { AuthInfo } from "./server/auth/types.js"; * - structuredContent: Tool-specific output that can have arbitrary fields * - metadata: Provider-specific metadata in sampling requests * - * All other objects use .strip() to remove unknown properties while + * All other objects use default behavior (no modifier) to remove unknown properties while * maintaining compatibility with extended protocols. */ @@ -108,7 +91,7 @@ export const ResultSchema = z */ _meta: z.optional(z.object({}).passthrough()), }) - .strip(); + ; /** * A uniquely identifying ID for a request in JSON-RPC. @@ -259,7 +242,7 @@ export const BaseMetadataSchema = z */ title: z.optional(z.string()), }) - .strip(); + ; /* Initialization */ /** @@ -281,11 +264,11 @@ export const ClientCapabilitiesSchema = z /** * Present if the client supports sampling from an LLM. */ - sampling: z.optional(z.object({}).strip()), + sampling: z.optional(z.object({})), /** * Present if the client supports eliciting user input. */ - elicitation: z.optional(z.object({}).strip()), + elicitation: z.optional(z.object({})), /** * Present if the client supports listing roots. */ @@ -297,10 +280,10 @@ export const ClientCapabilitiesSchema = z */ listChanged: z.optional(z.boolean()), }) - .strip(), + , ), }) - .strip(); + ; /** * This request is sent from the client to the server when it first connects, asking it to begin initialization. @@ -333,11 +316,11 @@ export const ServerCapabilitiesSchema = z /** * Present if the server supports sending log messages to the client. */ - logging: z.optional(z.object({}).strip()), + logging: z.optional(z.object({})), /** * Present if the server supports sending completions to the client. */ - completions: z.optional(z.object({}).strip()), + completions: z.optional(z.object({})), /** * Present if the server offers any prompt templates. */ @@ -349,7 +332,7 @@ export const ServerCapabilitiesSchema = z */ listChanged: z.optional(z.boolean()), }) - .strip(), + , ), /** * Present if the server offers any resources to read. @@ -367,7 +350,7 @@ export const ServerCapabilitiesSchema = z */ listChanged: z.optional(z.boolean()), }) - .strip(), + , ), /** * Present if the server offers any tools to call. @@ -380,10 +363,10 @@ export const ServerCapabilitiesSchema = z */ listChanged: z.optional(z.boolean()), }) - .strip(), + , ), }) - .strip(); + ; /** * After receiving an initialize request from the client, the server sends this response. @@ -437,7 +420,7 @@ export const ProgressSchema = z */ message: z.optional(z.string()), }) - .strip(); + ; /** * An out-of-band notification used to inform the receiver of a progress update for a long-running request. @@ -491,7 +474,7 @@ export const ResourceContentsSchema = z */ _meta: z.optional(z.object({}).passthrough()), }) - .strip(); + ; export const TextResourceContentsSchema = ResourceContentsSchema.extend({ /** @@ -700,7 +683,7 @@ export const PromptArgumentSchema = z */ required: z.optional(z.boolean()), }) - .strip(); + ; /** * A prompt or prompt template that the server offers. @@ -769,7 +752,7 @@ export const TextContentSchema = z */ _meta: z.optional(z.object({}).passthrough()), }) - .strip(); + ; /** * An image provided to or from an LLM. @@ -792,7 +775,7 @@ export const ImageContentSchema = z */ _meta: z.optional(z.object({}).passthrough()), }) - .strip(); + ; /** * An Audio provided to or from an LLM. @@ -815,7 +798,7 @@ export const AudioContentSchema = z */ _meta: z.optional(z.object({}).passthrough()), }) - .strip(); + ; /** * The contents of a resource, embedded into a prompt or tool call result. @@ -830,7 +813,7 @@ export const EmbeddedResourceSchema = z */ _meta: z.optional(z.object({}).passthrough()), }) - .strip(); + ; /** * A resource that the server is capable of reading, included in a prompt or tool call result. @@ -860,7 +843,7 @@ export const PromptMessageSchema = z role: z.enum(["user", "assistant"]), content: ContentBlockSchema, }) - .strip(); + ; /** * The server's response to a prompts/get request from the client. @@ -935,7 +918,7 @@ export const ToolAnnotationsSchema = z */ openWorldHint: z.optional(z.boolean()), }) - .strip(); + ; /** * Definition for a tool the client can call. @@ -954,7 +937,7 @@ export const ToolSchema = BaseMetadataSchema.extend({ properties: z.optional(z.object({}).passthrough()), required: z.optional(z.array(z.string())), }) - .strip(), + , /** * An optional JSON Schema object defining the structure of the tool's output returned in * the structuredContent field of a CallToolResult. @@ -965,7 +948,7 @@ export const ToolSchema = BaseMetadataSchema.extend({ properties: z.optional(z.object({}).passthrough()), required: z.optional(z.array(z.string())), }) - .strip() + ), /** * Optional additional tool information. @@ -1116,7 +1099,7 @@ export const ModelHintSchema = z */ name: z.string().optional(), }) - .strip(); + ; /** * The server's preferences for model selection, requested of the client during sampling. @@ -1140,7 +1123,7 @@ export const ModelPreferencesSchema = z */ intelligencePriority: z.optional(z.number().min(0).max(1)), }) - .strip(); + ; /** * Describes a message issued to or received from an LLM API. @@ -1150,7 +1133,7 @@ export const SamplingMessageSchema = z role: z.enum(["user", "assistant"]), content: z.union([TextContentSchema, ImageContentSchema, AudioContentSchema]), }) - .strip(); + ; /** * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. @@ -1217,7 +1200,7 @@ export const BooleanSchemaSchema = z description: z.optional(z.string()), default: z.optional(z.boolean()), }) - .strip(); + ; /** * Primitive schema definition for string fields. @@ -1231,7 +1214,7 @@ export const StringSchemaSchema = z maxLength: z.optional(z.number()), format: z.optional(z.enum(["email", "uri", "date", "date-time"])), }) - .strip(); + ; /** * Primitive schema definition for number fields. @@ -1244,7 +1227,7 @@ export const NumberSchemaSchema = z minimum: z.optional(z.number()), maximum: z.optional(z.number()), }) - .strip(); + ; /** * Primitive schema definition for enum fields. @@ -1257,7 +1240,7 @@ export const EnumSchemaSchema = z enum: z.array(z.string()), enumNames: z.optional(z.array(z.string())), }) - .strip(); + ; /** * Union of all primitive schema definitions. @@ -1289,7 +1272,7 @@ export const ElicitRequestSchema = RequestSchema.extend({ properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema), required: z.optional(z.array(z.string())), }) - .strip(), + , }), }); @@ -1319,7 +1302,7 @@ export const ResourceTemplateReferenceSchema = z */ uri: z.string(), }) - .strip(); + ; /** * @deprecated Use ResourceTemplateReferenceSchema instead @@ -1337,7 +1320,7 @@ export const PromptReferenceSchema = z */ name: z.string(), }) - .strip(); + ; /** * A request from the client to the server, to ask for completion options. @@ -1360,7 +1343,7 @@ export const CompleteRequestSchema = RequestSchema.extend({ */ value: z.string(), }) - .strip(), + , context: z.optional( z.object({ /** @@ -1391,7 +1374,7 @@ export const CompleteResultSchema = ResultSchema.extend({ */ hasMore: z.optional(z.boolean()), }) - .strip(), + , }); /* Roots */ @@ -1415,7 +1398,7 @@ export const RootSchema = z */ _meta: z.optional(z.object({}).passthrough()), }) - .strip(); + ; /** * Sent from the server to request a list of root URIs from the client.