@mcp-b/webmcp-ts-sdk 2.0.13 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -1
- package/dist/index.d.ts +12 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +48 -151
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["def","task","jsonrpcNotification","isPlainObject","Ajv","_addFormats","DEFAULT_INPUT_SCHEMA: InputSchema","isPlainObject","BaseMcpServer","enhancedOptions: ServerOptions","toolDescriptor: ToolDescriptor","item: ToolListItem","result"],"sources":["../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js","../src/stubs/ajv.ts","../src/stubs/ajv-formats.ts","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.27.1_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js","../src/polyfill-validator.ts","../src/browser-server.ts","../src/no-op-validator.ts"],"sourcesContent":["// zod-compat.ts\n// ----------------------------------------------------\n// Unified types + helpers to accept Zod v3 and v4 (Mini)\n// ----------------------------------------------------\nimport * as z3rt from 'zod/v3';\nimport * as z4mini from 'zod/v4-mini';\n// --- Runtime detection ---\nexport function isZ4Schema(s) {\n // Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3\n const schema = s;\n return !!schema._zod;\n}\n// --- Schema construction ---\nexport function objectFromShape(shape) {\n const values = Object.values(shape);\n if (values.length === 0)\n return z4mini.object({}); // default to v4 Mini\n const allV4 = values.every(isZ4Schema);\n const allV3 = values.every(s => !isZ4Schema(s));\n if (allV4)\n return z4mini.object(shape);\n if (allV3)\n return z3rt.object(shape);\n throw new Error('Mixed Zod versions detected in object shape.');\n}\n// --- Unified parsing ---\nexport function safeParse(schema, data) {\n if (isZ4Schema(schema)) {\n // Mini exposes top-level safeParse\n const result = z4mini.safeParse(schema, data);\n return result;\n }\n const v3Schema = schema;\n const result = v3Schema.safeParse(data);\n return result;\n}\nexport async function safeParseAsync(schema, data) {\n if (isZ4Schema(schema)) {\n // Mini exposes top-level safeParseAsync\n const result = await z4mini.safeParseAsync(schema, data);\n return result;\n }\n const v3Schema = schema;\n const result = await v3Schema.safeParseAsync(data);\n return result;\n}\n// --- Shape extraction ---\nexport function getObjectShape(schema) {\n if (!schema)\n return undefined;\n // Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape`\n let rawShape;\n if (isZ4Schema(schema)) {\n const v4Schema = schema;\n rawShape = v4Schema._zod?.def?.shape;\n }\n else {\n const v3Schema = schema;\n rawShape = v3Schema.shape;\n }\n if (!rawShape)\n return undefined;\n if (typeof rawShape === 'function') {\n try {\n return rawShape();\n }\n catch {\n return undefined;\n }\n }\n return rawShape;\n}\n// --- Schema normalization ---\n/**\n * Normalizes a schema to an object schema. Handles both:\n * - Already-constructed object schemas (v3 or v4)\n * - Raw shapes that need to be wrapped into object schemas\n */\nexport function normalizeObjectSchema(schema) {\n if (!schema)\n return undefined;\n // First check if it's a raw shape (Record<string, AnySchema>)\n // Raw shapes don't have _def or _zod properties and aren't schemas themselves\n if (typeof schema === 'object') {\n // Check if it's actually a ZodRawShapeCompat (not a schema instance)\n // by checking if it lacks schema-like internal properties\n const asV3 = schema;\n const asV4 = schema;\n // If it's not a schema instance (no _def or _zod), it might be a raw shape\n if (!asV3._def && !asV4._zod) {\n // Check if all values are schemas (heuristic to confirm it's a raw shape)\n const values = Object.values(schema);\n if (values.length > 0 &&\n values.every(v => typeof v === 'object' &&\n v !== null &&\n (v._def !== undefined ||\n v._zod !== undefined ||\n typeof v.parse === 'function'))) {\n return objectFromShape(schema);\n }\n }\n }\n // If we get here, it should be an AnySchema (not a raw shape)\n // Check if it's already an object schema\n if (isZ4Schema(schema)) {\n // Check if it's a v4 object\n const v4Schema = schema;\n const def = v4Schema._zod?.def;\n if (def && (def.type === 'object' || def.shape !== undefined)) {\n return schema;\n }\n }\n else {\n // Check if it's a v3 object\n const v3Schema = schema;\n if (v3Schema.shape !== undefined) {\n return schema;\n }\n }\n return undefined;\n}\n// --- Error message extraction ---\n/**\n * Safely extracts an error message from a parse result error.\n * Zod errors can have different structures, so we handle various cases.\n */\nexport function getParseErrorMessage(error) {\n if (error && typeof error === 'object') {\n // Try common error structures\n if ('message' in error && typeof error.message === 'string') {\n return error.message;\n }\n if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) {\n const firstIssue = error.issues[0];\n if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) {\n return String(firstIssue.message);\n }\n }\n // Fallback: try to stringify the error\n try {\n return JSON.stringify(error);\n }\n catch {\n return String(error);\n }\n }\n return String(error);\n}\n// --- Schema metadata access ---\n/**\n * Gets the description from a schema, if available.\n * Works with both Zod v3 and v4.\n *\n * Both versions expose a `.description` getter that returns the description\n * from their respective internal storage (v3: _def, v4: globalRegistry).\n */\nexport function getSchemaDescription(schema) {\n return schema.description;\n}\n/**\n * Checks if a schema is optional.\n * Works with both Zod v3 and v4.\n */\nexport function isSchemaOptional(schema) {\n if (isZ4Schema(schema)) {\n const v4Schema = schema;\n return v4Schema._zod?.def?.type === 'optional';\n }\n const v3Schema = schema;\n // v3 has isOptional() method\n if (typeof schema.isOptional === 'function') {\n return schema.isOptional();\n }\n return v3Schema._def?.typeName === 'ZodOptional';\n}\n/**\n * Gets the literal value from a schema, if it's a literal schema.\n * Works with both Zod v3 and v4.\n * Returns undefined if the schema is not a literal or the value cannot be determined.\n */\nexport function getLiteralValue(schema) {\n if (isZ4Schema(schema)) {\n const v4Schema = schema;\n const def = v4Schema._zod?.def;\n if (def) {\n // Try various ways to get the literal value\n if (def.value !== undefined)\n return def.value;\n if (Array.isArray(def.values) && def.values.length > 0) {\n return def.values[0];\n }\n }\n }\n const v3Schema = schema;\n const def = v3Schema._def;\n if (def) {\n if (def.value !== undefined)\n return def.value;\n if (Array.isArray(def.values) && def.values.length > 0) {\n return def.values[0];\n }\n }\n // Fallback: check for direct value property (some Zod versions)\n const directValue = schema.value;\n if (directValue !== undefined)\n return directValue;\n return undefined;\n}\n//# sourceMappingURL=zod-compat.js.map","import * as z from 'zod/v4';\nexport const LATEST_PROTOCOL_VERSION = '2025-11-25';\nexport const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26';\nexport const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07'];\nexport const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task';\n/* JSON-RPC types */\nexport const JSONRPC_VERSION = '2.0';\n/**\n * Assert 'object' type schema.\n *\n * @internal\n */\nconst AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function'));\n/**\n * A progress token, used to associate progress notifications with the original request.\n */\nexport const ProgressTokenSchema = z.union([z.string(), z.number().int()]);\n/**\n * An opaque token used to represent a cursor for pagination.\n */\nexport const CursorSchema = z.string();\n/**\n * Task creation parameters, used to ask that the server create a task to represent a request.\n */\nexport const TaskCreationParamsSchema = z.looseObject({\n /**\n * Time in milliseconds to keep task results available after completion.\n * If null, the task has unlimited lifetime until manually cleaned up.\n */\n ttl: z.union([z.number(), z.null()]).optional(),\n /**\n * Time in milliseconds to wait between task status requests.\n */\n pollInterval: z.number().optional()\n});\nexport const TaskMetadataSchema = z.object({\n ttl: z.number().optional()\n});\n/**\n * Metadata for associating messages with a task.\n * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.\n */\nexport const RelatedTaskMetadataSchema = z.object({\n taskId: z.string()\n});\nconst RequestMetaSchema = z.looseObject({\n /**\n * 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.\n */\n progressToken: ProgressTokenSchema.optional(),\n /**\n * If specified, this request is related to the provided task.\n */\n [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()\n});\n/**\n * Common params for any request.\n */\nconst BaseRequestParamsSchema = z.object({\n /**\n * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * Common params for any task-augmented request.\n */\nexport const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * If specified, the caller is requesting task-augmented execution for this request.\n * The request will return a CreateTaskResult immediately, and the actual result can be\n * retrieved later via tasks/result.\n *\n * Task augmentation is subject to capability negotiation - receivers MUST declare support\n * for task augmentation of specific request types in their capabilities.\n */\n task: TaskMetadataSchema.optional()\n});\n/**\n * Checks if a value is a valid TaskAugmentedRequestParams.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise.\n */\nexport const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;\nexport const RequestSchema = z.object({\n method: z.string(),\n params: BaseRequestParamsSchema.loose().optional()\n});\nconst NotificationsParamsSchema = z.object({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\nexport const NotificationSchema = z.object({\n method: z.string(),\n params: NotificationsParamsSchema.loose().optional()\n});\nexport const ResultSchema = z.looseObject({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * A uniquely identifying ID for a request in JSON-RPC.\n */\nexport const RequestIdSchema = z.union([z.string(), z.number().int()]);\n/**\n * A request that expects a response.\n */\nexport const JSONRPCRequestSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n ...RequestSchema.shape\n})\n .strict();\nexport const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;\n/**\n * A notification which does not expect a response.\n */\nexport const JSONRPCNotificationSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n ...NotificationSchema.shape\n})\n .strict();\nexport const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;\n/**\n * A successful (non-error) response to a request.\n */\nexport const JSONRPCResultResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n result: ResultSchema\n})\n .strict();\n/**\n * Checks if a value is a valid JSONRPCResultResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCResultResponse, false otherwise.\n */\nexport const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCResultResponse} instead.\n *\n * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse})\n */\nexport const isJSONRPCResponse = isJSONRPCResultResponse;\n/**\n * Error codes defined by the JSON-RPC specification.\n */\nexport var ErrorCode;\n(function (ErrorCode) {\n // SDK error codes\n ErrorCode[ErrorCode[\"ConnectionClosed\"] = -32000] = \"ConnectionClosed\";\n ErrorCode[ErrorCode[\"RequestTimeout\"] = -32001] = \"RequestTimeout\";\n // Standard JSON-RPC error codes\n ErrorCode[ErrorCode[\"ParseError\"] = -32700] = \"ParseError\";\n ErrorCode[ErrorCode[\"InvalidRequest\"] = -32600] = \"InvalidRequest\";\n ErrorCode[ErrorCode[\"MethodNotFound\"] = -32601] = \"MethodNotFound\";\n ErrorCode[ErrorCode[\"InvalidParams\"] = -32602] = \"InvalidParams\";\n ErrorCode[ErrorCode[\"InternalError\"] = -32603] = \"InternalError\";\n // MCP-specific error codes\n ErrorCode[ErrorCode[\"UrlElicitationRequired\"] = -32042] = \"UrlElicitationRequired\";\n})(ErrorCode || (ErrorCode = {}));\n/**\n * A response to a request that indicates an error occurred.\n */\nexport const JSONRPCErrorResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema.optional(),\n error: z.object({\n /**\n * The error type that occurred.\n */\n code: z.number().int(),\n /**\n * A short description of the error. The message SHOULD be limited to a concise single sentence.\n */\n message: z.string(),\n /**\n * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).\n */\n data: z.unknown().optional()\n })\n})\n .strict();\n/**\n * @deprecated Use {@link JSONRPCErrorResponseSchema} instead.\n */\nexport const JSONRPCErrorSchema = JSONRPCErrorResponseSchema;\n/**\n * Checks if a value is a valid JSONRPCErrorResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise.\n */\nexport const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCErrorResponse} instead.\n */\nexport const isJSONRPCError = isJSONRPCErrorResponse;\nexport const JSONRPCMessageSchema = z.union([\n JSONRPCRequestSchema,\n JSONRPCNotificationSchema,\n JSONRPCResultResponseSchema,\n JSONRPCErrorResponseSchema\n]);\nexport const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);\n/* Empty result */\n/**\n * A response that indicates success but carries no data.\n */\nexport const EmptyResultSchema = ResultSchema.strict();\nexport const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the request to cancel.\n *\n * This MUST correspond to the ID of a request previously issued in the same direction.\n */\n requestId: RequestIdSchema.optional(),\n /**\n * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.\n */\n reason: z.string().optional()\n});\n/* Cancellation */\n/**\n * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n *\n * 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.\n *\n * This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n *\n * A client MUST NOT attempt to cancel its `initialize` request.\n */\nexport const CancelledNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/cancelled'),\n params: CancelledNotificationParamsSchema\n});\n/* Base Metadata */\n/**\n * Icon schema for use in tools, prompts, resources, and implementations.\n */\nexport const IconSchema = z.object({\n /**\n * URL or data URI for the icon.\n */\n src: z.string(),\n /**\n * Optional MIME type for the icon.\n */\n mimeType: z.string().optional(),\n /**\n * Optional array of strings that specify sizes at which the icon can be used.\n * Each string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n *\n * If not provided, the client should assume that the icon can be used at any size.\n */\n sizes: z.array(z.string()).optional(),\n /**\n * Optional specifier for the theme this icon is designed for. `light` indicates\n * the icon is designed to be used with a light background, and `dark` indicates\n * the icon is designed to be used with a dark background.\n *\n * If not provided, the client should assume the icon can be used with any theme.\n */\n theme: z.enum(['light', 'dark']).optional()\n});\n/**\n * Base schema to add `icons` property.\n *\n */\nexport const IconsSchema = z.object({\n /**\n * Optional set of sized icons that the client can display in a user interface.\n *\n * Clients that support rendering icons MUST support at least the following MIME types:\n * - `image/png` - PNG images (safe, universal compatibility)\n * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n *\n * Clients that support rendering icons SHOULD also support:\n * - `image/svg+xml` - SVG images (scalable but requires security precautions)\n * - `image/webp` - WebP images (modern, efficient format)\n */\n icons: z.array(IconSchema).optional()\n});\n/**\n * Base metadata interface for common properties across resources, tools, prompts, and implementations.\n */\nexport const BaseMetadataSchema = z.object({\n /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */\n name: z.string(),\n /**\n * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\n * even by those unfamiliar with domain-specific terminology.\n *\n * If not provided, the name should be used for display (except for Tool,\n * where `annotations.title` should be given precedence over using `name`,\n * if present).\n */\n title: z.string().optional()\n});\n/* Initialization */\n/**\n * Describes the name and version of an MCP implementation.\n */\nexport const ImplementationSchema = BaseMetadataSchema.extend({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n version: z.string(),\n /**\n * An optional URL of the website for this implementation.\n */\n websiteUrl: z.string().optional(),\n /**\n * An optional human-readable description of what this implementation does.\n *\n * This can be used by clients or servers to provide context about their purpose\n * and capabilities. For example, a server might describe the types of resources\n * or tools it provides, while a client might describe its intended use case.\n */\n description: z.string().optional()\n});\nconst FormElicitationCapabilitySchema = z.intersection(z.object({\n applyDefaults: z.boolean().optional()\n}), z.record(z.string(), z.unknown()));\nconst ElicitationCapabilitySchema = z.preprocess(value => {\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n if (Object.keys(value).length === 0) {\n return { form: {} };\n }\n }\n return value;\n}, z.intersection(z.object({\n form: FormElicitationCapabilitySchema.optional(),\n url: AssertObjectSchema.optional()\n}), z.record(z.string(), z.unknown()).optional()));\n/**\n * Task capabilities for clients, indicating which request types support task creation.\n */\nexport const ClientTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the client supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the client supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for sampling requests.\n */\n sampling: z\n .looseObject({\n createMessage: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Task support for elicitation requests.\n */\n elicitation: z\n .looseObject({\n create: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Task capabilities for servers, indicating which request types support task creation.\n */\nexport const ServerTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the server supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the server supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for tool requests.\n */\n tools: z\n .looseObject({\n call: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * 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.\n */\nexport const ClientCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the client supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the client supports sampling from an LLM.\n */\n sampling: z\n .object({\n /**\n * Present if the client supports context inclusion via includeContext parameter.\n * If not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it).\n */\n context: AssertObjectSchema.optional(),\n /**\n * Present if the client supports tool use via tools and toolChoice parameters.\n */\n tools: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Present if the client supports eliciting user input.\n */\n elicitation: ElicitationCapabilitySchema.optional(),\n /**\n * Present if the client supports listing roots.\n */\n roots: z\n .object({\n /**\n * Whether the client supports issuing notifications for changes to the roots list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the client supports task creation.\n */\n tasks: ClientTasksCapabilitySchema.optional()\n});\nexport const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.\n */\n protocolVersion: z.string(),\n capabilities: ClientCapabilitiesSchema,\n clientInfo: ImplementationSchema\n});\n/**\n * This request is sent from the client to the server when it first connects, asking it to begin initialization.\n */\nexport const InitializeRequestSchema = RequestSchema.extend({\n method: z.literal('initialize'),\n params: InitializeRequestParamsSchema\n});\nexport const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success;\n/**\n * 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.\n */\nexport const ServerCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the server supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the server supports sending log messages to the client.\n */\n logging: AssertObjectSchema.optional(),\n /**\n * Present if the server supports sending completions to the client.\n */\n completions: AssertObjectSchema.optional(),\n /**\n * Present if the server offers any prompt templates.\n */\n prompts: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the prompt list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any resources to read.\n */\n resources: z\n .object({\n /**\n * Whether this server supports clients subscribing to resource updates.\n */\n subscribe: z.boolean().optional(),\n /**\n * Whether this server supports issuing notifications for changes to the resource list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any tools to call.\n */\n tools: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the tool list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server supports task creation.\n */\n tasks: ServerTasksCapabilitySchema.optional()\n});\n/**\n * After receiving an initialize request from the client, the server sends this response.\n */\nexport const InitializeResultSchema = ResultSchema.extend({\n /**\n * 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.\n */\n protocolVersion: z.string(),\n capabilities: ServerCapabilitiesSchema,\n serverInfo: ImplementationSchema,\n /**\n * Instructions describing how to use the server and its features.\n *\n * 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.\n */\n instructions: z.string().optional()\n});\n/**\n * This notification is sent from the client to the server after initialization has finished.\n */\nexport const InitializedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/initialized'),\n params: NotificationsParamsSchema.optional()\n});\nexport const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;\n/* Ping */\n/**\n * 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.\n */\nexport const PingRequestSchema = RequestSchema.extend({\n method: z.literal('ping'),\n params: BaseRequestParamsSchema.optional()\n});\n/* Progress notifications */\nexport const ProgressSchema = z.object({\n /**\n * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n */\n progress: z.number(),\n /**\n * Total number of items to process (or total progress required), if known.\n */\n total: z.optional(z.number()),\n /**\n * An optional message describing the current progress.\n */\n message: z.optional(z.string())\n});\nexport const ProgressNotificationParamsSchema = z.object({\n ...NotificationsParamsSchema.shape,\n ...ProgressSchema.shape,\n /**\n * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.\n */\n progressToken: ProgressTokenSchema\n});\n/**\n * An out-of-band notification used to inform the receiver of a progress update for a long-running request.\n *\n * @category notifications/progress\n */\nexport const ProgressNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/progress'),\n params: ProgressNotificationParamsSchema\n});\nexport const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * An opaque token representing the current pagination position.\n * If provided, the server should return results starting after this cursor.\n */\n cursor: CursorSchema.optional()\n});\n/* Pagination */\nexport const PaginatedRequestSchema = RequestSchema.extend({\n params: PaginatedRequestParamsSchema.optional()\n});\nexport const PaginatedResultSchema = ResultSchema.extend({\n /**\n * An opaque token representing the pagination position after the last returned result.\n * If present, there may be more results available.\n */\n nextCursor: CursorSchema.optional()\n});\n/**\n * The status of a task.\n * */\nexport const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']);\n/* Tasks */\n/**\n * A pollable state object associated with a request.\n */\nexport const TaskSchema = z.object({\n taskId: z.string(),\n status: TaskStatusSchema,\n /**\n * Time in milliseconds to keep task results available after completion.\n * If null, the task has unlimited lifetime until manually cleaned up.\n */\n ttl: z.union([z.number(), z.null()]),\n /**\n * ISO 8601 timestamp when the task was created.\n */\n createdAt: z.string(),\n /**\n * ISO 8601 timestamp when the task was last updated.\n */\n lastUpdatedAt: z.string(),\n pollInterval: z.optional(z.number()),\n /**\n * Optional diagnostic message for failed tasks or other status information.\n */\n statusMessage: z.optional(z.string())\n});\n/**\n * Result returned when a task is created, containing the task data wrapped in a task field.\n */\nexport const CreateTaskResultSchema = ResultSchema.extend({\n task: TaskSchema\n});\n/**\n * Parameters for task status notification.\n */\nexport const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);\n/**\n * A notification sent when a task's status changes.\n */\nexport const TaskStatusNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tasks/status'),\n params: TaskStatusNotificationParamsSchema\n});\n/**\n * A request to get the state of a specific task.\n */\nexport const GetTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/get'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/get request.\n */\nexport const GetTaskResultSchema = ResultSchema.merge(TaskSchema);\n/**\n * A request to get the result of a specific task.\n */\nexport const GetTaskPayloadRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/result'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/result request.\n * The structure matches the result type of the original request.\n * For example, a tools/call task would return the CallToolResult structure.\n *\n */\nexport const GetTaskPayloadResultSchema = ResultSchema.loose();\n/**\n * A request to list tasks.\n */\nexport const ListTasksRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tasks/list')\n});\n/**\n * The response to a tasks/list request.\n */\nexport const ListTasksResultSchema = PaginatedResultSchema.extend({\n tasks: z.array(TaskSchema)\n});\n/**\n * A request to cancel a specific task.\n */\nexport const CancelTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/cancel'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/cancel request.\n */\nexport const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);\n/* Resources */\n/**\n * The contents of a specific resource or sub-resource.\n */\nexport const ResourceContentsSchema = z.object({\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\nexport const TextResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * The text of the item. This must only be set if the item can actually be represented as text (not binary data).\n */\n text: z.string()\n});\n/**\n * A Zod schema for validating Base64 strings that is more performant and\n * robust for very large inputs than the default regex-based check. It avoids\n * stack overflows by using the native `atob` function for validation.\n */\nconst Base64Schema = z.string().refine(val => {\n try {\n // atob throws a DOMException if the string contains characters\n // that are not part of the Base64 character set.\n atob(val);\n return true;\n }\n catch {\n return false;\n }\n}, { message: 'Invalid Base64 string' });\nexport const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * A base64-encoded string representing the binary data of the item.\n */\n blob: Base64Schema\n});\n/**\n * The sender or recipient of messages and data in a conversation.\n */\nexport const RoleSchema = z.enum(['user', 'assistant']);\n/**\n * Optional annotations providing clients additional context about a resource.\n */\nexport const AnnotationsSchema = z.object({\n /**\n * Intended audience(s) for the resource.\n */\n audience: z.array(RoleSchema).optional(),\n /**\n * Importance hint for the resource, from 0 (least) to 1 (most).\n */\n priority: z.number().min(0).max(1).optional(),\n /**\n * ISO 8601 timestamp for the most recent modification.\n */\n lastModified: z.iso.datetime({ offset: true }).optional()\n});\n/**\n * A known resource that the server is capable of reading.\n */\nexport const ResourceSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * A description of what this resource represents.\n *\n * 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.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * A template description for resources available on the server.\n */\nexport const ResourceTemplateSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A URI template (according to RFC 6570) that can be used to construct resource URIs.\n */\n uriTemplate: z.string(),\n /**\n * A description of what this template is for.\n *\n * 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.\n */\n description: z.optional(z.string()),\n /**\n * 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.\n */\n mimeType: z.optional(z.string()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of resources the server has.\n */\nexport const ListResourcesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/list')\n});\n/**\n * The server's response to a resources/list request from the client.\n */\nexport const ListResourcesResultSchema = PaginatedResultSchema.extend({\n resources: z.array(ResourceSchema)\n});\n/**\n * Sent from the client to request a list of resource templates the server has.\n */\nexport const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/templates/list')\n});\n/**\n * The server's response to a resources/templates/list request from the client.\n */\nexport const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({\n resourceTemplates: z.array(ResourceTemplateSchema)\n});\nexport const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n *\n * @format uri\n */\n uri: z.string()\n});\n/**\n * Parameters for a `resources/read` request.\n */\nexport const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to the server, to read a specific resource URI.\n */\nexport const ReadResourceRequestSchema = RequestSchema.extend({\n method: z.literal('resources/read'),\n params: ReadResourceRequestParamsSchema\n});\n/**\n * The server's response to a resources/read request from the client.\n */\nexport const ReadResourceResultSchema = ResultSchema.extend({\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n});\n/**\n * 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.\n */\nexport const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\nexport const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.\n */\nexport const SubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/subscribe'),\n params: SubscribeRequestParamsSchema\n});\nexport const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.\n */\nexport const UnsubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/unsubscribe'),\n params: UnsubscribeRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/resources/updated` notification.\n */\nexport const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n */\n uri: z.string()\n});\n/**\n * 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.\n */\nexport const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/updated'),\n params: ResourceUpdatedNotificationParamsSchema\n});\n/* Prompts */\n/**\n * Describes an argument that a prompt can accept.\n */\nexport const PromptArgumentSchema = z.object({\n /**\n * The name of the argument.\n */\n name: z.string(),\n /**\n * A human-readable description of the argument.\n */\n description: z.optional(z.string()),\n /**\n * Whether this argument must be provided.\n */\n required: z.optional(z.boolean())\n});\n/**\n * A prompt or prompt template that the server offers.\n */\nexport const PromptSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * An optional description of what this prompt provides\n */\n description: z.optional(z.string()),\n /**\n * A list of arguments to use for templating the prompt.\n */\n arguments: z.optional(z.array(PromptArgumentSchema)),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of prompts and prompt templates the server has.\n */\nexport const ListPromptsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('prompts/list')\n});\n/**\n * The server's response to a prompts/list request from the client.\n */\nexport const ListPromptsResultSchema = PaginatedResultSchema.extend({\n prompts: z.array(PromptSchema)\n});\n/**\n * Parameters for a `prompts/get` request.\n */\nexport const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The name of the prompt or prompt template.\n */\n name: z.string(),\n /**\n * Arguments to use for templating the prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n});\n/**\n * Used by the client to get a prompt provided by the server.\n */\nexport const GetPromptRequestSchema = RequestSchema.extend({\n method: z.literal('prompts/get'),\n params: GetPromptRequestParamsSchema\n});\n/**\n * Text provided to or from an LLM.\n */\nexport const TextContentSchema = z.object({\n type: z.literal('text'),\n /**\n * The text content of the message.\n */\n text: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An image provided to or from an LLM.\n */\nexport const ImageContentSchema = z.object({\n type: z.literal('image'),\n /**\n * The base64-encoded image data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the image. Different providers may support different image types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An Audio provided to or from an LLM.\n */\nexport const AudioContentSchema = z.object({\n type: z.literal('audio'),\n /**\n * The base64-encoded audio data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the audio. Different providers may support different audio types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A tool call request from an assistant (LLM).\n * Represents the assistant's request to use a tool.\n */\nexport const ToolUseContentSchema = z.object({\n type: z.literal('tool_use'),\n /**\n * The name of the tool to invoke.\n * Must match a tool name from the request's tools array.\n */\n name: z.string(),\n /**\n * Unique identifier for this tool call.\n * Used to correlate with ToolResultContent in subsequent messages.\n */\n id: z.string(),\n /**\n * Arguments to pass to the tool.\n * Must conform to the tool's inputSchema.\n */\n input: z.record(z.string(), z.unknown()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * The contents of a resource, embedded into a prompt or tool call result.\n */\nexport const EmbeddedResourceSchema = z.object({\n type: z.literal('resource'),\n resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A resource that the server is capable of reading, included in a prompt or tool call result.\n *\n * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n */\nexport const ResourceLinkSchema = ResourceSchema.extend({\n type: z.literal('resource_link')\n});\n/**\n * A content block that can be used in prompts and tool results.\n */\nexport const ContentBlockSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ResourceLinkSchema,\n EmbeddedResourceSchema\n]);\n/**\n * Describes a message returned as part of a prompt.\n */\nexport const PromptMessageSchema = z.object({\n role: RoleSchema,\n content: ContentBlockSchema\n});\n/**\n * The server's response to a prompts/get request from the client.\n */\nexport const GetPromptResultSchema = ResultSchema.extend({\n /**\n * An optional description for the prompt.\n */\n description: z.string().optional(),\n messages: z.array(PromptMessageSchema)\n});\n/**\n * 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.\n */\nexport const PromptListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/prompts/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Tools */\n/**\n * Additional properties describing a Tool to clients.\n *\n * NOTE: all properties in ToolAnnotations are **hints**.\n * They are not guaranteed to provide a faithful description of\n * tool behavior (including descriptive properties like `title`).\n *\n * Clients should never make tool use decisions based on ToolAnnotations\n * received from untrusted servers.\n */\nexport const ToolAnnotationsSchema = z.object({\n /**\n * A human-readable title for the tool.\n */\n title: z.string().optional(),\n /**\n * If true, the tool does not modify its environment.\n *\n * Default: false\n */\n readOnlyHint: z.boolean().optional(),\n /**\n * If true, the tool may perform destructive updates to its environment.\n * If false, the tool performs only additive updates.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: true\n */\n destructiveHint: z.boolean().optional(),\n /**\n * If true, calling the tool repeatedly with the same arguments\n * will have no additional effect on the its environment.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: false\n */\n idempotentHint: z.boolean().optional(),\n /**\n * If true, this tool may interact with an \"open world\" of external\n * entities. If false, the tool's domain of interaction is closed.\n * For example, the world of a web search tool is open, whereas that\n * of a memory tool is not.\n *\n * Default: true\n */\n openWorldHint: z.boolean().optional()\n});\n/**\n * Execution-related properties for a tool.\n */\nexport const ToolExecutionSchema = z.object({\n /**\n * Indicates the tool's preference for task-augmented execution.\n * - \"required\": Clients MUST invoke the tool as a task\n * - \"optional\": Clients MAY invoke the tool as a task or normal request\n * - \"forbidden\": Clients MUST NOT attempt to invoke the tool as a task\n *\n * If not present, defaults to \"forbidden\".\n */\n taskSupport: z.enum(['required', 'optional', 'forbidden']).optional()\n});\n/**\n * Definition for a tool the client can call.\n */\nexport const ToolSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A human-readable description of the tool.\n */\n description: z.string().optional(),\n /**\n * A JSON Schema 2020-12 object defining the expected parameters for the tool.\n * Must have type: 'object' at the root level per MCP spec.\n */\n inputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown()),\n /**\n * An optional JSON Schema 2020-12 object defining the structure of the tool's output\n * returned in the structuredContent field of a CallToolResult.\n * Must have type: 'object' at the root level per MCP spec.\n */\n outputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown())\n .optional(),\n /**\n * Optional additional tool information.\n */\n annotations: ToolAnnotationsSchema.optional(),\n /**\n * Execution-related properties for this tool.\n */\n execution: ToolExecutionSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the client to request a list of tools the server has.\n */\nexport const ListToolsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tools/list')\n});\n/**\n * The server's response to a tools/list request from the client.\n */\nexport const ListToolsResultSchema = PaginatedResultSchema.extend({\n tools: z.array(ToolSchema)\n});\n/**\n * The server's response to a tool call.\n */\nexport const CallToolResultSchema = ResultSchema.extend({\n /**\n * A list of content objects that represent the result of the tool call.\n *\n * If the Tool does not define an outputSchema, this field MUST be present in the result.\n * For backwards compatibility, this field is always present, but it may be empty.\n */\n content: z.array(ContentBlockSchema).default([]),\n /**\n * An object containing structured tool output.\n *\n * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.\n */\n structuredContent: z.record(z.string(), z.unknown()).optional(),\n /**\n * Whether the tool call ended in an error.\n *\n * If not set, this is assumed to be false (the call was successful).\n *\n * Any errors that originate from the tool SHOULD be reported inside the result\n * object, with `isError` set to true, _not_ as an MCP protocol-level error\n * response. Otherwise, the LLM would not be able to see that an error occurred\n * and self-correct.\n *\n * However, any errors in _finding_ the tool, an error indicating that the\n * server does not support tool calls, or any other exceptional conditions,\n * should be reported as an MCP error response.\n */\n isError: z.boolean().optional()\n});\n/**\n * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07.\n */\nexport const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({\n toolResult: z.unknown()\n}));\n/**\n * Parameters for a `tools/call` request.\n */\nexport const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The name of the tool to call.\n */\n name: z.string(),\n /**\n * Arguments to pass to the tool.\n */\n arguments: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Used by the client to invoke a tool provided by the server.\n */\nexport const CallToolRequestSchema = RequestSchema.extend({\n method: z.literal('tools/call'),\n params: CallToolRequestParamsSchema\n});\n/**\n * 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.\n */\nexport const ToolListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tools/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/**\n * Base schema for list changed subscription options (without callback).\n * Used internally for Zod validation of autoRefresh and debounceMs.\n */\nexport const ListChangedOptionsBaseSchema = z.object({\n /**\n * If true, the list will be refreshed automatically when a list changed notification is received.\n * The callback will be called with the updated list.\n *\n * If false, the callback will be called with null items, allowing manual refresh.\n *\n * @default true\n */\n autoRefresh: z.boolean().default(true),\n /**\n * Debounce time in milliseconds for list changed notification processing.\n *\n * Multiple notifications received within this timeframe will only trigger one refresh.\n * Set to 0 to disable debouncing.\n *\n * @default 300\n */\n debounceMs: z.number().int().nonnegative().default(300)\n});\n/* Logging */\n/**\n * The severity of a log message.\n */\nexport const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n/**\n * Parameters for a `logging/setLevel` request.\n */\nexport const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * 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.\n */\n level: LoggingLevelSchema\n});\n/**\n * A request from the client to the server, to enable or adjust logging.\n */\nexport const SetLevelRequestSchema = RequestSchema.extend({\n method: z.literal('logging/setLevel'),\n params: SetLevelRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/message` notification.\n */\nexport const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The severity of this log message.\n */\n level: LoggingLevelSchema,\n /**\n * An optional name of the logger issuing this message.\n */\n logger: z.string().optional(),\n /**\n * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.\n */\n data: z.unknown()\n});\n/**\n * 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.\n */\nexport const LoggingMessageNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/message'),\n params: LoggingMessageNotificationParamsSchema\n});\n/* Sampling */\n/**\n * Hints to use for model selection.\n */\nexport const ModelHintSchema = z.object({\n /**\n * A hint for a model name.\n */\n name: z.string().optional()\n});\n/**\n * The server's preferences for model selection, requested of the client during sampling.\n */\nexport const ModelPreferencesSchema = z.object({\n /**\n * Optional hints to use for model selection.\n */\n hints: z.array(ModelHintSchema).optional(),\n /**\n * How much to prioritize cost when selecting a model.\n */\n costPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize sampling speed (latency) when selecting a model.\n */\n speedPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize intelligence and capabilities when selecting a model.\n */\n intelligencePriority: z.number().min(0).max(1).optional()\n});\n/**\n * Controls tool usage behavior in sampling requests.\n */\nexport const ToolChoiceSchema = z.object({\n /**\n * Controls when tools are used:\n * - \"auto\": Model decides whether to use tools (default)\n * - \"required\": Model MUST use at least one tool before completing\n * - \"none\": Model MUST NOT use any tools\n */\n mode: z.enum(['auto', 'required', 'none']).optional()\n});\n/**\n * The result of a tool execution, provided by the user (server).\n * Represents the outcome of invoking a tool requested via ToolUseContent.\n */\nexport const ToolResultContentSchema = z.object({\n type: z.literal('tool_result'),\n toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'),\n content: z.array(ContentBlockSchema).default([]),\n structuredContent: z.object({}).loose().optional(),\n isError: z.boolean().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Basic content types for sampling responses (without tool use).\n * Used for backwards-compatible CreateMessageResult when tools are not used.\n */\nexport const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);\n/**\n * Content block types allowed in sampling messages.\n * This includes text, image, audio, tool use requests, and tool results.\n */\nexport const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n ToolResultContentSchema\n]);\n/**\n * Describes a message issued to or received from an LLM API.\n */\nexport const SamplingMessageSchema = z.object({\n role: RoleSchema,\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Parameters for a `sampling/createMessage` request.\n */\nexport const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n messages: z.array(SamplingMessageSchema),\n /**\n * The server's preferences for which model to select. The client MAY modify or omit this request.\n */\n modelPreferences: ModelPreferencesSchema.optional(),\n /**\n * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.\n */\n systemPrompt: z.string().optional(),\n /**\n * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\n * The client MAY ignore this request.\n *\n * Default is \"none\". Values \"thisServer\" and \"allServers\" are soft-deprecated. Servers SHOULD only use these values if the client\n * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.\n */\n includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n temperature: z.number().optional(),\n /**\n * The requested maximum number of tokens to sample (to prevent runaway completions).\n *\n * The client MAY choose to sample fewer tokens than the requested maximum.\n */\n maxTokens: z.number().int(),\n stopSequences: z.array(z.string()).optional(),\n /**\n * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.\n */\n metadata: AssertObjectSchema.optional(),\n /**\n * Tools that the model may use during generation.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n */\n tools: z.array(ToolSchema).optional(),\n /**\n * Controls how the model uses tools.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n * Default is `{ mode: \"auto\" }`.\n */\n toolChoice: ToolChoiceSchema.optional()\n});\n/**\n * 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.\n */\nexport const CreateMessageRequestSchema = RequestSchema.extend({\n method: z.literal('sampling/createMessage'),\n params: CreateMessageRequestParamsSchema\n});\n/**\n * The client's response to a sampling/create_message request from the server.\n * This is the backwards-compatible version that returns single content (no arrays).\n * Used when the request does not include tools.\n */\nexport const CreateMessageResultSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. Single content block (text, image, or audio).\n */\n content: SamplingContentSchema\n});\n/**\n * The client's response to a sampling/create_message request when tools were provided.\n * This version supports array content for tool use flows.\n */\nexport const CreateMessageResultWithToolsSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n * - \"toolUse\": The model wants to use one or more tools\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. May be a single block or array. May include ToolUseContent if stopReason is \"toolUse\".\n */\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)])\n});\n/* Elicitation */\n/**\n * Primitive schema definition for boolean fields.\n */\nexport const BooleanSchemaSchema = z.object({\n type: z.literal('boolean'),\n title: z.string().optional(),\n description: z.string().optional(),\n default: z.boolean().optional()\n});\n/**\n * Primitive schema definition for string fields.\n */\nexport const StringSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),\n default: z.string().optional()\n});\n/**\n * Primitive schema definition for number fields.\n */\nexport const NumberSchemaSchema = z.object({\n type: z.enum(['number', 'integer']),\n title: z.string().optional(),\n description: z.string().optional(),\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n default: z.number().optional()\n});\n/**\n * Schema for single-selection enumeration without display titles for options.\n */\nexport const UntitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n default: z.string().optional()\n});\n/**\n * Schema for single-selection enumeration with display titles for each option.\n */\nexport const TitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n oneOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n })),\n default: z.string().optional()\n});\n/**\n * Use TitledSingleSelectEnumSchema instead.\n * This interface will be removed in a future version.\n */\nexport const LegacyTitledEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n enumNames: z.array(z.string()).optional(),\n default: z.string().optional()\n});\n// Combined single selection enumeration\nexport const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n/**\n * Schema for multiple-selection enumeration without display titles for options.\n */\nexport const UntitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n type: z.literal('string'),\n enum: z.array(z.string())\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Schema for multiple-selection enumeration with display titles for each option.\n */\nexport const TitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n anyOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n }))\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Combined schema for multiple-selection enumeration\n */\nexport const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n/**\n * Primitive schema definition for enum fields.\n */\nexport const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n/**\n * Union of all primitive schema definitions.\n */\nexport const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n/**\n * Parameters for an `elicitation/create` request for form-based elicitation.\n */\nexport const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n *\n * Optional for backward compatibility. Clients MUST treat missing mode as \"form\".\n */\n mode: z.literal('form').optional(),\n /**\n * The message to present to the user describing what information is being requested.\n */\n message: z.string(),\n /**\n * A restricted subset of JSON Schema.\n * Only top-level properties are allowed, without nesting.\n */\n requestedSchema: z.object({\n type: z.literal('object'),\n properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n required: z.array(z.string()).optional()\n })\n});\n/**\n * Parameters for an `elicitation/create` request for URL-based elicitation.\n */\nexport const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n */\n mode: z.literal('url'),\n /**\n * The message to present to the user explaining why the interaction is needed.\n */\n message: z.string(),\n /**\n * The ID of the elicitation, which must be unique within the context of the server.\n * The client MUST treat this ID as an opaque value.\n */\n elicitationId: z.string(),\n /**\n * The URL that the user should navigate to.\n */\n url: z.string().url()\n});\n/**\n * The parameters for a request to elicit additional information from the user via the client.\n */\nexport const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n/**\n * A request from the server to elicit user input via the client.\n * The client should present the message and form fields to the user (form mode)\n * or navigate to a URL (URL mode).\n */\nexport const ElicitRequestSchema = RequestSchema.extend({\n method: z.literal('elicitation/create'),\n params: ElicitRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/elicitation/complete` notification.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the elicitation that completed.\n */\n elicitationId: z.string()\n});\n/**\n * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/elicitation/complete'),\n params: ElicitationCompleteNotificationParamsSchema\n});\n/**\n * The client's response to an elicitation/create request from the server.\n */\nexport const ElicitResultSchema = ResultSchema.extend({\n /**\n * The user action in response to the elicitation.\n * - \"accept\": User submitted the form/confirmed the action\n * - \"decline\": User explicitly decline the action\n * - \"cancel\": User dismissed without making an explicit choice\n */\n action: z.enum(['accept', 'decline', 'cancel']),\n /**\n * The submitted form data, only present when action is \"accept\".\n * Contains values matching the requested schema.\n * Per MCP spec, content is \"typically omitted\" for decline/cancel actions.\n * We normalize null to undefined for leniency while maintaining type compatibility.\n */\n content: z.preprocess(val => (val === null ? undefined : val), z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional())\n});\n/* Autocomplete */\n/**\n * A reference to a resource or resource template definition.\n */\nexport const ResourceTemplateReferenceSchema = z.object({\n type: z.literal('ref/resource'),\n /**\n * The URI or URI template of the resource.\n */\n uri: z.string()\n});\n/**\n * @deprecated Use ResourceTemplateReferenceSchema instead\n */\nexport const ResourceReferenceSchema = ResourceTemplateReferenceSchema;\n/**\n * Identifies a prompt.\n */\nexport const PromptReferenceSchema = z.object({\n type: z.literal('ref/prompt'),\n /**\n * The name of the prompt or prompt template\n */\n name: z.string()\n});\n/**\n * Parameters for a `completion/complete` request.\n */\nexport const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({\n ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n /**\n * The argument's information\n */\n argument: z.object({\n /**\n * The name of the argument\n */\n name: z.string(),\n /**\n * The value of the argument to use for completion matching.\n */\n value: z.string()\n }),\n context: z\n .object({\n /**\n * Previously-resolved variables in a URI template or prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n })\n .optional()\n});\n/**\n * A request from the client to the server, to ask for completion options.\n */\nexport const CompleteRequestSchema = RequestSchema.extend({\n method: z.literal('completion/complete'),\n params: CompleteRequestParamsSchema\n});\nexport function assertCompleteRequestPrompt(request) {\n if (request.params.ref.type !== 'ref/prompt') {\n throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);\n }\n void request;\n}\nexport function assertCompleteRequestResourceTemplate(request) {\n if (request.params.ref.type !== 'ref/resource') {\n throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);\n }\n void request;\n}\n/**\n * The server's response to a completion/complete request\n */\nexport const CompleteResultSchema = ResultSchema.extend({\n completion: z.looseObject({\n /**\n * An array of completion values. Must not exceed 100 items.\n */\n values: z.array(z.string()).max(100),\n /**\n * The total number of completion options available. This can exceed the number of values actually sent in the response.\n */\n total: z.optional(z.number().int()),\n /**\n * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n */\n hasMore: z.optional(z.boolean())\n })\n});\n/* Roots */\n/**\n * Represents a root directory or file that the server can operate on.\n */\nexport const RootSchema = z.object({\n /**\n * The URI identifying the root. This *must* start with file:// for now.\n */\n uri: z.string().startsWith('file://'),\n /**\n * An optional name for the root.\n */\n name: z.string().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the server to request a list of root URIs from the client.\n */\nexport const ListRootsRequestSchema = RequestSchema.extend({\n method: z.literal('roots/list'),\n params: BaseRequestParamsSchema.optional()\n});\n/**\n * The client's response to a roots/list request from the server.\n */\nexport const ListRootsResultSchema = ResultSchema.extend({\n roots: z.array(RootSchema)\n});\n/**\n * A notification from the client to the server, informing it that the list of roots has changed.\n */\nexport const RootsListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/roots/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Client messages */\nexport const ClientRequestSchema = z.union([\n PingRequestSchema,\n InitializeRequestSchema,\n CompleteRequestSchema,\n SetLevelRequestSchema,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ReadResourceRequestSchema,\n SubscribeRequestSchema,\n UnsubscribeRequestSchema,\n CallToolRequestSchema,\n ListToolsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ClientNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n InitializedNotificationSchema,\n RootsListChangedNotificationSchema,\n TaskStatusNotificationSchema\n]);\nexport const ClientResultSchema = z.union([\n EmptyResultSchema,\n CreateMessageResultSchema,\n CreateMessageResultWithToolsSchema,\n ElicitResultSchema,\n ListRootsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\n/* Server messages */\nexport const ServerRequestSchema = z.union([\n PingRequestSchema,\n CreateMessageRequestSchema,\n ElicitRequestSchema,\n ListRootsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ServerNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n LoggingMessageNotificationSchema,\n ResourceUpdatedNotificationSchema,\n ResourceListChangedNotificationSchema,\n ToolListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n TaskStatusNotificationSchema,\n ElicitationCompleteNotificationSchema\n]);\nexport const ServerResultSchema = z.union([\n EmptyResultSchema,\n InitializeResultSchema,\n CompleteResultSchema,\n GetPromptResultSchema,\n ListPromptsResultSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesResultSchema,\n ReadResourceResultSchema,\n CallToolResultSchema,\n ListToolsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\nexport class McpError extends Error {\n constructor(code, message, data) {\n super(`MCP error ${code}: ${message}`);\n this.code = code;\n this.data = data;\n this.name = 'McpError';\n }\n /**\n * Factory method to create the appropriate error type based on the error code and data\n */\n static fromError(code, message, data) {\n // Check for specific error types\n if (code === ErrorCode.UrlElicitationRequired && data) {\n const errorData = data;\n if (errorData.elicitations) {\n return new UrlElicitationRequiredError(errorData.elicitations, message);\n }\n }\n // Default to generic McpError\n return new McpError(code, message, data);\n }\n}\n/**\n * Specialized error type when a tool requires a URL mode elicitation.\n * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against.\n */\nexport class UrlElicitationRequiredError extends McpError {\n constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) {\n super(ErrorCode.UrlElicitationRequired, message, {\n elicitations: elicitations\n });\n }\n get elicitations() {\n return this.data?.elicitations ?? [];\n }\n}\n//# sourceMappingURL=types.js.map","/**\n * Experimental task interfaces for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n */\n/**\n * Checks if a task status represents a terminal state.\n * Terminal states are those where the task has finished and will not change.\n *\n * @param status - The task status to check\n * @returns True if the status is terminal (completed, failed, or cancelled)\n * @experimental\n */\nexport function isTerminal(status) {\n return status === 'completed' || status === 'failed' || status === 'cancelled';\n}\n//# sourceMappingURL=interfaces.js.map","// zod-json-schema-compat.ts\n// ----------------------------------------------------\n// JSON Schema conversion for both Zod v3 and Zod v4 (Mini)\n// v3 uses your vendored converter; v4 uses Mini's toJSONSchema\n// ----------------------------------------------------\nimport * as z4mini from 'zod/v4-mini';\nimport { getObjectShape, safeParse, isZ4Schema, getLiteralValue } from './zod-compat.js';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nfunction mapMiniTarget(t) {\n if (!t)\n return 'draft-7';\n if (t === 'jsonSchema7' || t === 'draft-7')\n return 'draft-7';\n if (t === 'jsonSchema2019-09' || t === 'draft-2020-12')\n return 'draft-2020-12';\n return 'draft-7'; // fallback\n}\nexport function toJsonSchemaCompat(schema, opts) {\n if (isZ4Schema(schema)) {\n // v4 branch — use Mini's built-in toJSONSchema\n return z4mini.toJSONSchema(schema, {\n target: mapMiniTarget(opts?.target),\n io: opts?.pipeStrategy ?? 'input'\n });\n }\n // v3 branch — use vendored converter\n return zodToJsonSchema(schema, {\n strictUnions: opts?.strictUnions ?? true,\n pipeStrategy: opts?.pipeStrategy ?? 'input'\n });\n}\nexport function getMethodLiteral(schema) {\n const shape = getObjectShape(schema);\n const methodSchema = shape?.method;\n if (!methodSchema) {\n throw new Error('Schema is missing a method literal');\n }\n const value = getLiteralValue(methodSchema);\n if (typeof value !== 'string') {\n throw new Error('Schema method literal must be a string');\n }\n return value;\n}\nexport function parseWithCompat(schema, data) {\n const result = safeParse(schema, data);\n if (!result.success) {\n throw result.error;\n }\n return result.data;\n}\n//# sourceMappingURL=zod-json-schema-compat.js.map","import { safeParse } from '../server/zod-compat.js';\nimport { CancelledNotificationSchema, CreateTaskResultSchema, ErrorCode, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse, isJSONRPCNotification, McpError, PingRequestSchema, ProgressNotificationSchema, RELATED_TASK_META_KEY, TaskStatusNotificationSchema, isTaskAugmentedRequestParams } from '../types.js';\nimport { isTerminal } from '../experimental/tasks/interfaces.js';\nimport { getMethodLiteral, parseWithCompat } from '../server/zod-json-schema-compat.js';\n/**\n * The default request timeout, in miliseconds.\n */\nexport const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000;\n/**\n * Implements MCP protocol framing on top of a pluggable transport, including\n * features like request/response linking, notifications, and progress.\n */\nexport class Protocol {\n constructor(_options) {\n this._options = _options;\n this._requestMessageId = 0;\n this._requestHandlers = new Map();\n this._requestHandlerAbortControllers = new Map();\n this._notificationHandlers = new Map();\n this._responseHandlers = new Map();\n this._progressHandlers = new Map();\n this._timeoutInfo = new Map();\n this._pendingDebouncedNotifications = new Set();\n // Maps task IDs to progress tokens to keep handlers alive after CreateTaskResult\n this._taskProgressTokens = new Map();\n this._requestResolvers = new Map();\n this.setNotificationHandler(CancelledNotificationSchema, notification => {\n this._oncancel(notification);\n });\n this.setNotificationHandler(ProgressNotificationSchema, notification => {\n this._onprogress(notification);\n });\n this.setRequestHandler(PingRequestSchema, \n // Automatic pong by default.\n _request => ({}));\n // Install task handlers if TaskStore is provided\n this._taskStore = _options?.taskStore;\n this._taskMessageQueue = _options?.taskMessageQueue;\n if (this._taskStore) {\n this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {\n const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found');\n }\n // Per spec: tasks/get responses SHALL NOT include related-task metadata\n // as the taskId parameter is the source of truth\n // @ts-expect-error SendResultT cannot contain GetTaskResult, but we include it in our derived types everywhere else\n return {\n ...task\n };\n });\n this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {\n const handleTaskResult = async () => {\n const taskId = request.params.taskId;\n // Deliver queued messages\n if (this._taskMessageQueue) {\n let queuedMessage;\n while ((queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId))) {\n // Handle response and error messages by routing them to the appropriate resolver\n if (queuedMessage.type === 'response' || queuedMessage.type === 'error') {\n const message = queuedMessage.message;\n const requestId = message.id;\n // Lookup resolver in _requestResolvers map\n const resolver = this._requestResolvers.get(requestId);\n if (resolver) {\n // Remove resolver from map after invocation\n this._requestResolvers.delete(requestId);\n // Invoke resolver with response or error\n if (queuedMessage.type === 'response') {\n resolver(message);\n }\n else {\n // Convert JSONRPCError to McpError\n const errorMessage = message;\n const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);\n resolver(error);\n }\n }\n else {\n // Handle missing resolver gracefully with error logging\n const messageType = queuedMessage.type === 'response' ? 'Response' : 'Error';\n this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));\n }\n // Continue to next message\n continue;\n }\n // Send the message on the response stream by passing the relatedRequestId\n // This tells the transport to write the message to the tasks/result response stream\n await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });\n }\n }\n // Now check task status\n const task = await this._taskStore.getTask(taskId, extra.sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);\n }\n // Block if task is not terminal (we've already delivered all queued messages above)\n if (!isTerminal(task.status)) {\n // Wait for status change or new messages\n await this._waitForTaskUpdate(taskId, extra.signal);\n // After waking up, recursively call to deliver any new messages or result\n return await handleTaskResult();\n }\n // If task is terminal, return the result\n if (isTerminal(task.status)) {\n const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);\n this._clearTaskQueue(taskId);\n return {\n ...result,\n _meta: {\n ...result._meta,\n [RELATED_TASK_META_KEY]: {\n taskId: taskId\n }\n }\n };\n }\n return await handleTaskResult();\n };\n return await handleTaskResult();\n });\n this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {\n try {\n const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);\n // @ts-expect-error SendResultT cannot contain ListTasksResult, but we include it in our derived types everywhere else\n return {\n tasks,\n nextCursor,\n _meta: {}\n };\n }\n catch (error) {\n throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`);\n }\n });\n this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {\n try {\n // Get the current task to check if it's in a terminal state, in case the implementation is not atomic\n const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);\n }\n // Reject cancellation of terminal tasks\n if (isTerminal(task.status)) {\n throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);\n }\n await this._taskStore.updateTaskStatus(request.params.taskId, 'cancelled', 'Client cancelled task execution.', extra.sessionId);\n this._clearTaskQueue(request.params.taskId);\n const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n if (!cancelledTask) {\n // Task was deleted during cancellation (e.g., cleanup happened)\n throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);\n }\n return {\n _meta: {},\n ...cancelledTask\n };\n }\n catch (error) {\n // Re-throw McpError as-is\n if (error instanceof McpError) {\n throw error;\n }\n throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`);\n }\n });\n }\n }\n async _oncancel(notification) {\n if (!notification.params.requestId) {\n return;\n }\n // Handle request cancellation\n const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);\n controller?.abort(notification.params.reason);\n }\n _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {\n this._timeoutInfo.set(messageId, {\n timeoutId: setTimeout(onTimeout, timeout),\n startTime: Date.now(),\n timeout,\n maxTotalTimeout,\n resetTimeoutOnProgress,\n onTimeout\n });\n }\n _resetTimeout(messageId) {\n const info = this._timeoutInfo.get(messageId);\n if (!info)\n return false;\n const totalElapsed = Date.now() - info.startTime;\n if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {\n this._timeoutInfo.delete(messageId);\n throw McpError.fromError(ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', {\n maxTotalTimeout: info.maxTotalTimeout,\n totalElapsed\n });\n }\n clearTimeout(info.timeoutId);\n info.timeoutId = setTimeout(info.onTimeout, info.timeout);\n return true;\n }\n _cleanupTimeout(messageId) {\n const info = this._timeoutInfo.get(messageId);\n if (info) {\n clearTimeout(info.timeoutId);\n this._timeoutInfo.delete(messageId);\n }\n }\n /**\n * Attaches to the given transport, starts it, and starts listening for messages.\n *\n * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.\n */\n async connect(transport) {\n if (this._transport) {\n throw new Error('Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.');\n }\n this._transport = transport;\n const _onclose = this.transport?.onclose;\n this._transport.onclose = () => {\n _onclose?.();\n this._onclose();\n };\n const _onerror = this.transport?.onerror;\n this._transport.onerror = (error) => {\n _onerror?.(error);\n this._onerror(error);\n };\n const _onmessage = this._transport?.onmessage;\n this._transport.onmessage = (message, extra) => {\n _onmessage?.(message, extra);\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n this._onresponse(message);\n }\n else if (isJSONRPCRequest(message)) {\n this._onrequest(message, extra);\n }\n else if (isJSONRPCNotification(message)) {\n this._onnotification(message);\n }\n else {\n this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));\n }\n };\n await this._transport.start();\n }\n _onclose() {\n const responseHandlers = this._responseHandlers;\n this._responseHandlers = new Map();\n this._progressHandlers.clear();\n this._taskProgressTokens.clear();\n this._pendingDebouncedNotifications.clear();\n // Abort all in-flight request handlers so they stop sending messages\n for (const controller of this._requestHandlerAbortControllers.values()) {\n controller.abort();\n }\n this._requestHandlerAbortControllers.clear();\n const error = McpError.fromError(ErrorCode.ConnectionClosed, 'Connection closed');\n this._transport = undefined;\n this.onclose?.();\n for (const handler of responseHandlers.values()) {\n handler(error);\n }\n }\n _onerror(error) {\n this.onerror?.(error);\n }\n _onnotification(notification) {\n const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;\n // Ignore notifications not being subscribed to.\n if (handler === undefined) {\n return;\n }\n // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n Promise.resolve()\n .then(() => handler(notification))\n .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));\n }\n _onrequest(request, extra) {\n const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;\n // Capture the current transport at request time to ensure responses go to the correct client\n const capturedTransport = this._transport;\n // Extract taskId from request metadata if present (needed early for method not found case)\n const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;\n if (handler === undefined) {\n const errorResponse = {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: ErrorCode.MethodNotFound,\n message: 'Method not found'\n }\n };\n // Queue or send the error response based on whether this is a task-related request\n if (relatedTaskId && this._taskMessageQueue) {\n this._enqueueTaskMessage(relatedTaskId, {\n type: 'error',\n message: errorResponse,\n timestamp: Date.now()\n }, capturedTransport?.sessionId).catch(error => this._onerror(new Error(`Failed to enqueue error response: ${error}`)));\n }\n else {\n capturedTransport\n ?.send(errorResponse)\n .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`)));\n }\n return;\n }\n const abortController = new AbortController();\n this._requestHandlerAbortControllers.set(request.id, abortController);\n const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : undefined;\n const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined;\n const fullExtra = {\n signal: abortController.signal,\n sessionId: capturedTransport?.sessionId,\n _meta: request.params?._meta,\n sendNotification: async (notification) => {\n if (abortController.signal.aborted)\n return;\n // Include related-task metadata if this request is part of a task\n const notificationOptions = { relatedRequestId: request.id };\n if (relatedTaskId) {\n notificationOptions.relatedTask = { taskId: relatedTaskId };\n }\n await this.notification(notification, notificationOptions);\n },\n sendRequest: async (r, resultSchema, options) => {\n if (abortController.signal.aborted) {\n throw new McpError(ErrorCode.ConnectionClosed, 'Request was cancelled');\n }\n // Include related-task metadata if this request is part of a task\n const requestOptions = { ...options, relatedRequestId: request.id };\n if (relatedTaskId && !requestOptions.relatedTask) {\n requestOptions.relatedTask = { taskId: relatedTaskId };\n }\n // Set task status to input_required when sending a request within a task context\n // Use the taskId from options (explicit) or fall back to relatedTaskId (inherited)\n const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;\n if (effectiveTaskId && taskStore) {\n await taskStore.updateTaskStatus(effectiveTaskId, 'input_required');\n }\n return await this.request(r, resultSchema, requestOptions);\n },\n authInfo: extra?.authInfo,\n requestId: request.id,\n requestInfo: extra?.requestInfo,\n taskId: relatedTaskId,\n taskStore: taskStore,\n taskRequestedTtl: taskCreationParams?.ttl,\n closeSSEStream: extra?.closeSSEStream,\n closeStandaloneSSEStream: extra?.closeStandaloneSSEStream\n };\n // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n Promise.resolve()\n .then(() => {\n // If this request asked for task creation, check capability first\n if (taskCreationParams) {\n // Check if the request method supports task creation\n this.assertTaskHandlerCapability(request.method);\n }\n })\n .then(() => handler(request, fullExtra))\n .then(async (result) => {\n if (abortController.signal.aborted) {\n // Request was cancelled\n return;\n }\n const response = {\n result,\n jsonrpc: '2.0',\n id: request.id\n };\n // Queue or send the response based on whether this is a task-related request\n if (relatedTaskId && this._taskMessageQueue) {\n await this._enqueueTaskMessage(relatedTaskId, {\n type: 'response',\n message: response,\n timestamp: Date.now()\n }, capturedTransport?.sessionId);\n }\n else {\n await capturedTransport?.send(response);\n }\n }, async (error) => {\n if (abortController.signal.aborted) {\n // Request was cancelled\n return;\n }\n const errorResponse = {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode.InternalError,\n message: error.message ?? 'Internal error',\n ...(error['data'] !== undefined && { data: error['data'] })\n }\n };\n // Queue or send the error response based on whether this is a task-related request\n if (relatedTaskId && this._taskMessageQueue) {\n await this._enqueueTaskMessage(relatedTaskId, {\n type: 'error',\n message: errorResponse,\n timestamp: Date.now()\n }, capturedTransport?.sessionId);\n }\n else {\n await capturedTransport?.send(errorResponse);\n }\n })\n .catch(error => this._onerror(new Error(`Failed to send response: ${error}`)))\n .finally(() => {\n this._requestHandlerAbortControllers.delete(request.id);\n });\n }\n _onprogress(notification) {\n const { progressToken, ...params } = notification.params;\n const messageId = Number(progressToken);\n const handler = this._progressHandlers.get(messageId);\n if (!handler) {\n this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));\n return;\n }\n const responseHandler = this._responseHandlers.get(messageId);\n const timeoutInfo = this._timeoutInfo.get(messageId);\n if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {\n try {\n this._resetTimeout(messageId);\n }\n catch (error) {\n // Clean up if maxTotalTimeout was exceeded\n this._responseHandlers.delete(messageId);\n this._progressHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n responseHandler(error);\n return;\n }\n }\n handler(params);\n }\n _onresponse(response) {\n const messageId = Number(response.id);\n // Check if this is a response to a queued request\n const resolver = this._requestResolvers.get(messageId);\n if (resolver) {\n this._requestResolvers.delete(messageId);\n if (isJSONRPCResultResponse(response)) {\n resolver(response);\n }\n else {\n const error = new McpError(response.error.code, response.error.message, response.error.data);\n resolver(error);\n }\n return;\n }\n const handler = this._responseHandlers.get(messageId);\n if (handler === undefined) {\n this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));\n return;\n }\n this._responseHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n // Keep progress handler alive for CreateTaskResult responses\n let isTaskResponse = false;\n if (isJSONRPCResultResponse(response) && response.result && typeof response.result === 'object') {\n const result = response.result;\n if (result.task && typeof result.task === 'object') {\n const task = result.task;\n if (typeof task.taskId === 'string') {\n isTaskResponse = true;\n this._taskProgressTokens.set(task.taskId, messageId);\n }\n }\n }\n if (!isTaskResponse) {\n this._progressHandlers.delete(messageId);\n }\n if (isJSONRPCResultResponse(response)) {\n handler(response);\n }\n else {\n const error = McpError.fromError(response.error.code, response.error.message, response.error.data);\n handler(error);\n }\n }\n get transport() {\n return this._transport;\n }\n /**\n * Closes the connection.\n */\n async close() {\n await this._transport?.close();\n }\n /**\n * Sends a request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * @example\n * ```typescript\n * const stream = protocol.requestStream(request, resultSchema, options);\n * for await (const message of stream) {\n * switch (message.type) {\n * case 'taskCreated':\n * console.log('Task created:', message.task.taskId);\n * break;\n * case 'taskStatus':\n * console.log('Task status:', message.task.status);\n * break;\n * case 'result':\n * console.log('Final result:', message.result);\n * break;\n * case 'error':\n * console.error('Error:', message.error);\n * break;\n * }\n * }\n * ```\n *\n * @experimental Use `client.experimental.tasks.requestStream()` to access this method.\n */\n async *requestStream(request, resultSchema, options) {\n const { task } = options ?? {};\n // For non-task requests, just yield the result\n if (!task) {\n try {\n const result = await this.request(request, resultSchema, options);\n yield { type: 'result', result };\n }\n catch (error) {\n yield {\n type: 'error',\n error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))\n };\n }\n return;\n }\n // For task-augmented requests, we need to poll for status\n // First, make the request to create the task\n let taskId;\n try {\n // Send the request and get the CreateTaskResult\n const createResult = await this.request(request, CreateTaskResultSchema, options);\n // Extract taskId from the result\n if (createResult.task) {\n taskId = createResult.task.taskId;\n yield { type: 'taskCreated', task: createResult.task };\n }\n else {\n throw new McpError(ErrorCode.InternalError, 'Task creation did not return a task');\n }\n // Poll for task completion\n while (true) {\n // Get current task status\n const task = await this.getTask({ taskId }, options);\n yield { type: 'taskStatus', task };\n // Check if task is terminal\n if (isTerminal(task.status)) {\n if (task.status === 'completed') {\n // Get the final result\n const result = await this.getTaskResult({ taskId }, resultSchema, options);\n yield { type: 'result', result };\n }\n else if (task.status === 'failed') {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)\n };\n }\n else if (task.status === 'cancelled') {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)\n };\n }\n return;\n }\n // When input_required, call tasks/result to deliver queued messages\n // (elicitation, sampling) via SSE and block until terminal\n if (task.status === 'input_required') {\n const result = await this.getTaskResult({ taskId }, resultSchema, options);\n yield { type: 'result', result };\n return;\n }\n // Wait before polling again\n const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1000;\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n // Check if cancelled\n options?.signal?.throwIfAborted();\n }\n }\n catch (error) {\n yield {\n type: 'error',\n error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))\n };\n }\n }\n /**\n * Sends a request and waits for a response.\n *\n * Do not use this method to emit notifications! Use notification() instead.\n */\n request(request, resultSchema, options) {\n const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};\n // Send the request\n return new Promise((resolve, reject) => {\n const earlyReject = (error) => {\n reject(error);\n };\n if (!this._transport) {\n earlyReject(new Error('Not connected'));\n return;\n }\n if (this._options?.enforceStrictCapabilities === true) {\n try {\n this.assertCapabilityForMethod(request.method);\n // If task creation is requested, also check task capabilities\n if (task) {\n this.assertTaskCapability(request.method);\n }\n }\n catch (e) {\n earlyReject(e);\n return;\n }\n }\n options?.signal?.throwIfAborted();\n const messageId = this._requestMessageId++;\n const jsonrpcRequest = {\n ...request,\n jsonrpc: '2.0',\n id: messageId\n };\n if (options?.onprogress) {\n this._progressHandlers.set(messageId, options.onprogress);\n jsonrpcRequest.params = {\n ...request.params,\n _meta: {\n ...(request.params?._meta || {}),\n progressToken: messageId\n }\n };\n }\n // Augment with task creation parameters if provided\n if (task) {\n jsonrpcRequest.params = {\n ...jsonrpcRequest.params,\n task: task\n };\n }\n // Augment with related task metadata if relatedTask is provided\n if (relatedTask) {\n jsonrpcRequest.params = {\n ...jsonrpcRequest.params,\n _meta: {\n ...(jsonrpcRequest.params?._meta || {}),\n [RELATED_TASK_META_KEY]: relatedTask\n }\n };\n }\n const cancel = (reason) => {\n this._responseHandlers.delete(messageId);\n this._progressHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n this._transport\n ?.send({\n jsonrpc: '2.0',\n method: 'notifications/cancelled',\n params: {\n requestId: messageId,\n reason: String(reason)\n }\n }, { relatedRequestId, resumptionToken, onresumptiontoken })\n .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`)));\n // Wrap the reason in an McpError if it isn't already\n const error = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));\n reject(error);\n };\n this._responseHandlers.set(messageId, response => {\n if (options?.signal?.aborted) {\n return;\n }\n if (response instanceof Error) {\n return reject(response);\n }\n try {\n const parseResult = safeParse(resultSchema, response.result);\n if (!parseResult.success) {\n // Type guard: if success is false, error is guaranteed to exist\n reject(parseResult.error);\n }\n else {\n resolve(parseResult.data);\n }\n }\n catch (error) {\n reject(error);\n }\n });\n options?.signal?.addEventListener('abort', () => {\n cancel(options?.signal?.reason);\n });\n const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;\n const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, 'Request timed out', { timeout }));\n this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);\n // Queue request if related to a task\n const relatedTaskId = relatedTask?.taskId;\n if (relatedTaskId) {\n // Store the response resolver for this request so responses can be routed back\n const responseResolver = (response) => {\n const handler = this._responseHandlers.get(messageId);\n if (handler) {\n handler(response);\n }\n else {\n // Log error when resolver is missing, but don't fail\n this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));\n }\n };\n this._requestResolvers.set(messageId, responseResolver);\n this._enqueueTaskMessage(relatedTaskId, {\n type: 'request',\n message: jsonrpcRequest,\n timestamp: Date.now()\n }).catch(error => {\n this._cleanupTimeout(messageId);\n reject(error);\n });\n // Don't send through transport - queued messages are delivered via tasks/result only\n // This prevents duplicate delivery for bidirectional transports\n }\n else {\n // No related task - send through transport normally\n this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => {\n this._cleanupTimeout(messageId);\n reject(error);\n });\n }\n });\n }\n /**\n * Gets the current status of a task.\n *\n * @experimental Use `client.experimental.tasks.getTask()` to access this method.\n */\n async getTask(params, options) {\n // @ts-expect-error SendRequestT cannot directly contain GetTaskRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/get', params }, GetTaskResultSchema, options);\n }\n /**\n * Retrieves the result of a completed task.\n *\n * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.\n */\n async getTaskResult(params, resultSchema, options) {\n // @ts-expect-error SendRequestT cannot directly contain GetTaskPayloadRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/result', params }, resultSchema, options);\n }\n /**\n * Lists tasks, optionally starting from a pagination cursor.\n *\n * @experimental Use `client.experimental.tasks.listTasks()` to access this method.\n */\n async listTasks(params, options) {\n // @ts-expect-error SendRequestT cannot directly contain ListTasksRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/list', params }, ListTasksResultSchema, options);\n }\n /**\n * Cancels a specific task.\n *\n * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.\n */\n async cancelTask(params, options) {\n // @ts-expect-error SendRequestT cannot directly contain CancelTaskRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/cancel', params }, CancelTaskResultSchema, options);\n }\n /**\n * Emits a notification, which is a one-way message that does not expect a response.\n */\n async notification(notification, options) {\n if (!this._transport) {\n throw new Error('Not connected');\n }\n this.assertNotificationCapability(notification.method);\n // Queue notification if related to a task\n const relatedTaskId = options?.relatedTask?.taskId;\n if (relatedTaskId) {\n // Build the JSONRPC notification with metadata\n const jsonrpcNotification = {\n ...notification,\n jsonrpc: '2.0',\n params: {\n ...notification.params,\n _meta: {\n ...(notification.params?._meta || {}),\n [RELATED_TASK_META_KEY]: options.relatedTask\n }\n }\n };\n await this._enqueueTaskMessage(relatedTaskId, {\n type: 'notification',\n message: jsonrpcNotification,\n timestamp: Date.now()\n });\n // Don't send through transport - queued messages are delivered via tasks/result only\n // This prevents duplicate delivery for bidirectional transports\n return;\n }\n const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];\n // A notification can only be debounced if it's in the list AND it's \"simple\"\n // (i.e., has no parameters and no related request ID or related task that could be lost).\n const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;\n if (canDebounce) {\n // If a notification of this type is already scheduled, do nothing.\n if (this._pendingDebouncedNotifications.has(notification.method)) {\n return;\n }\n // Mark this notification type as pending.\n this._pendingDebouncedNotifications.add(notification.method);\n // Schedule the actual send to happen in the next microtask.\n // This allows all synchronous calls in the current event loop tick to be coalesced.\n Promise.resolve().then(() => {\n // Un-mark the notification so the next one can be scheduled.\n this._pendingDebouncedNotifications.delete(notification.method);\n // SAFETY CHECK: If the connection was closed while this was pending, abort.\n if (!this._transport) {\n return;\n }\n let jsonrpcNotification = {\n ...notification,\n jsonrpc: '2.0'\n };\n // Augment with related task metadata if relatedTask is provided\n if (options?.relatedTask) {\n jsonrpcNotification = {\n ...jsonrpcNotification,\n params: {\n ...jsonrpcNotification.params,\n _meta: {\n ...(jsonrpcNotification.params?._meta || {}),\n [RELATED_TASK_META_KEY]: options.relatedTask\n }\n }\n };\n }\n // Send the notification, but don't await it here to avoid blocking.\n // Handle potential errors with a .catch().\n this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error));\n });\n // Return immediately.\n return;\n }\n let jsonrpcNotification = {\n ...notification,\n jsonrpc: '2.0'\n };\n // Augment with related task metadata if relatedTask is provided\n if (options?.relatedTask) {\n jsonrpcNotification = {\n ...jsonrpcNotification,\n params: {\n ...jsonrpcNotification.params,\n _meta: {\n ...(jsonrpcNotification.params?._meta || {}),\n [RELATED_TASK_META_KEY]: options.relatedTask\n }\n }\n };\n }\n await this._transport.send(jsonrpcNotification, options);\n }\n /**\n * Registers a handler to invoke when this protocol object receives a request with the given method.\n *\n * Note that this will replace any previous request handler for the same method.\n */\n setRequestHandler(requestSchema, handler) {\n const method = getMethodLiteral(requestSchema);\n this.assertRequestHandlerCapability(method);\n this._requestHandlers.set(method, (request, extra) => {\n const parsed = parseWithCompat(requestSchema, request);\n return Promise.resolve(handler(parsed, extra));\n });\n }\n /**\n * Removes the request handler for the given method.\n */\n removeRequestHandler(method) {\n this._requestHandlers.delete(method);\n }\n /**\n * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.\n */\n assertCanSetRequestHandler(method) {\n if (this._requestHandlers.has(method)) {\n throw new Error(`A request handler for ${method} already exists, which would be overridden`);\n }\n }\n /**\n * Registers a handler to invoke when this protocol object receives a notification with the given method.\n *\n * Note that this will replace any previous notification handler for the same method.\n */\n setNotificationHandler(notificationSchema, handler) {\n const method = getMethodLiteral(notificationSchema);\n this._notificationHandlers.set(method, notification => {\n const parsed = parseWithCompat(notificationSchema, notification);\n return Promise.resolve(handler(parsed));\n });\n }\n /**\n * Removes the notification handler for the given method.\n */\n removeNotificationHandler(method) {\n this._notificationHandlers.delete(method);\n }\n /**\n * Cleans up the progress handler associated with a task.\n * This should be called when a task reaches a terminal status.\n */\n _cleanupTaskProgressHandler(taskId) {\n const progressToken = this._taskProgressTokens.get(taskId);\n if (progressToken !== undefined) {\n this._progressHandlers.delete(progressToken);\n this._taskProgressTokens.delete(taskId);\n }\n }\n /**\n * Enqueues a task-related message for side-channel delivery via tasks/result.\n * @param taskId The task ID to associate the message with\n * @param message The message to enqueue\n * @param sessionId Optional session ID for binding the operation to a specific session\n * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)\n *\n * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle\n * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer\n * simply propagates the error.\n */\n async _enqueueTaskMessage(taskId, message, sessionId) {\n // Task message queues are only used when taskStore is configured\n if (!this._taskStore || !this._taskMessageQueue) {\n throw new Error('Cannot enqueue task message: taskStore and taskMessageQueue are not configured');\n }\n const maxQueueSize = this._options?.maxTaskQueueSize;\n await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);\n }\n /**\n * Clears the message queue for a task and rejects any pending request resolvers.\n * @param taskId The task ID whose queue should be cleared\n * @param sessionId Optional session ID for binding the operation to a specific session\n */\n async _clearTaskQueue(taskId, sessionId) {\n if (this._taskMessageQueue) {\n // Reject any pending request resolvers\n const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);\n for (const message of messages) {\n if (message.type === 'request' && isJSONRPCRequest(message.message)) {\n // Extract request ID from the message\n const requestId = message.message.id;\n const resolver = this._requestResolvers.get(requestId);\n if (resolver) {\n resolver(new McpError(ErrorCode.InternalError, 'Task cancelled or completed'));\n this._requestResolvers.delete(requestId);\n }\n else {\n // Log error when resolver is missing during cleanup for better observability\n this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));\n }\n }\n }\n }\n }\n /**\n * Waits for a task update (new messages or status change) with abort signal support.\n * Uses polling to check for updates at the task's configured poll interval.\n * @param taskId The task ID to wait for\n * @param signal Abort signal to cancel the wait\n * @returns Promise that resolves when an update occurs or rejects if aborted\n */\n async _waitForTaskUpdate(taskId, signal) {\n // Get the task's poll interval, falling back to default\n let interval = this._options?.defaultTaskPollInterval ?? 1000;\n try {\n const task = await this._taskStore?.getTask(taskId);\n if (task?.pollInterval) {\n interval = task.pollInterval;\n }\n }\n catch {\n // Use default interval if task lookup fails\n }\n return new Promise((resolve, reject) => {\n if (signal.aborted) {\n reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled'));\n return;\n }\n // Wait for the poll interval, then resolve so caller can check for updates\n const timeoutId = setTimeout(resolve, interval);\n // Clean up timeout and reject if aborted\n signal.addEventListener('abort', () => {\n clearTimeout(timeoutId);\n reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled'));\n }, { once: true });\n });\n }\n requestTaskStore(request, sessionId) {\n const taskStore = this._taskStore;\n if (!taskStore) {\n throw new Error('No task store configured');\n }\n return {\n createTask: async (taskParams) => {\n if (!request) {\n throw new Error('No request provided');\n }\n return await taskStore.createTask(taskParams, request.id, {\n method: request.method,\n params: request.params\n }, sessionId);\n },\n getTask: async (taskId) => {\n const task = await taskStore.getTask(taskId, sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found');\n }\n return task;\n },\n storeTaskResult: async (taskId, status, result) => {\n await taskStore.storeTaskResult(taskId, status, result, sessionId);\n // Get updated task state and send notification\n const task = await taskStore.getTask(taskId, sessionId);\n if (task) {\n const notification = TaskStatusNotificationSchema.parse({\n method: 'notifications/tasks/status',\n params: task\n });\n await this.notification(notification);\n if (isTerminal(task.status)) {\n this._cleanupTaskProgressHandler(taskId);\n // Don't clear queue here - it will be cleared after delivery via tasks/result\n }\n }\n },\n getTaskResult: taskId => {\n return taskStore.getTaskResult(taskId, sessionId);\n },\n updateTaskStatus: async (taskId, status, statusMessage) => {\n // Check if task exists\n const task = await taskStore.getTask(taskId, sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, `Task \"${taskId}\" not found - it may have been cleaned up`);\n }\n // Don't allow transitions from terminal states\n if (isTerminal(task.status)) {\n throw new McpError(ErrorCode.InvalidParams, `Cannot update task \"${taskId}\" from terminal status \"${task.status}\" to \"${status}\". Terminal states (completed, failed, cancelled) cannot transition to other states.`);\n }\n await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);\n // Get updated task state and send notification\n const updatedTask = await taskStore.getTask(taskId, sessionId);\n if (updatedTask) {\n const notification = TaskStatusNotificationSchema.parse({\n method: 'notifications/tasks/status',\n params: updatedTask\n });\n await this.notification(notification);\n if (isTerminal(updatedTask.status)) {\n this._cleanupTaskProgressHandler(taskId);\n // Don't clear queue here - it will be cleared after delivery via tasks/result\n }\n }\n },\n listTasks: cursor => {\n return taskStore.listTasks(cursor, sessionId);\n }\n };\n }\n}\nfunction isPlainObject(value) {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\nexport function mergeCapabilities(base, additional) {\n const result = { ...base };\n for (const key in additional) {\n const k = key;\n const addValue = additional[k];\n if (addValue === undefined)\n continue;\n const baseValue = result[k];\n if (isPlainObject(baseValue) && isPlainObject(addValue)) {\n result[k] = { ...baseValue, ...addValue };\n }\n else {\n result[k] = addValue;\n }\n }\n return result;\n}\n//# sourceMappingURL=protocol.js.map","/**\n * Throwing ajv stub for browser environments.\n *\n * The MCP SDK's Server class statically imports AjvJsonSchemaValidator as a\n * default fallback. BrowserMcpServer always passes PolyfillJsonSchemaValidator,\n * so ajv is never actually used — but the static import still resolves. This\n * stub satisfies that import without pulling in the real ajv (CJS-only, breaks\n * in browsers).\n *\n * If any code path unexpectedly reaches this stub, it throws immediately so the\n * issue is surfaced rather than silently passing all validation.\n */\n\nexport class Ajv {\n compile(_schema: unknown): never {\n throw new Error(\n '[WebMCP] Ajv stub was invoked. This indicates the MCP SDK is bypassing ' +\n 'PolyfillJsonSchemaValidator. Please report this as a bug.'\n );\n }\n\n getSchema(_id: string): undefined {\n return undefined;\n }\n\n errorsText(_errors?: unknown): string {\n return '';\n }\n}\n\nexport default Ajv;\n","/**\n * No-op ajv-formats stub for browser environments.\n * See ./ajv.ts for rationale.\n */\nexport default function addFormats(_ajv: unknown): void {}\n","/**\n * AJV-based JSON Schema validator provider\n */\nimport Ajv from 'ajv';\nimport _addFormats from 'ajv-formats';\nfunction createDefaultAjvInstance() {\n const ajv = new Ajv({\n strict: false,\n validateFormats: true,\n validateSchema: false,\n allErrors: true\n });\n const addFormats = _addFormats;\n addFormats(ajv);\n return ajv;\n}\n/**\n * @example\n * ```typescript\n * // Use with default AJV instance (recommended)\n * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';\n * const validator = new AjvJsonSchemaValidator();\n *\n * // Use with custom AJV instance\n * import { Ajv } from 'ajv';\n * const ajv = new Ajv({ strict: true, allErrors: true });\n * const validator = new AjvJsonSchemaValidator(ajv);\n * ```\n */\nexport class AjvJsonSchemaValidator {\n /**\n * Create an AJV validator\n *\n * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created.\n *\n * @example\n * ```typescript\n * // Use default configuration (recommended for most cases)\n * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';\n * const validator = new AjvJsonSchemaValidator();\n *\n * // Or provide custom AJV instance for advanced configuration\n * import { Ajv } from 'ajv';\n * import addFormats from 'ajv-formats';\n *\n * const ajv = new Ajv({ validateFormats: true });\n * addFormats(ajv);\n * const validator = new AjvJsonSchemaValidator(ajv);\n * ```\n */\n constructor(ajv) {\n this._ajv = ajv ?? createDefaultAjvInstance();\n }\n /**\n * Create a validator for the given JSON Schema\n *\n * The validator is compiled once and can be reused multiple times.\n * If the schema has an $id, it will be cached by AJV automatically.\n *\n * @param schema - Standard JSON Schema object\n * @returns A validator function that validates input data\n */\n getValidator(schema) {\n // Check if schema has $id and is already compiled/cached\n const ajvValidator = '$id' in schema && typeof schema.$id === 'string'\n ? (this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema))\n : this._ajv.compile(schema);\n return (input) => {\n const valid = ajvValidator(input);\n if (valid) {\n return {\n valid: true,\n data: input,\n errorMessage: undefined\n };\n }\n else {\n return {\n valid: false,\n data: undefined,\n errorMessage: this._ajv.errorsText(ajvValidator.errors)\n };\n }\n };\n }\n}\n//# sourceMappingURL=ajv-provider.js.map","/**\n * Experimental client task features for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\nimport { CallToolResultSchema, McpError, ErrorCode } from '../../types.js';\n/**\n * Experimental task features for MCP clients.\n *\n * Access via `client.experimental.tasks`:\n * ```typescript\n * const stream = client.experimental.tasks.callToolStream({ name: 'tool', arguments: {} });\n * const task = await client.experimental.tasks.getTask(taskId);\n * ```\n *\n * @experimental\n */\nexport class ExperimentalClientTasks {\n constructor(_client) {\n this._client = _client;\n }\n /**\n * Calls a tool and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * This method provides streaming access to tool execution, allowing you to\n * observe intermediate task status updates for long-running tool calls.\n * Automatically validates structured output if the tool has an outputSchema.\n *\n * @example\n * ```typescript\n * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });\n * for await (const message of stream) {\n * switch (message.type) {\n * case 'taskCreated':\n * console.log('Tool execution started:', message.task.taskId);\n * break;\n * case 'taskStatus':\n * console.log('Tool status:', message.task.status);\n * break;\n * case 'result':\n * console.log('Tool result:', message.result);\n * break;\n * case 'error':\n * console.error('Tool error:', message.error);\n * break;\n * }\n * }\n * ```\n *\n * @param params - Tool call parameters (name and arguments)\n * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)\n * @param options - Optional request options (timeout, signal, task creation params, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n async *callToolStream(params, resultSchema = CallToolResultSchema, options) {\n // Access Client's internal methods\n const clientInternal = this._client;\n // Add task creation parameters if server supports it and not explicitly provided\n const optionsWithTask = {\n ...options,\n // We check if the tool is known to be a task during auto-configuration, but assume\n // the caller knows what they're doing if they pass this explicitly\n task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : undefined)\n };\n const stream = clientInternal.requestStream({ method: 'tools/call', params }, resultSchema, optionsWithTask);\n // Get the validator for this tool (if it has an output schema)\n const validator = clientInternal.getToolOutputValidator(params.name);\n // Iterate through the stream and validate the final result if needed\n for await (const message of stream) {\n // If this is a result message and the tool has an output schema, validate it\n if (message.type === 'result' && validator) {\n const result = message.result;\n // If tool has outputSchema, it MUST return structuredContent (unless it's an error)\n if (!result.structuredContent && !result.isError) {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)\n };\n return;\n }\n // Only validate structured content if present (not when there's an error)\n if (result.structuredContent) {\n try {\n // Validate the structured content against the schema\n const validationResult = validator(result.structuredContent);\n if (!validationResult.valid) {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)\n };\n return;\n }\n }\n catch (error) {\n if (error instanceof McpError) {\n yield { type: 'error', error };\n return;\n }\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)\n };\n return;\n }\n }\n }\n // Yield the message (either validated result or any other message type)\n yield message;\n }\n }\n /**\n * Gets the current status of a task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n * @returns The task status\n *\n * @experimental\n */\n async getTask(taskId, options) {\n return this._client.getTask({ taskId }, options);\n }\n /**\n * Retrieves the result of a completed task.\n *\n * @param taskId - The task identifier\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options\n * @returns The task result\n *\n * @experimental\n */\n async getTaskResult(taskId, resultSchema, options) {\n // Delegate to the client's underlying Protocol method\n return this._client.getTaskResult({ taskId }, resultSchema, options);\n }\n /**\n * Lists tasks with optional pagination.\n *\n * @param cursor - Optional pagination cursor\n * @param options - Optional request options\n * @returns List of tasks with optional next cursor\n *\n * @experimental\n */\n async listTasks(cursor, options) {\n // Delegate to the client's underlying Protocol method\n return this._client.listTasks(cursor ? { cursor } : undefined, options);\n }\n /**\n * Cancels a running task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n *\n * @experimental\n */\n async cancelTask(taskId, options) {\n // Delegate to the client's underlying Protocol method\n return this._client.cancelTask({ taskId }, options);\n }\n /**\n * Sends a request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * This method provides streaming access to request processing, allowing you to\n * observe intermediate task status updates for task-augmented requests.\n *\n * @param request - The request to send\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options (timeout, signal, task creation params, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n requestStream(request, resultSchema, options) {\n return this._client.requestStream(request, resultSchema, options);\n }\n}\n//# sourceMappingURL=client.js.map","/**\n * Experimental task capability assertion helpers.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n/**\n * Asserts that task creation is supported for tools/call.\n * Used by Client.assertTaskCapability and Server.assertTaskHandlerCapability.\n *\n * @param requests - The task requests capability object\n * @param method - The method being checked\n * @param entityName - 'Server' or 'Client' for error messages\n * @throws Error if the capability is not supported\n *\n * @experimental\n */\nexport function assertToolsCallTaskCapability(requests, method, entityName) {\n if (!requests) {\n throw new Error(`${entityName} does not support task creation (required for ${method})`);\n }\n switch (method) {\n case 'tools/call':\n if (!requests.tools?.call) {\n throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);\n }\n break;\n default:\n // Method doesn't support tasks, which is fine - no error\n break;\n }\n}\n/**\n * Asserts that task creation is supported for sampling/createMessage or elicitation/create.\n * Used by Server.assertTaskCapability and Client.assertTaskHandlerCapability.\n *\n * @param requests - The task requests capability object\n * @param method - The method being checked\n * @param entityName - 'Server' or 'Client' for error messages\n * @throws Error if the capability is not supported\n *\n * @experimental\n */\nexport function assertClientRequestTaskCapability(requests, method, entityName) {\n if (!requests) {\n throw new Error(`${entityName} does not support task creation (required for ${method})`);\n }\n switch (method) {\n case 'sampling/createMessage':\n if (!requests.sampling?.createMessage) {\n throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);\n }\n break;\n case 'elicitation/create':\n if (!requests.elicitation?.create) {\n throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);\n }\n break;\n default:\n // Method doesn't support tasks, which is fine - no error\n break;\n }\n}\n//# sourceMappingURL=helpers.js.map","import { mergeCapabilities, Protocol } from '../shared/protocol.js';\nimport { CallToolResultSchema, CompleteResultSchema, EmptyResultSchema, ErrorCode, GetPromptResultSchema, InitializeResultSchema, LATEST_PROTOCOL_VERSION, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ListToolsResultSchema, McpError, ReadResourceResultSchema, SUPPORTED_PROTOCOL_VERSIONS, ElicitResultSchema, ElicitRequestSchema, CreateTaskResultSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ToolListChangedNotificationSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ListChangedOptionsBaseSchema } from '../types.js';\nimport { AjvJsonSchemaValidator } from '../validation/ajv-provider.js';\nimport { getObjectShape, isZ4Schema, safeParse } from '../server/zod-compat.js';\nimport { ExperimentalClientTasks } from '../experimental/tasks/client.js';\nimport { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js';\n/**\n * Elicitation default application helper. Applies defaults to the data based on the schema.\n *\n * @param schema - The schema to apply defaults to.\n * @param data - The data to apply defaults to.\n */\nfunction applyElicitationDefaults(schema, data) {\n if (!schema || data === null || typeof data !== 'object')\n return;\n // Handle object properties\n if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') {\n const obj = data;\n const props = schema.properties;\n for (const key of Object.keys(props)) {\n const propSchema = props[key];\n // If missing or explicitly undefined, apply default if present\n if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) {\n obj[key] = propSchema.default;\n }\n // Recurse into existing nested objects/arrays\n if (obj[key] !== undefined) {\n applyElicitationDefaults(propSchema, obj[key]);\n }\n }\n }\n if (Array.isArray(schema.anyOf)) {\n for (const sub of schema.anyOf) {\n // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)\n if (typeof sub !== 'boolean') {\n applyElicitationDefaults(sub, data);\n }\n }\n }\n // Combine schemas\n if (Array.isArray(schema.oneOf)) {\n for (const sub of schema.oneOf) {\n // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)\n if (typeof sub !== 'boolean') {\n applyElicitationDefaults(sub, data);\n }\n }\n }\n}\n/**\n * Determines which elicitation modes are supported based on declared client capabilities.\n *\n * According to the spec:\n * - An empty elicitation capability object defaults to form mode support (backwards compatibility)\n * - URL mode is only supported if explicitly declared\n *\n * @param capabilities - The client's elicitation capabilities\n * @returns An object indicating which modes are supported\n */\nexport function getSupportedElicitationModes(capabilities) {\n if (!capabilities) {\n return { supportsFormMode: false, supportsUrlMode: false };\n }\n const hasFormCapability = capabilities.form !== undefined;\n const hasUrlCapability = capabilities.url !== undefined;\n // If neither form nor url are explicitly declared, form mode is supported (backwards compatibility)\n const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability);\n const supportsUrlMode = hasUrlCapability;\n return { supportsFormMode, supportsUrlMode };\n}\n/**\n * An MCP client on top of a pluggable transport.\n *\n * The client will automatically begin the initialization flow with the server when connect() is called.\n *\n * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:\n *\n * ```typescript\n * // Custom schemas\n * const CustomRequestSchema = RequestSchema.extend({...})\n * const CustomNotificationSchema = NotificationSchema.extend({...})\n * const CustomResultSchema = ResultSchema.extend({...})\n *\n * // Type aliases\n * type CustomRequest = z.infer<typeof CustomRequestSchema>\n * type CustomNotification = z.infer<typeof CustomNotificationSchema>\n * type CustomResult = z.infer<typeof CustomResultSchema>\n *\n * // Create typed client\n * const client = new Client<CustomRequest, CustomNotification, CustomResult>({\n * name: \"CustomClient\",\n * version: \"1.0.0\"\n * })\n * ```\n */\nexport class Client extends Protocol {\n /**\n * Initializes this client with the given name and version information.\n */\n constructor(_clientInfo, options) {\n super(options);\n this._clientInfo = _clientInfo;\n this._cachedToolOutputValidators = new Map();\n this._cachedKnownTaskTools = new Set();\n this._cachedRequiredTaskTools = new Set();\n this._listChangedDebounceTimers = new Map();\n this._capabilities = options?.capabilities ?? {};\n this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();\n // Store list changed config for setup after connection (when we know server capabilities)\n if (options?.listChanged) {\n this._pendingListChangedConfig = options.listChanged;\n }\n }\n /**\n * Set up handlers for list changed notifications based on config and server capabilities.\n * This should only be called after initialization when server capabilities are known.\n * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.\n * @internal\n */\n _setupListChangedHandlers(config) {\n if (config.tools && this._serverCapabilities?.tools?.listChanged) {\n this._setupListChangedHandler('tools', ToolListChangedNotificationSchema, config.tools, async () => {\n const result = await this.listTools();\n return result.tools;\n });\n }\n if (config.prompts && this._serverCapabilities?.prompts?.listChanged) {\n this._setupListChangedHandler('prompts', PromptListChangedNotificationSchema, config.prompts, async () => {\n const result = await this.listPrompts();\n return result.prompts;\n });\n }\n if (config.resources && this._serverCapabilities?.resources?.listChanged) {\n this._setupListChangedHandler('resources', ResourceListChangedNotificationSchema, config.resources, async () => {\n const result = await this.listResources();\n return result.resources;\n });\n }\n }\n /**\n * Access experimental features.\n *\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n get experimental() {\n if (!this._experimental) {\n this._experimental = {\n tasks: new ExperimentalClientTasks(this)\n };\n }\n return this._experimental;\n }\n /**\n * Registers new capabilities. This can only be called before connecting to a transport.\n *\n * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).\n */\n registerCapabilities(capabilities) {\n if (this.transport) {\n throw new Error('Cannot register capabilities after connecting to transport');\n }\n this._capabilities = mergeCapabilities(this._capabilities, capabilities);\n }\n /**\n * Override request handler registration to enforce client-side validation for elicitation.\n */\n setRequestHandler(requestSchema, handler) {\n const shape = getObjectShape(requestSchema);\n const methodSchema = shape?.method;\n if (!methodSchema) {\n throw new Error('Schema is missing a method literal');\n }\n // Extract literal value using type-safe property access\n let methodValue;\n if (isZ4Schema(methodSchema)) {\n const v4Schema = methodSchema;\n const v4Def = v4Schema._zod?.def;\n methodValue = v4Def?.value ?? v4Schema.value;\n }\n else {\n const v3Schema = methodSchema;\n const legacyDef = v3Schema._def;\n methodValue = legacyDef?.value ?? v3Schema.value;\n }\n if (typeof methodValue !== 'string') {\n throw new Error('Schema method literal must be a string');\n }\n const method = methodValue;\n if (method === 'elicitation/create') {\n const wrappedHandler = async (request, extra) => {\n const validatedRequest = safeParse(ElicitRequestSchema, request);\n if (!validatedRequest.success) {\n // Type guard: if success is false, error is guaranteed to exist\n const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);\n }\n const { params } = validatedRequest.data;\n params.mode = params.mode ?? 'form';\n const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);\n if (params.mode === 'form' && !supportsFormMode) {\n throw new McpError(ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests');\n }\n if (params.mode === 'url' && !supportsUrlMode) {\n throw new McpError(ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests');\n }\n const result = await Promise.resolve(handler(request, extra));\n // When task creation is requested, validate and return CreateTaskResult\n if (params.task) {\n const taskValidationResult = safeParse(CreateTaskResultSchema, result);\n if (!taskValidationResult.success) {\n const errorMessage = taskValidationResult.error instanceof Error\n ? taskValidationResult.error.message\n : String(taskValidationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);\n }\n return taskValidationResult.data;\n }\n // For non-task requests, validate against ElicitResultSchema\n const validationResult = safeParse(ElicitResultSchema, result);\n if (!validationResult.success) {\n // Type guard: if success is false, error is guaranteed to exist\n const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);\n }\n const validatedResult = validationResult.data;\n const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined;\n if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) {\n if (this._capabilities.elicitation?.form?.applyDefaults) {\n try {\n applyElicitationDefaults(requestedSchema, validatedResult.content);\n }\n catch {\n // gracefully ignore errors in default application\n }\n }\n }\n return validatedResult;\n };\n // Install the wrapped handler\n return super.setRequestHandler(requestSchema, wrappedHandler);\n }\n if (method === 'sampling/createMessage') {\n const wrappedHandler = async (request, extra) => {\n const validatedRequest = safeParse(CreateMessageRequestSchema, request);\n if (!validatedRequest.success) {\n const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);\n }\n const { params } = validatedRequest.data;\n const result = await Promise.resolve(handler(request, extra));\n // When task creation is requested, validate and return CreateTaskResult\n if (params.task) {\n const taskValidationResult = safeParse(CreateTaskResultSchema, result);\n if (!taskValidationResult.success) {\n const errorMessage = taskValidationResult.error instanceof Error\n ? taskValidationResult.error.message\n : String(taskValidationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);\n }\n return taskValidationResult.data;\n }\n // For non-task requests, validate against appropriate schema based on tools presence\n const hasTools = params.tools || params.toolChoice;\n const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;\n const validationResult = safeParse(resultSchema, result);\n if (!validationResult.success) {\n const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);\n }\n return validationResult.data;\n };\n // Install the wrapped handler\n return super.setRequestHandler(requestSchema, wrappedHandler);\n }\n // Other handlers use default behavior\n return super.setRequestHandler(requestSchema, handler);\n }\n assertCapability(capability, method) {\n if (!this._serverCapabilities?.[capability]) {\n throw new Error(`Server does not support ${capability} (required for ${method})`);\n }\n }\n async connect(transport, options) {\n await super.connect(transport);\n // When transport sessionId is already set this means we are trying to reconnect.\n // In this case we don't need to initialize again.\n if (transport.sessionId !== undefined) {\n return;\n }\n try {\n const result = await this.request({\n method: 'initialize',\n params: {\n protocolVersion: LATEST_PROTOCOL_VERSION,\n capabilities: this._capabilities,\n clientInfo: this._clientInfo\n }\n }, InitializeResultSchema, options);\n if (result === undefined) {\n throw new Error(`Server sent invalid initialize result: ${result}`);\n }\n if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {\n throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);\n }\n this._serverCapabilities = result.capabilities;\n this._serverVersion = result.serverInfo;\n // HTTP transports must set the protocol version in each header after initialization.\n if (transport.setProtocolVersion) {\n transport.setProtocolVersion(result.protocolVersion);\n }\n this._instructions = result.instructions;\n await this.notification({\n method: 'notifications/initialized'\n });\n // Set up list changed handlers now that we know server capabilities\n if (this._pendingListChangedConfig) {\n this._setupListChangedHandlers(this._pendingListChangedConfig);\n this._pendingListChangedConfig = undefined;\n }\n }\n catch (error) {\n // Disconnect if initialization fails.\n void this.close();\n throw error;\n }\n }\n /**\n * After initialization has completed, this will be populated with the server's reported capabilities.\n */\n getServerCapabilities() {\n return this._serverCapabilities;\n }\n /**\n * After initialization has completed, this will be populated with information about the server's name and version.\n */\n getServerVersion() {\n return this._serverVersion;\n }\n /**\n * After initialization has completed, this may be populated with information about the server's instructions.\n */\n getInstructions() {\n return this._instructions;\n }\n assertCapabilityForMethod(method) {\n switch (method) {\n case 'logging/setLevel':\n if (!this._serverCapabilities?.logging) {\n throw new Error(`Server does not support logging (required for ${method})`);\n }\n break;\n case 'prompts/get':\n case 'prompts/list':\n if (!this._serverCapabilities?.prompts) {\n throw new Error(`Server does not support prompts (required for ${method})`);\n }\n break;\n case 'resources/list':\n case 'resources/templates/list':\n case 'resources/read':\n case 'resources/subscribe':\n case 'resources/unsubscribe':\n if (!this._serverCapabilities?.resources) {\n throw new Error(`Server does not support resources (required for ${method})`);\n }\n if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) {\n throw new Error(`Server does not support resource subscriptions (required for ${method})`);\n }\n break;\n case 'tools/call':\n case 'tools/list':\n if (!this._serverCapabilities?.tools) {\n throw new Error(`Server does not support tools (required for ${method})`);\n }\n break;\n case 'completion/complete':\n if (!this._serverCapabilities?.completions) {\n throw new Error(`Server does not support completions (required for ${method})`);\n }\n break;\n case 'initialize':\n // No specific capability required for initialize\n break;\n case 'ping':\n // No specific capability required for ping\n break;\n }\n }\n assertNotificationCapability(method) {\n switch (method) {\n case 'notifications/roots/list_changed':\n if (!this._capabilities.roots?.listChanged) {\n throw new Error(`Client does not support roots list changed notifications (required for ${method})`);\n }\n break;\n case 'notifications/initialized':\n // No specific capability required for initialized\n break;\n case 'notifications/cancelled':\n // Cancellation notifications are always allowed\n break;\n case 'notifications/progress':\n // Progress notifications are always allowed\n break;\n }\n }\n assertRequestHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n switch (method) {\n case 'sampling/createMessage':\n if (!this._capabilities.sampling) {\n throw new Error(`Client does not support sampling capability (required for ${method})`);\n }\n break;\n case 'elicitation/create':\n if (!this._capabilities.elicitation) {\n throw new Error(`Client does not support elicitation capability (required for ${method})`);\n }\n break;\n case 'roots/list':\n if (!this._capabilities.roots) {\n throw new Error(`Client does not support roots capability (required for ${method})`);\n }\n break;\n case 'tasks/get':\n case 'tasks/list':\n case 'tasks/result':\n case 'tasks/cancel':\n if (!this._capabilities.tasks) {\n throw new Error(`Client does not support tasks capability (required for ${method})`);\n }\n break;\n case 'ping':\n // No specific capability required for ping\n break;\n }\n }\n assertTaskCapability(method) {\n assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, 'Server');\n }\n assertTaskHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, 'Client');\n }\n async ping(options) {\n return this.request({ method: 'ping' }, EmptyResultSchema, options);\n }\n async complete(params, options) {\n return this.request({ method: 'completion/complete', params }, CompleteResultSchema, options);\n }\n async setLoggingLevel(level, options) {\n return this.request({ method: 'logging/setLevel', params: { level } }, EmptyResultSchema, options);\n }\n async getPrompt(params, options) {\n return this.request({ method: 'prompts/get', params }, GetPromptResultSchema, options);\n }\n async listPrompts(params, options) {\n return this.request({ method: 'prompts/list', params }, ListPromptsResultSchema, options);\n }\n async listResources(params, options) {\n return this.request({ method: 'resources/list', params }, ListResourcesResultSchema, options);\n }\n async listResourceTemplates(params, options) {\n return this.request({ method: 'resources/templates/list', params }, ListResourceTemplatesResultSchema, options);\n }\n async readResource(params, options) {\n return this.request({ method: 'resources/read', params }, ReadResourceResultSchema, options);\n }\n async subscribeResource(params, options) {\n return this.request({ method: 'resources/subscribe', params }, EmptyResultSchema, options);\n }\n async unsubscribeResource(params, options) {\n return this.request({ method: 'resources/unsubscribe', params }, EmptyResultSchema, options);\n }\n /**\n * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.\n *\n * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.\n */\n async callTool(params, resultSchema = CallToolResultSchema, options) {\n // Guard: required-task tools need experimental API\n if (this.isToolTaskRequired(params.name)) {\n throw new McpError(ErrorCode.InvalidRequest, `Tool \"${params.name}\" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);\n }\n const result = await this.request({ method: 'tools/call', params }, resultSchema, options);\n // Check if the tool has an outputSchema\n const validator = this.getToolOutputValidator(params.name);\n if (validator) {\n // If tool has outputSchema, it MUST return structuredContent (unless it's an error)\n if (!result.structuredContent && !result.isError) {\n throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);\n }\n // Only validate structured content if present (not when there's an error)\n if (result.structuredContent) {\n try {\n // Validate the structured content against the schema\n const validationResult = validator(result.structuredContent);\n if (!validationResult.valid) {\n throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);\n }\n }\n catch (error) {\n if (error instanceof McpError) {\n throw error;\n }\n throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n }\n return result;\n }\n isToolTask(toolName) {\n if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {\n return false;\n }\n return this._cachedKnownTaskTools.has(toolName);\n }\n /**\n * Check if a tool requires task-based execution.\n * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.\n */\n isToolTaskRequired(toolName) {\n return this._cachedRequiredTaskTools.has(toolName);\n }\n /**\n * Cache validators for tool output schemas.\n * Called after listTools() to pre-compile validators for better performance.\n */\n cacheToolMetadata(tools) {\n this._cachedToolOutputValidators.clear();\n this._cachedKnownTaskTools.clear();\n this._cachedRequiredTaskTools.clear();\n for (const tool of tools) {\n // If the tool has an outputSchema, create and cache the validator\n if (tool.outputSchema) {\n const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);\n this._cachedToolOutputValidators.set(tool.name, toolValidator);\n }\n // If the tool supports task-based execution, cache that information\n const taskSupport = tool.execution?.taskSupport;\n if (taskSupport === 'required' || taskSupport === 'optional') {\n this._cachedKnownTaskTools.add(tool.name);\n }\n if (taskSupport === 'required') {\n this._cachedRequiredTaskTools.add(tool.name);\n }\n }\n }\n /**\n * Get cached validator for a tool\n */\n getToolOutputValidator(toolName) {\n return this._cachedToolOutputValidators.get(toolName);\n }\n async listTools(params, options) {\n const result = await this.request({ method: 'tools/list', params }, ListToolsResultSchema, options);\n // Cache the tools and their output schemas for future validation\n this.cacheToolMetadata(result.tools);\n return result;\n }\n /**\n * Set up a single list changed handler.\n * @internal\n */\n _setupListChangedHandler(listType, notificationSchema, options, fetcher) {\n // Validate options using Zod schema (validates autoRefresh and debounceMs)\n const parseResult = ListChangedOptionsBaseSchema.safeParse(options);\n if (!parseResult.success) {\n throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);\n }\n // Validate callback\n if (typeof options.onChanged !== 'function') {\n throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);\n }\n const { autoRefresh, debounceMs } = parseResult.data;\n const { onChanged } = options;\n const refresh = async () => {\n if (!autoRefresh) {\n onChanged(null, null);\n return;\n }\n try {\n const items = await fetcher();\n onChanged(null, items);\n }\n catch (e) {\n const error = e instanceof Error ? e : new Error(String(e));\n onChanged(error, null);\n }\n };\n const handler = () => {\n if (debounceMs) {\n // Clear any pending debounce timer for this list type\n const existingTimer = this._listChangedDebounceTimers.get(listType);\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n // Set up debounced refresh\n const timer = setTimeout(refresh, debounceMs);\n this._listChangedDebounceTimers.set(listType, timer);\n }\n else {\n // No debounce, refresh immediately\n refresh();\n }\n };\n // Register notification handler\n this.setNotificationHandler(notificationSchema, handler);\n }\n async sendRootsListChanged() {\n return this.notification({ method: 'notifications/roots/list_changed' });\n }\n}\n//# sourceMappingURL=index.js.map","import { JSONRPCMessageSchema } from '../types.js';\n/**\n * Buffers a continuous stdio stream into discrete JSON-RPC messages.\n */\nexport class ReadBuffer {\n append(chunk) {\n this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;\n }\n readMessage() {\n if (!this._buffer) {\n return null;\n }\n const index = this._buffer.indexOf('\\n');\n if (index === -1) {\n return null;\n }\n const line = this._buffer.toString('utf8', 0, index).replace(/\\r$/, '');\n this._buffer = this._buffer.subarray(index + 1);\n return deserializeMessage(line);\n }\n clear() {\n this._buffer = undefined;\n }\n}\nexport function deserializeMessage(line) {\n return JSONRPCMessageSchema.parse(JSON.parse(line));\n}\nexport function serializeMessage(message) {\n return JSON.stringify(message) + '\\n';\n}\n//# sourceMappingURL=stdio.js.map","/**\n * Experimental server task features for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\nimport { CreateMessageResultSchema, ElicitResultSchema } from '../../types.js';\n/**\n * Experimental task features for low-level MCP servers.\n *\n * Access via `server.experimental.tasks`:\n * ```typescript\n * const stream = server.experimental.tasks.requestStream(request, schema, options);\n * ```\n *\n * For high-level server usage with task-based tools, use `McpServer.experimental.tasks` instead.\n *\n * @experimental\n */\nexport class ExperimentalServerTasks {\n constructor(_server) {\n this._server = _server;\n }\n /**\n * Sends a request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * This method provides streaming access to request processing, allowing you to\n * observe intermediate task status updates for task-augmented requests.\n *\n * @param request - The request to send\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options (timeout, signal, task creation params, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n requestStream(request, resultSchema, options) {\n return this._server.requestStream(request, resultSchema, options);\n }\n /**\n * Sends a sampling request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages\n * before the final result.\n *\n * @example\n * ```typescript\n * const stream = server.experimental.tasks.createMessageStream({\n * messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }],\n * maxTokens: 100\n * }, {\n * onprogress: (progress) => {\n * // Handle streaming tokens via progress notifications\n * console.log('Progress:', progress.message);\n * }\n * });\n *\n * for await (const message of stream) {\n * switch (message.type) {\n * case 'taskCreated':\n * console.log('Task created:', message.task.taskId);\n * break;\n * case 'taskStatus':\n * console.log('Task status:', message.task.status);\n * break;\n * case 'result':\n * console.log('Final result:', message.result);\n * break;\n * case 'error':\n * console.error('Error:', message.error);\n * break;\n * }\n * }\n * ```\n *\n * @param params - The sampling request parameters\n * @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n createMessageStream(params, options) {\n // Access client capabilities via the server\n const clientCapabilities = this._server.getClientCapabilities();\n // Capability check - only required when tools/toolChoice are provided\n if ((params.tools || params.toolChoice) && !clientCapabilities?.sampling?.tools) {\n throw new Error('Client does not support sampling tools capability.');\n }\n // Message structure validation - always validate tool_use/tool_result pairs.\n // These may appear even without tools/toolChoice in the current request when\n // a previous sampling request returned tool_use and this is a follow-up with results.\n if (params.messages.length > 0) {\n const lastMessage = params.messages[params.messages.length - 1];\n const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];\n const hasToolResults = lastContent.some(c => c.type === 'tool_result');\n const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined;\n const previousContent = previousMessage\n ? Array.isArray(previousMessage.content)\n ? previousMessage.content\n : [previousMessage.content]\n : [];\n const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use');\n if (hasToolResults) {\n if (lastContent.some(c => c.type !== 'tool_result')) {\n throw new Error('The last message must contain only tool_result content if any is present');\n }\n if (!hasPreviousToolUse) {\n throw new Error('tool_result blocks are not matching any tool_use from the previous message');\n }\n }\n if (hasPreviousToolUse) {\n // Extract tool_use IDs from previous message and tool_result IDs from current message\n const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id));\n const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId));\n if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) {\n throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match');\n }\n }\n }\n return this.requestStream({\n method: 'sampling/createMessage',\n params\n }, CreateMessageResultSchema, options);\n }\n /**\n * Sends an elicitation request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * For task-augmented requests (especially URL-based elicitation), yields 'taskCreated'\n * and 'taskStatus' messages before the final result.\n *\n * @example\n * ```typescript\n * const stream = server.experimental.tasks.elicitInputStream({\n * mode: 'url',\n * message: 'Please authenticate',\n * elicitationId: 'auth-123',\n * url: 'https://example.com/auth'\n * }, {\n * task: { ttl: 300000 } // Task-augmented for long-running auth flow\n * });\n *\n * for await (const message of stream) {\n * switch (message.type) {\n * case 'taskCreated':\n * console.log('Task created:', message.task.taskId);\n * break;\n * case 'taskStatus':\n * console.log('Task status:', message.task.status);\n * break;\n * case 'result':\n * console.log('User action:', message.result.action);\n * break;\n * case 'error':\n * console.error('Error:', message.error);\n * break;\n * }\n * }\n * ```\n *\n * @param params - The elicitation request parameters\n * @param options - Optional request options (timeout, signal, task creation params, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n elicitInputStream(params, options) {\n // Access client capabilities via the server\n const clientCapabilities = this._server.getClientCapabilities();\n const mode = params.mode ?? 'form';\n // Capability check based on mode\n switch (mode) {\n case 'url': {\n if (!clientCapabilities?.elicitation?.url) {\n throw new Error('Client does not support url elicitation.');\n }\n break;\n }\n case 'form': {\n if (!clientCapabilities?.elicitation?.form) {\n throw new Error('Client does not support form elicitation.');\n }\n break;\n }\n }\n // Normalize params to ensure mode is set for form mode (defaults to 'form' per spec)\n const normalizedParams = mode === 'form' && params.mode === undefined ? { ...params, mode: 'form' } : params;\n // Cast to ServerRequest needed because TypeScript can't narrow the union type\n // based on the discriminated 'method' field when constructing the object literal\n return this.requestStream({\n method: 'elicitation/create',\n params: normalizedParams\n }, ElicitResultSchema, options);\n }\n /**\n * Gets the current status of a task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n * @returns The task status\n *\n * @experimental\n */\n async getTask(taskId, options) {\n return this._server.getTask({ taskId }, options);\n }\n /**\n * Retrieves the result of a completed task.\n *\n * @param taskId - The task identifier\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options\n * @returns The task result\n *\n * @experimental\n */\n async getTaskResult(taskId, resultSchema, options) {\n return this._server.getTaskResult({ taskId }, resultSchema, options);\n }\n /**\n * Lists tasks with optional pagination.\n *\n * @param cursor - Optional pagination cursor\n * @param options - Optional request options\n * @returns List of tasks with optional next cursor\n *\n * @experimental\n */\n async listTasks(cursor, options) {\n return this._server.listTasks(cursor ? { cursor } : undefined, options);\n }\n /**\n * Cancels a running task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n *\n * @experimental\n */\n async cancelTask(taskId, options) {\n return this._server.cancelTask({ taskId }, options);\n }\n}\n//# sourceMappingURL=server.js.map","import { mergeCapabilities, Protocol } from '../shared/protocol.js';\nimport { CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ElicitResultSchema, EmptyResultSchema, ErrorCode, InitializedNotificationSchema, InitializeRequestSchema, LATEST_PROTOCOL_VERSION, ListRootsResultSchema, LoggingLevelSchema, McpError, SetLevelRequestSchema, SUPPORTED_PROTOCOL_VERSIONS, CallToolRequestSchema, CallToolResultSchema, CreateTaskResultSchema } from '../types.js';\nimport { AjvJsonSchemaValidator } from '../validation/ajv-provider.js';\nimport { getObjectShape, isZ4Schema, safeParse } from './zod-compat.js';\nimport { ExperimentalServerTasks } from '../experimental/tasks/server.js';\nimport { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js';\n/**\n * An MCP server on top of a pluggable transport.\n *\n * This server will automatically respond to the initialization flow as initiated from the client.\n *\n * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:\n *\n * ```typescript\n * // Custom schemas\n * const CustomRequestSchema = RequestSchema.extend({...})\n * const CustomNotificationSchema = NotificationSchema.extend({...})\n * const CustomResultSchema = ResultSchema.extend({...})\n *\n * // Type aliases\n * type CustomRequest = z.infer<typeof CustomRequestSchema>\n * type CustomNotification = z.infer<typeof CustomNotificationSchema>\n * type CustomResult = z.infer<typeof CustomResultSchema>\n *\n * // Create typed server\n * const server = new Server<CustomRequest, CustomNotification, CustomResult>({\n * name: \"CustomServer\",\n * version: \"1.0.0\"\n * })\n * ```\n * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases.\n */\nexport class Server extends Protocol {\n /**\n * Initializes this server with the given name and version information.\n */\n constructor(_serverInfo, options) {\n super(options);\n this._serverInfo = _serverInfo;\n // Map log levels by session id\n this._loggingLevels = new Map();\n // Map LogLevelSchema to severity index\n this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index]));\n // Is a message with the given level ignored in the log level set for the given session id?\n this.isMessageIgnored = (level, sessionId) => {\n const currentLevel = this._loggingLevels.get(sessionId);\n return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false;\n };\n this._capabilities = options?.capabilities ?? {};\n this._instructions = options?.instructions;\n this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();\n this.setRequestHandler(InitializeRequestSchema, request => this._oninitialize(request));\n this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.());\n if (this._capabilities.logging) {\n this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => {\n const transportSessionId = extra.sessionId || extra.requestInfo?.headers['mcp-session-id'] || undefined;\n const { level } = request.params;\n const parseResult = LoggingLevelSchema.safeParse(level);\n if (parseResult.success) {\n this._loggingLevels.set(transportSessionId, parseResult.data);\n }\n return {};\n });\n }\n }\n /**\n * Access experimental features.\n *\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n get experimental() {\n if (!this._experimental) {\n this._experimental = {\n tasks: new ExperimentalServerTasks(this)\n };\n }\n return this._experimental;\n }\n /**\n * Registers new capabilities. This can only be called before connecting to a transport.\n *\n * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).\n */\n registerCapabilities(capabilities) {\n if (this.transport) {\n throw new Error('Cannot register capabilities after connecting to transport');\n }\n this._capabilities = mergeCapabilities(this._capabilities, capabilities);\n }\n /**\n * Override request handler registration to enforce server-side validation for tools/call.\n */\n setRequestHandler(requestSchema, handler) {\n const shape = getObjectShape(requestSchema);\n const methodSchema = shape?.method;\n if (!methodSchema) {\n throw new Error('Schema is missing a method literal');\n }\n // Extract literal value using type-safe property access\n let methodValue;\n if (isZ4Schema(methodSchema)) {\n const v4Schema = methodSchema;\n const v4Def = v4Schema._zod?.def;\n methodValue = v4Def?.value ?? v4Schema.value;\n }\n else {\n const v3Schema = methodSchema;\n const legacyDef = v3Schema._def;\n methodValue = legacyDef?.value ?? v3Schema.value;\n }\n if (typeof methodValue !== 'string') {\n throw new Error('Schema method literal must be a string');\n }\n const method = methodValue;\n if (method === 'tools/call') {\n const wrappedHandler = async (request, extra) => {\n const validatedRequest = safeParse(CallToolRequestSchema, request);\n if (!validatedRequest.success) {\n const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`);\n }\n const { params } = validatedRequest.data;\n const result = await Promise.resolve(handler(request, extra));\n // When task creation is requested, validate and return CreateTaskResult\n if (params.task) {\n const taskValidationResult = safeParse(CreateTaskResultSchema, result);\n if (!taskValidationResult.success) {\n const errorMessage = taskValidationResult.error instanceof Error\n ? taskValidationResult.error.message\n : String(taskValidationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);\n }\n return taskValidationResult.data;\n }\n // For non-task requests, validate against CallToolResultSchema\n const validationResult = safeParse(CallToolResultSchema, result);\n if (!validationResult.success) {\n const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`);\n }\n return validationResult.data;\n };\n // Install the wrapped handler\n return super.setRequestHandler(requestSchema, wrappedHandler);\n }\n // Other handlers use default behavior\n return super.setRequestHandler(requestSchema, handler);\n }\n assertCapabilityForMethod(method) {\n switch (method) {\n case 'sampling/createMessage':\n if (!this._clientCapabilities?.sampling) {\n throw new Error(`Client does not support sampling (required for ${method})`);\n }\n break;\n case 'elicitation/create':\n if (!this._clientCapabilities?.elicitation) {\n throw new Error(`Client does not support elicitation (required for ${method})`);\n }\n break;\n case 'roots/list':\n if (!this._clientCapabilities?.roots) {\n throw new Error(`Client does not support listing roots (required for ${method})`);\n }\n break;\n case 'ping':\n // No specific capability required for ping\n break;\n }\n }\n assertNotificationCapability(method) {\n switch (method) {\n case 'notifications/message':\n if (!this._capabilities.logging) {\n throw new Error(`Server does not support logging (required for ${method})`);\n }\n break;\n case 'notifications/resources/updated':\n case 'notifications/resources/list_changed':\n if (!this._capabilities.resources) {\n throw new Error(`Server does not support notifying about resources (required for ${method})`);\n }\n break;\n case 'notifications/tools/list_changed':\n if (!this._capabilities.tools) {\n throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);\n }\n break;\n case 'notifications/prompts/list_changed':\n if (!this._capabilities.prompts) {\n throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);\n }\n break;\n case 'notifications/elicitation/complete':\n if (!this._clientCapabilities?.elicitation?.url) {\n throw new Error(`Client does not support URL elicitation (required for ${method})`);\n }\n break;\n case 'notifications/cancelled':\n // Cancellation notifications are always allowed\n break;\n case 'notifications/progress':\n // Progress notifications are always allowed\n break;\n }\n }\n assertRequestHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n switch (method) {\n case 'completion/complete':\n if (!this._capabilities.completions) {\n throw new Error(`Server does not support completions (required for ${method})`);\n }\n break;\n case 'logging/setLevel':\n if (!this._capabilities.logging) {\n throw new Error(`Server does not support logging (required for ${method})`);\n }\n break;\n case 'prompts/get':\n case 'prompts/list':\n if (!this._capabilities.prompts) {\n throw new Error(`Server does not support prompts (required for ${method})`);\n }\n break;\n case 'resources/list':\n case 'resources/templates/list':\n case 'resources/read':\n if (!this._capabilities.resources) {\n throw new Error(`Server does not support resources (required for ${method})`);\n }\n break;\n case 'tools/call':\n case 'tools/list':\n if (!this._capabilities.tools) {\n throw new Error(`Server does not support tools (required for ${method})`);\n }\n break;\n case 'tasks/get':\n case 'tasks/list':\n case 'tasks/result':\n case 'tasks/cancel':\n if (!this._capabilities.tasks) {\n throw new Error(`Server does not support tasks capability (required for ${method})`);\n }\n break;\n case 'ping':\n case 'initialize':\n // No specific capability required for these methods\n break;\n }\n }\n assertTaskCapability(method) {\n assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, 'Client');\n }\n assertTaskHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, 'Server');\n }\n async _oninitialize(request) {\n const requestedVersion = request.params.protocolVersion;\n this._clientCapabilities = request.params.capabilities;\n this._clientVersion = request.params.clientInfo;\n const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION;\n return {\n protocolVersion,\n capabilities: this.getCapabilities(),\n serverInfo: this._serverInfo,\n ...(this._instructions && { instructions: this._instructions })\n };\n }\n /**\n * After initialization has completed, this will be populated with the client's reported capabilities.\n */\n getClientCapabilities() {\n return this._clientCapabilities;\n }\n /**\n * After initialization has completed, this will be populated with information about the client's name and version.\n */\n getClientVersion() {\n return this._clientVersion;\n }\n getCapabilities() {\n return this._capabilities;\n }\n async ping() {\n return this.request({ method: 'ping' }, EmptyResultSchema);\n }\n // Implementation\n async createMessage(params, options) {\n // Capability check - only required when tools/toolChoice are provided\n if (params.tools || params.toolChoice) {\n if (!this._clientCapabilities?.sampling?.tools) {\n throw new Error('Client does not support sampling tools capability.');\n }\n }\n // Message structure validation - always validate tool_use/tool_result pairs.\n // These may appear even without tools/toolChoice in the current request when\n // a previous sampling request returned tool_use and this is a follow-up with results.\n if (params.messages.length > 0) {\n const lastMessage = params.messages[params.messages.length - 1];\n const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];\n const hasToolResults = lastContent.some(c => c.type === 'tool_result');\n const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined;\n const previousContent = previousMessage\n ? Array.isArray(previousMessage.content)\n ? previousMessage.content\n : [previousMessage.content]\n : [];\n const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use');\n if (hasToolResults) {\n if (lastContent.some(c => c.type !== 'tool_result')) {\n throw new Error('The last message must contain only tool_result content if any is present');\n }\n if (!hasPreviousToolUse) {\n throw new Error('tool_result blocks are not matching any tool_use from the previous message');\n }\n }\n if (hasPreviousToolUse) {\n const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id));\n const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId));\n if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) {\n throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match');\n }\n }\n }\n // Use different schemas based on whether tools are provided\n if (params.tools) {\n return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultWithToolsSchema, options);\n }\n return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultSchema, options);\n }\n /**\n * Creates an elicitation request for the given parameters.\n * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`.\n * @param params The parameters for the elicitation request.\n * @param options Optional request options.\n * @returns The result of the elicitation request.\n */\n async elicitInput(params, options) {\n const mode = (params.mode ?? 'form');\n switch (mode) {\n case 'url': {\n if (!this._clientCapabilities?.elicitation?.url) {\n throw new Error('Client does not support url elicitation.');\n }\n const urlParams = params;\n return this.request({ method: 'elicitation/create', params: urlParams }, ElicitResultSchema, options);\n }\n case 'form': {\n if (!this._clientCapabilities?.elicitation?.form) {\n throw new Error('Client does not support form elicitation.');\n }\n const formParams = params.mode === 'form' ? params : { ...params, mode: 'form' };\n const result = await this.request({ method: 'elicitation/create', params: formParams }, ElicitResultSchema, options);\n if (result.action === 'accept' && result.content && formParams.requestedSchema) {\n try {\n const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema);\n const validationResult = validator(result.content);\n if (!validationResult.valid) {\n throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`);\n }\n }\n catch (error) {\n if (error instanceof McpError) {\n throw error;\n }\n throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return result;\n }\n }\n }\n /**\n * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete`\n * notification for the specified elicitation ID.\n *\n * @param elicitationId The ID of the elicitation to mark as complete.\n * @param options Optional notification options. Useful when the completion notification should be related to a prior request.\n * @returns A function that emits the completion notification when awaited.\n */\n createElicitationCompletionNotifier(elicitationId, options) {\n if (!this._clientCapabilities?.elicitation?.url) {\n throw new Error('Client does not support URL elicitation (required for notifications/elicitation/complete)');\n }\n return () => this.notification({\n method: 'notifications/elicitation/complete',\n params: {\n elicitationId\n }\n }, options);\n }\n async listRoots(params, options) {\n return this.request({ method: 'roots/list', params }, ListRootsResultSchema, options);\n }\n /**\n * Sends a logging message to the client, if connected.\n * Note: You only need to send the parameters object, not the entire JSON RPC message\n * @see LoggingMessageNotification\n * @param params\n * @param sessionId optional for stateless and backward compatibility\n */\n async sendLoggingMessage(params, sessionId) {\n if (this._capabilities.logging) {\n if (!this.isMessageIgnored(params.level, sessionId)) {\n return this.notification({ method: 'notifications/message', params });\n }\n }\n }\n async sendResourceUpdated(params) {\n return this.notification({\n method: 'notifications/resources/updated',\n params\n });\n }\n async sendResourceListChanged() {\n return this.notification({\n method: 'notifications/resources/list_changed'\n });\n }\n async sendToolListChanged() {\n return this.notification({ method: 'notifications/tools/list_changed' });\n }\n async sendPromptListChanged() {\n return this.notification({ method: 'notifications/prompts/list_changed' });\n }\n}\n//# sourceMappingURL=index.js.map","export const COMPLETABLE_SYMBOL = Symbol.for('mcp.completable');\n/**\n * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP.\n * Works with both Zod v3 and v4 schemas.\n */\nexport function completable(schema, complete) {\n Object.defineProperty(schema, COMPLETABLE_SYMBOL, {\n value: { complete },\n enumerable: false,\n writable: false,\n configurable: false\n });\n return schema;\n}\n/**\n * Checks if a schema is completable (has completion metadata).\n */\nexport function isCompletable(schema) {\n return !!schema && typeof schema === 'object' && COMPLETABLE_SYMBOL in schema;\n}\n/**\n * Gets the completer callback from a completable schema, if it exists.\n */\nexport function getCompleter(schema) {\n const meta = schema[COMPLETABLE_SYMBOL];\n return meta?.complete;\n}\n/**\n * Unwraps a completable schema to get the underlying schema.\n * For backward compatibility with code that called `.unwrap()`.\n */\nexport function unwrapCompletable(schema) {\n return schema;\n}\n// Legacy exports for backward compatibility\n// These types are deprecated but kept for existing code\nexport var McpZodTypeKind;\n(function (McpZodTypeKind) {\n McpZodTypeKind[\"Completable\"] = \"McpCompletable\";\n})(McpZodTypeKind || (McpZodTypeKind = {}));\n//# sourceMappingURL=completable.js.map","/**\n * Tool name validation utilities according to SEP: Specify Format for Tool Names\n *\n * Tool names SHOULD be between 1 and 128 characters in length (inclusive).\n * Tool names are case-sensitive.\n * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits\n * (0-9), underscore (_), dash (-), and dot (.).\n * Tool names SHOULD NOT contain spaces, commas, or other special characters.\n */\n/**\n * Regular expression for valid tool names according to SEP-986 specification\n */\nconst TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;\n/**\n * Validates a tool name according to the SEP specification\n * @param name - The tool name to validate\n * @returns An object containing validation result and any warnings\n */\nexport function validateToolName(name) {\n const warnings = [];\n // Check length\n if (name.length === 0) {\n return {\n isValid: false,\n warnings: ['Tool name cannot be empty']\n };\n }\n if (name.length > 128) {\n return {\n isValid: false,\n warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]\n };\n }\n // Check for specific problematic patterns (these are warnings, not validation failures)\n if (name.includes(' ')) {\n warnings.push('Tool name contains spaces, which may cause parsing issues');\n }\n if (name.includes(',')) {\n warnings.push('Tool name contains commas, which may cause parsing issues');\n }\n // Check for potentially confusing patterns (leading/trailing dashes, dots, slashes)\n if (name.startsWith('-') || name.endsWith('-')) {\n warnings.push('Tool name starts or ends with a dash, which may cause parsing issues in some contexts');\n }\n if (name.startsWith('.') || name.endsWith('.')) {\n warnings.push('Tool name starts or ends with a dot, which may cause parsing issues in some contexts');\n }\n // Check for invalid characters\n if (!TOOL_NAME_REGEX.test(name)) {\n const invalidChars = name\n .split('')\n .filter(char => !/[A-Za-z0-9._-]/.test(char))\n .filter((char, index, arr) => arr.indexOf(char) === index); // Remove duplicates\n warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c => `\"${c}\"`).join(', ')}`, 'Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)');\n return {\n isValid: false,\n warnings\n };\n }\n return {\n isValid: true,\n warnings\n };\n}\n/**\n * Issues warnings for non-conforming tool names\n * @param name - The tool name that triggered the warnings\n * @param warnings - Array of warning messages\n */\nexport function issueToolNameWarning(name, warnings) {\n if (warnings.length > 0) {\n console.warn(`Tool name validation warning for \"${name}\":`);\n for (const warning of warnings) {\n console.warn(` - ${warning}`);\n }\n console.warn('Tool registration will proceed, but this may cause compatibility issues.');\n console.warn('Consider updating the tool name to conform to the MCP tool naming standard.');\n console.warn('See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.');\n }\n}\n/**\n * Validates a tool name and issues warnings for non-conforming names\n * @param name - The tool name to validate\n * @returns true if the name is valid, false otherwise\n */\nexport function validateAndWarnToolName(name) {\n const result = validateToolName(name);\n // Always issue warnings for any validation issues (both invalid names and warnings)\n issueToolNameWarning(name, result.warnings);\n return result.isValid;\n}\n//# sourceMappingURL=toolNameValidation.js.map","/**\n * Experimental McpServer task features for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n/**\n * Experimental task features for McpServer.\n *\n * Access via `server.experimental.tasks`:\n * ```typescript\n * server.experimental.tasks.registerToolTask('long-running', config, handler);\n * ```\n *\n * @experimental\n */\nexport class ExperimentalMcpServerTasks {\n constructor(_mcpServer) {\n this._mcpServer = _mcpServer;\n }\n registerToolTask(name, config, handler) {\n // Validate that taskSupport is not 'forbidden' for task-based tools\n const execution = { taskSupport: 'required', ...config.execution };\n if (execution.taskSupport === 'forbidden') {\n throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`);\n }\n // Access McpServer's internal _createRegisteredTool method\n const mcpServerInternal = this._mcpServer;\n return mcpServerInternal._createRegisteredTool(name, config.title, config.description, config.inputSchema, config.outputSchema, config.annotations, execution, config._meta, handler);\n }\n}\n//# sourceMappingURL=mcp-server.js.map","import { Server } from './index.js';\nimport { normalizeObjectSchema, safeParseAsync, getObjectShape, objectFromShape, getParseErrorMessage, getSchemaDescription, isSchemaOptional, getLiteralValue } from './zod-compat.js';\nimport { toJsonSchemaCompat } from './zod-json-schema-compat.js';\nimport { McpError, ErrorCode, ListResourceTemplatesRequestSchema, ReadResourceRequestSchema, ListToolsRequestSchema, CallToolRequestSchema, ListResourcesRequestSchema, ListPromptsRequestSchema, GetPromptRequestSchema, CompleteRequestSchema, assertCompleteRequestPrompt, assertCompleteRequestResourceTemplate } from '../types.js';\nimport { isCompletable, getCompleter } from './completable.js';\nimport { UriTemplate } from '../shared/uriTemplate.js';\nimport { validateAndWarnToolName } from '../shared/toolNameValidation.js';\nimport { ExperimentalMcpServerTasks } from '../experimental/tasks/mcp-server.js';\nimport { ZodOptional } from 'zod';\n/**\n * High-level MCP server that provides a simpler API for working with resources, tools, and prompts.\n * For advanced usage (like sending notifications or setting custom request handlers), use the underlying\n * Server instance available via the `server` property.\n */\nexport class McpServer {\n constructor(serverInfo, options) {\n this._registeredResources = {};\n this._registeredResourceTemplates = {};\n this._registeredTools = {};\n this._registeredPrompts = {};\n this._toolHandlersInitialized = false;\n this._completionHandlerInitialized = false;\n this._resourceHandlersInitialized = false;\n this._promptHandlersInitialized = false;\n this.server = new Server(serverInfo, options);\n }\n /**\n * Access experimental features.\n *\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n get experimental() {\n if (!this._experimental) {\n this._experimental = {\n tasks: new ExperimentalMcpServerTasks(this)\n };\n }\n return this._experimental;\n }\n /**\n * Attaches to the given transport, starts it, and starts listening for messages.\n *\n * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.\n */\n async connect(transport) {\n return await this.server.connect(transport);\n }\n /**\n * Closes the connection.\n */\n async close() {\n await this.server.close();\n }\n setToolRequestHandlers() {\n if (this._toolHandlersInitialized) {\n return;\n }\n this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema));\n this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema));\n this.server.registerCapabilities({\n tools: {\n listChanged: true\n }\n });\n this.server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: Object.entries(this._registeredTools)\n .filter(([, tool]) => tool.enabled)\n .map(([name, tool]) => {\n const toolDefinition = {\n name,\n title: tool.title,\n description: tool.description,\n inputSchema: (() => {\n const obj = normalizeObjectSchema(tool.inputSchema);\n return obj\n ? toJsonSchemaCompat(obj, {\n strictUnions: true,\n pipeStrategy: 'input'\n })\n : EMPTY_OBJECT_JSON_SCHEMA;\n })(),\n annotations: tool.annotations,\n execution: tool.execution,\n _meta: tool._meta\n };\n if (tool.outputSchema) {\n const obj = normalizeObjectSchema(tool.outputSchema);\n if (obj) {\n toolDefinition.outputSchema = toJsonSchemaCompat(obj, {\n strictUnions: true,\n pipeStrategy: 'output'\n });\n }\n }\n return toolDefinition;\n })\n }));\n this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n try {\n const tool = this._registeredTools[request.params.name];\n if (!tool) {\n throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`);\n }\n if (!tool.enabled) {\n throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);\n }\n const isTaskRequest = !!request.params.task;\n const taskSupport = tool.execution?.taskSupport;\n const isTaskHandler = 'createTask' in tool.handler;\n // Validate task hint configuration\n if ((taskSupport === 'required' || taskSupport === 'optional') && !isTaskHandler) {\n throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);\n }\n // Handle taskSupport 'required' without task augmentation\n if (taskSupport === 'required' && !isTaskRequest) {\n throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);\n }\n // Handle taskSupport 'optional' without task augmentation - automatic polling\n if (taskSupport === 'optional' && !isTaskRequest && isTaskHandler) {\n return await this.handleAutomaticTaskPolling(tool, request, extra);\n }\n // Normal execution path\n const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);\n const result = await this.executeToolHandler(tool, args, extra);\n // Return CreateTaskResult immediately for task requests\n if (isTaskRequest) {\n return result;\n }\n // Validate output schema for non-task requests\n await this.validateToolOutput(tool, result, request.params.name);\n return result;\n }\n catch (error) {\n if (error instanceof McpError) {\n if (error.code === ErrorCode.UrlElicitationRequired) {\n throw error; // Return the error to the caller without wrapping in CallToolResult\n }\n }\n return this.createToolError(error instanceof Error ? error.message : String(error));\n }\n });\n this._toolHandlersInitialized = true;\n }\n /**\n * Creates a tool error result.\n *\n * @param errorMessage - The error message.\n * @returns The tool error result.\n */\n createToolError(errorMessage) {\n return {\n content: [\n {\n type: 'text',\n text: errorMessage\n }\n ],\n isError: true\n };\n }\n /**\n * Validates tool input arguments against the tool's input schema.\n */\n async validateToolInput(tool, args, toolName) {\n if (!tool.inputSchema) {\n return undefined;\n }\n // Try to normalize to object schema first (for raw shapes and object schemas)\n // If that fails, use the schema directly (for union/intersection/etc)\n const inputObj = normalizeObjectSchema(tool.inputSchema);\n const schemaToParse = inputObj ?? tool.inputSchema;\n const parseResult = await safeParseAsync(schemaToParse, args);\n if (!parseResult.success) {\n const error = 'error' in parseResult ? parseResult.error : 'Unknown error';\n const errorMessage = getParseErrorMessage(error);\n throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`);\n }\n return parseResult.data;\n }\n /**\n * Validates tool output against the tool's output schema.\n */\n async validateToolOutput(tool, result, toolName) {\n if (!tool.outputSchema) {\n return;\n }\n // Only validate CallToolResult, not CreateTaskResult\n if (!('content' in result)) {\n return;\n }\n if (result.isError) {\n return;\n }\n if (!result.structuredContent) {\n throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);\n }\n // if the tool has an output schema, validate structured content\n const outputObj = normalizeObjectSchema(tool.outputSchema);\n const parseResult = await safeParseAsync(outputObj, result.structuredContent);\n if (!parseResult.success) {\n const error = 'error' in parseResult ? parseResult.error : 'Unknown error';\n const errorMessage = getParseErrorMessage(error);\n throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`);\n }\n }\n /**\n * Executes a tool handler (either regular or task-based).\n */\n async executeToolHandler(tool, args, extra) {\n const handler = tool.handler;\n const isTaskHandler = 'createTask' in handler;\n if (isTaskHandler) {\n if (!extra.taskStore) {\n throw new Error('No task store provided.');\n }\n const taskExtra = { ...extra, taskStore: extra.taskStore };\n if (tool.inputSchema) {\n const typedHandler = handler;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return await Promise.resolve(typedHandler.createTask(args, taskExtra));\n }\n else {\n const typedHandler = handler;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return await Promise.resolve(typedHandler.createTask(taskExtra));\n }\n }\n if (tool.inputSchema) {\n const typedHandler = handler;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return await Promise.resolve(typedHandler(args, extra));\n }\n else {\n const typedHandler = handler;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return await Promise.resolve(typedHandler(extra));\n }\n }\n /**\n * Handles automatic task polling for tools with taskSupport 'optional'.\n */\n async handleAutomaticTaskPolling(tool, request, extra) {\n if (!extra.taskStore) {\n throw new Error('No task store provided for task-capable tool.');\n }\n // Validate input and create task\n const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);\n const handler = tool.handler;\n const taskExtra = { ...extra, taskStore: extra.taskStore };\n const createTaskResult = args // undefined only if tool.inputSchema is undefined\n ? await Promise.resolve(handler.createTask(args, taskExtra))\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await Promise.resolve(handler.createTask(taskExtra));\n // Poll until completion\n const taskId = createTaskResult.task.taskId;\n let task = createTaskResult.task;\n const pollInterval = task.pollInterval ?? 5000;\n while (task.status !== 'completed' && task.status !== 'failed' && task.status !== 'cancelled') {\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n const updatedTask = await extra.taskStore.getTask(taskId);\n if (!updatedTask) {\n throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);\n }\n task = updatedTask;\n }\n // Return the final result\n return (await extra.taskStore.getTaskResult(taskId));\n }\n setCompletionRequestHandler() {\n if (this._completionHandlerInitialized) {\n return;\n }\n this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema));\n this.server.registerCapabilities({\n completions: {}\n });\n this.server.setRequestHandler(CompleteRequestSchema, async (request) => {\n switch (request.params.ref.type) {\n case 'ref/prompt':\n assertCompleteRequestPrompt(request);\n return this.handlePromptCompletion(request, request.params.ref);\n case 'ref/resource':\n assertCompleteRequestResourceTemplate(request);\n return this.handleResourceCompletion(request, request.params.ref);\n default:\n throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);\n }\n });\n this._completionHandlerInitialized = true;\n }\n async handlePromptCompletion(request, ref) {\n const prompt = this._registeredPrompts[ref.name];\n if (!prompt) {\n throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`);\n }\n if (!prompt.enabled) {\n throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);\n }\n if (!prompt.argsSchema) {\n return EMPTY_COMPLETION_RESULT;\n }\n const promptShape = getObjectShape(prompt.argsSchema);\n const field = promptShape?.[request.params.argument.name];\n if (!isCompletable(field)) {\n return EMPTY_COMPLETION_RESULT;\n }\n const completer = getCompleter(field);\n if (!completer) {\n return EMPTY_COMPLETION_RESULT;\n }\n const suggestions = await completer(request.params.argument.value, request.params.context);\n return createCompletionResult(suggestions);\n }\n async handleResourceCompletion(request, ref) {\n const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri);\n if (!template) {\n if (this._registeredResources[ref.uri]) {\n // Attempting to autocomplete a fixed resource URI is not an error in the spec (but probably should be).\n return EMPTY_COMPLETION_RESULT;\n }\n throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);\n }\n const completer = template.resourceTemplate.completeCallback(request.params.argument.name);\n if (!completer) {\n return EMPTY_COMPLETION_RESULT;\n }\n const suggestions = await completer(request.params.argument.value, request.params.context);\n return createCompletionResult(suggestions);\n }\n setResourceRequestHandlers() {\n if (this._resourceHandlersInitialized) {\n return;\n }\n this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema));\n this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema));\n this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema));\n this.server.registerCapabilities({\n resources: {\n listChanged: true\n }\n });\n this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => {\n const resources = Object.entries(this._registeredResources)\n .filter(([_, resource]) => resource.enabled)\n .map(([uri, resource]) => ({\n uri,\n name: resource.name,\n ...resource.metadata\n }));\n const templateResources = [];\n for (const template of Object.values(this._registeredResourceTemplates)) {\n if (!template.resourceTemplate.listCallback) {\n continue;\n }\n const result = await template.resourceTemplate.listCallback(extra);\n for (const resource of result.resources) {\n templateResources.push({\n ...template.metadata,\n // the defined resource metadata should override the template metadata if present\n ...resource\n });\n }\n }\n return { resources: [...resources, ...templateResources] };\n });\n this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {\n const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({\n name,\n uriTemplate: template.resourceTemplate.uriTemplate.toString(),\n ...template.metadata\n }));\n return { resourceTemplates };\n });\n this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {\n const uri = new URL(request.params.uri);\n // First check for exact resource match\n const resource = this._registeredResources[uri.toString()];\n if (resource) {\n if (!resource.enabled) {\n throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`);\n }\n return resource.readCallback(uri, extra);\n }\n // Then check templates\n for (const template of Object.values(this._registeredResourceTemplates)) {\n const variables = template.resourceTemplate.uriTemplate.match(uri.toString());\n if (variables) {\n return template.readCallback(uri, variables, extra);\n }\n }\n throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`);\n });\n this._resourceHandlersInitialized = true;\n }\n setPromptRequestHandlers() {\n if (this._promptHandlersInitialized) {\n return;\n }\n this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema));\n this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema));\n this.server.registerCapabilities({\n prompts: {\n listChanged: true\n }\n });\n this.server.setRequestHandler(ListPromptsRequestSchema, () => ({\n prompts: Object.entries(this._registeredPrompts)\n .filter(([, prompt]) => prompt.enabled)\n .map(([name, prompt]) => {\n return {\n name,\n title: prompt.title,\n description: prompt.description,\n arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined\n };\n })\n }));\n this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => {\n const prompt = this._registeredPrompts[request.params.name];\n if (!prompt) {\n throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);\n }\n if (!prompt.enabled) {\n throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);\n }\n if (prompt.argsSchema) {\n const argsObj = normalizeObjectSchema(prompt.argsSchema);\n const parseResult = await safeParseAsync(argsObj, request.params.arguments);\n if (!parseResult.success) {\n const error = 'error' in parseResult ? parseResult.error : 'Unknown error';\n const errorMessage = getParseErrorMessage(error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`);\n }\n const args = parseResult.data;\n const cb = prompt.callback;\n return await Promise.resolve(cb(args, extra));\n }\n else {\n const cb = prompt.callback;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return await Promise.resolve(cb(extra));\n }\n });\n this._promptHandlersInitialized = true;\n }\n resource(name, uriOrTemplate, ...rest) {\n let metadata;\n if (typeof rest[0] === 'object') {\n metadata = rest.shift();\n }\n const readCallback = rest[0];\n if (typeof uriOrTemplate === 'string') {\n if (this._registeredResources[uriOrTemplate]) {\n throw new Error(`Resource ${uriOrTemplate} is already registered`);\n }\n const registeredResource = this._createRegisteredResource(name, undefined, uriOrTemplate, metadata, readCallback);\n this.setResourceRequestHandlers();\n this.sendResourceListChanged();\n return registeredResource;\n }\n else {\n if (this._registeredResourceTemplates[name]) {\n throw new Error(`Resource template ${name} is already registered`);\n }\n const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, undefined, uriOrTemplate, metadata, readCallback);\n this.setResourceRequestHandlers();\n this.sendResourceListChanged();\n return registeredResourceTemplate;\n }\n }\n registerResource(name, uriOrTemplate, config, readCallback) {\n if (typeof uriOrTemplate === 'string') {\n if (this._registeredResources[uriOrTemplate]) {\n throw new Error(`Resource ${uriOrTemplate} is already registered`);\n }\n const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback);\n this.setResourceRequestHandlers();\n this.sendResourceListChanged();\n return registeredResource;\n }\n else {\n if (this._registeredResourceTemplates[name]) {\n throw new Error(`Resource template ${name} is already registered`);\n }\n const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback);\n this.setResourceRequestHandlers();\n this.sendResourceListChanged();\n return registeredResourceTemplate;\n }\n }\n _createRegisteredResource(name, title, uri, metadata, readCallback) {\n const registeredResource = {\n name,\n title,\n metadata,\n readCallback,\n enabled: true,\n disable: () => registeredResource.update({ enabled: false }),\n enable: () => registeredResource.update({ enabled: true }),\n remove: () => registeredResource.update({ uri: null }),\n update: updates => {\n if (typeof updates.uri !== 'undefined' && updates.uri !== uri) {\n delete this._registeredResources[uri];\n if (updates.uri)\n this._registeredResources[updates.uri] = registeredResource;\n }\n if (typeof updates.name !== 'undefined')\n registeredResource.name = updates.name;\n if (typeof updates.title !== 'undefined')\n registeredResource.title = updates.title;\n if (typeof updates.metadata !== 'undefined')\n registeredResource.metadata = updates.metadata;\n if (typeof updates.callback !== 'undefined')\n registeredResource.readCallback = updates.callback;\n if (typeof updates.enabled !== 'undefined')\n registeredResource.enabled = updates.enabled;\n this.sendResourceListChanged();\n }\n };\n this._registeredResources[uri] = registeredResource;\n return registeredResource;\n }\n _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {\n const registeredResourceTemplate = {\n resourceTemplate: template,\n title,\n metadata,\n readCallback,\n enabled: true,\n disable: () => registeredResourceTemplate.update({ enabled: false }),\n enable: () => registeredResourceTemplate.update({ enabled: true }),\n remove: () => registeredResourceTemplate.update({ name: null }),\n update: updates => {\n if (typeof updates.name !== 'undefined' && updates.name !== name) {\n delete this._registeredResourceTemplates[name];\n if (updates.name)\n this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;\n }\n if (typeof updates.title !== 'undefined')\n registeredResourceTemplate.title = updates.title;\n if (typeof updates.template !== 'undefined')\n registeredResourceTemplate.resourceTemplate = updates.template;\n if (typeof updates.metadata !== 'undefined')\n registeredResourceTemplate.metadata = updates.metadata;\n if (typeof updates.callback !== 'undefined')\n registeredResourceTemplate.readCallback = updates.callback;\n if (typeof updates.enabled !== 'undefined')\n registeredResourceTemplate.enabled = updates.enabled;\n this.sendResourceListChanged();\n }\n };\n this._registeredResourceTemplates[name] = registeredResourceTemplate;\n // If the resource template has any completion callbacks, enable completions capability\n const variableNames = template.uriTemplate.variableNames;\n const hasCompleter = Array.isArray(variableNames) && variableNames.some(v => !!template.completeCallback(v));\n if (hasCompleter) {\n this.setCompletionRequestHandler();\n }\n return registeredResourceTemplate;\n }\n _createRegisteredPrompt(name, title, description, argsSchema, callback) {\n const registeredPrompt = {\n title,\n description,\n argsSchema: argsSchema === undefined ? undefined : objectFromShape(argsSchema),\n callback,\n enabled: true,\n disable: () => registeredPrompt.update({ enabled: false }),\n enable: () => registeredPrompt.update({ enabled: true }),\n remove: () => registeredPrompt.update({ name: null }),\n update: updates => {\n if (typeof updates.name !== 'undefined' && updates.name !== name) {\n delete this._registeredPrompts[name];\n if (updates.name)\n this._registeredPrompts[updates.name] = registeredPrompt;\n }\n if (typeof updates.title !== 'undefined')\n registeredPrompt.title = updates.title;\n if (typeof updates.description !== 'undefined')\n registeredPrompt.description = updates.description;\n if (typeof updates.argsSchema !== 'undefined')\n registeredPrompt.argsSchema = objectFromShape(updates.argsSchema);\n if (typeof updates.callback !== 'undefined')\n registeredPrompt.callback = updates.callback;\n if (typeof updates.enabled !== 'undefined')\n registeredPrompt.enabled = updates.enabled;\n this.sendPromptListChanged();\n }\n };\n this._registeredPrompts[name] = registeredPrompt;\n // If any argument uses a Completable schema, enable completions capability\n if (argsSchema) {\n const hasCompletable = Object.values(argsSchema).some(field => {\n const inner = field instanceof ZodOptional ? field._def?.innerType : field;\n return isCompletable(inner);\n });\n if (hasCompletable) {\n this.setCompletionRequestHandler();\n }\n }\n return registeredPrompt;\n }\n _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) {\n // Validate tool name according to SEP specification\n validateAndWarnToolName(name);\n const registeredTool = {\n title,\n description,\n inputSchema: getZodSchemaObject(inputSchema),\n outputSchema: getZodSchemaObject(outputSchema),\n annotations,\n execution,\n _meta,\n handler: handler,\n enabled: true,\n disable: () => registeredTool.update({ enabled: false }),\n enable: () => registeredTool.update({ enabled: true }),\n remove: () => registeredTool.update({ name: null }),\n update: updates => {\n if (typeof updates.name !== 'undefined' && updates.name !== name) {\n if (typeof updates.name === 'string') {\n validateAndWarnToolName(updates.name);\n }\n delete this._registeredTools[name];\n if (updates.name)\n this._registeredTools[updates.name] = registeredTool;\n }\n if (typeof updates.title !== 'undefined')\n registeredTool.title = updates.title;\n if (typeof updates.description !== 'undefined')\n registeredTool.description = updates.description;\n if (typeof updates.paramsSchema !== 'undefined')\n registeredTool.inputSchema = objectFromShape(updates.paramsSchema);\n if (typeof updates.outputSchema !== 'undefined')\n registeredTool.outputSchema = objectFromShape(updates.outputSchema);\n if (typeof updates.callback !== 'undefined')\n registeredTool.handler = updates.callback;\n if (typeof updates.annotations !== 'undefined')\n registeredTool.annotations = updates.annotations;\n if (typeof updates._meta !== 'undefined')\n registeredTool._meta = updates._meta;\n if (typeof updates.enabled !== 'undefined')\n registeredTool.enabled = updates.enabled;\n this.sendToolListChanged();\n }\n };\n this._registeredTools[name] = registeredTool;\n this.setToolRequestHandlers();\n this.sendToolListChanged();\n return registeredTool;\n }\n /**\n * tool() implementation. Parses arguments passed to overrides defined above.\n */\n tool(name, ...rest) {\n if (this._registeredTools[name]) {\n throw new Error(`Tool ${name} is already registered`);\n }\n let description;\n let inputSchema;\n let outputSchema;\n let annotations;\n // Tool properties are passed as separate arguments, with omissions allowed.\n // Support for this style is frozen as of protocol version 2025-03-26. Future additions\n // to tool definition should *NOT* be added.\n if (typeof rest[0] === 'string') {\n description = rest.shift();\n }\n // Handle the different overload combinations\n if (rest.length > 1) {\n // We have at least one more arg before the callback\n const firstArg = rest[0];\n if (isZodRawShapeCompat(firstArg)) {\n // We have a params schema as the first arg\n inputSchema = rest.shift();\n // Check if the next arg is potentially annotations\n if (rest.length > 1 && typeof rest[0] === 'object' && rest[0] !== null && !isZodRawShapeCompat(rest[0])) {\n // Case: tool(name, paramsSchema, annotations, cb)\n // Or: tool(name, description, paramsSchema, annotations, cb)\n annotations = rest.shift();\n }\n }\n else if (typeof firstArg === 'object' && firstArg !== null) {\n // Not a ZodRawShapeCompat, so must be annotations in this position\n // Case: tool(name, annotations, cb)\n // Or: tool(name, description, annotations, cb)\n annotations = rest.shift();\n }\n }\n const callback = rest[0];\n return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, undefined, callback);\n }\n /**\n * Registers a tool with a config object and callback.\n */\n registerTool(name, config, cb) {\n if (this._registeredTools[name]) {\n throw new Error(`Tool ${name} is already registered`);\n }\n const { title, description, inputSchema, outputSchema, annotations, _meta } = config;\n return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, _meta, cb);\n }\n prompt(name, ...rest) {\n if (this._registeredPrompts[name]) {\n throw new Error(`Prompt ${name} is already registered`);\n }\n let description;\n if (typeof rest[0] === 'string') {\n description = rest.shift();\n }\n let argsSchema;\n if (rest.length > 1) {\n argsSchema = rest.shift();\n }\n const cb = rest[0];\n const registeredPrompt = this._createRegisteredPrompt(name, undefined, description, argsSchema, cb);\n this.setPromptRequestHandlers();\n this.sendPromptListChanged();\n return registeredPrompt;\n }\n /**\n * Registers a prompt with a config object and callback.\n */\n registerPrompt(name, config, cb) {\n if (this._registeredPrompts[name]) {\n throw new Error(`Prompt ${name} is already registered`);\n }\n const { title, description, argsSchema } = config;\n const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb);\n this.setPromptRequestHandlers();\n this.sendPromptListChanged();\n return registeredPrompt;\n }\n /**\n * Checks if the server is connected to a transport.\n * @returns True if the server is connected\n */\n isConnected() {\n return this.server.transport !== undefined;\n }\n /**\n * Sends a logging message to the client, if connected.\n * Note: You only need to send the parameters object, not the entire JSON RPC message\n * @see LoggingMessageNotification\n * @param params\n * @param sessionId optional for stateless and backward compatibility\n */\n async sendLoggingMessage(params, sessionId) {\n return this.server.sendLoggingMessage(params, sessionId);\n }\n /**\n * Sends a resource list changed event to the client, if connected.\n */\n sendResourceListChanged() {\n if (this.isConnected()) {\n this.server.sendResourceListChanged();\n }\n }\n /**\n * Sends a tool list changed event to the client, if connected.\n */\n sendToolListChanged() {\n if (this.isConnected()) {\n this.server.sendToolListChanged();\n }\n }\n /**\n * Sends a prompt list changed event to the client, if connected.\n */\n sendPromptListChanged() {\n if (this.isConnected()) {\n this.server.sendPromptListChanged();\n }\n }\n}\n/**\n * A resource template combines a URI pattern with optional functionality to enumerate\n * all resources matching that pattern.\n */\nexport class ResourceTemplate {\n constructor(uriTemplate, _callbacks) {\n this._callbacks = _callbacks;\n this._uriTemplate = typeof uriTemplate === 'string' ? new UriTemplate(uriTemplate) : uriTemplate;\n }\n /**\n * Gets the URI template pattern.\n */\n get uriTemplate() {\n return this._uriTemplate;\n }\n /**\n * Gets the list callback, if one was provided.\n */\n get listCallback() {\n return this._callbacks.list;\n }\n /**\n * Gets the callback for completing a specific URI template variable, if one was provided.\n */\n completeCallback(variable) {\n return this._callbacks.complete?.[variable];\n }\n}\nconst EMPTY_OBJECT_JSON_SCHEMA = {\n type: 'object',\n properties: {}\n};\n/**\n * Checks if a value looks like a Zod schema by checking for parse/safeParse methods.\n */\nfunction isZodTypeLike(value) {\n return (value !== null &&\n typeof value === 'object' &&\n 'parse' in value &&\n typeof value.parse === 'function' &&\n 'safeParse' in value &&\n typeof value.safeParse === 'function');\n}\n/**\n * Checks if an object is a Zod schema instance (v3 or v4).\n *\n * Zod schemas have internal markers:\n * - v3: `_def` property\n * - v4: `_zod` property\n *\n * This includes transformed schemas like z.preprocess(), z.transform(), z.pipe().\n */\nfunction isZodSchemaInstance(obj) {\n return '_def' in obj || '_zod' in obj || isZodTypeLike(obj);\n}\n/**\n * Checks if an object is a \"raw shape\" - a plain object where values are Zod schemas.\n *\n * Raw shapes are used as shorthand: `{ name: z.string() }` instead of `z.object({ name: z.string() })`.\n *\n * IMPORTANT: This must NOT match actual Zod schema instances (like z.preprocess, z.pipe),\n * which have internal properties that could be mistaken for schema values.\n */\nfunction isZodRawShapeCompat(obj) {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n // If it's already a Zod schema instance, it's NOT a raw shape\n if (isZodSchemaInstance(obj)) {\n return false;\n }\n // Empty objects are valid raw shapes (tools with no parameters)\n if (Object.keys(obj).length === 0) {\n return true;\n }\n // A raw shape has at least one property that is a Zod schema\n return Object.values(obj).some(isZodTypeLike);\n}\n/**\n * Converts a provided Zod schema to a Zod object if it is a ZodRawShapeCompat,\n * otherwise returns the schema as is.\n */\nfunction getZodSchemaObject(schema) {\n if (!schema) {\n return undefined;\n }\n if (isZodRawShapeCompat(schema)) {\n return objectFromShape(schema);\n }\n return schema;\n}\nfunction promptArgumentsFromSchema(schema) {\n const shape = getObjectShape(schema);\n if (!shape)\n return [];\n return Object.entries(shape).map(([name, field]) => {\n // Get description - works for both v3 and v4\n const description = getSchemaDescription(field);\n // Check if optional - works for both v3 and v4\n const isOptional = isSchemaOptional(field);\n return {\n name,\n description,\n required: !isOptional\n };\n });\n}\nfunction getMethodValue(schema) {\n const shape = getObjectShape(schema);\n const methodSchema = shape?.method;\n if (!methodSchema) {\n throw new Error('Schema is missing a method literal');\n }\n // Extract literal value - works for both v3 and v4\n const value = getLiteralValue(methodSchema);\n if (typeof value === 'string') {\n return value;\n }\n throw new Error('Schema method literal must be a string');\n}\nfunction createCompletionResult(suggestions) {\n return {\n completion: {\n values: suggestions.slice(0, 100),\n total: suggestions.length,\n hasMore: suggestions.length > 100\n }\n };\n}\nconst EMPTY_COMPLETION_RESULT = {\n completion: {\n values: [],\n hasMore: false\n }\n};\n//# sourceMappingURL=mcp.js.map","import { isPlainObject, validateArgsWithSchema } from '@mcp-b/webmcp-polyfill';\nimport type { InputSchema } from '@mcp-b/webmcp-types';\n\ninterface JsonSchemaValidator {\n getValidator<T>(schema: unknown): (input: unknown) => JsonSchemaValidatorResult<T>;\n}\n\ntype JsonSchemaValidatorResult<T> =\n | { valid: true; data: T; errorMessage: undefined }\n | { valid: false; data: undefined; errorMessage: string };\n\nexport class PolyfillJsonSchemaValidator implements JsonSchemaValidator {\n getValidator<T>(schema: unknown): (input: unknown) => JsonSchemaValidatorResult<T> {\n return (input: unknown): JsonSchemaValidatorResult<T> => {\n if (!isPlainObject(input)) {\n return { valid: false, data: undefined, errorMessage: 'expected object arguments' };\n }\n\n const issue = validateArgsWithSchema(input, schema as InputSchema);\n if (issue) {\n return { valid: false, data: undefined, errorMessage: issue.message };\n }\n\n return { valid: true, data: input as T, errorMessage: undefined };\n };\n }\n}\n","import type {\n InputSchema,\n JsonObject,\n ModelContextClient,\n ModelContextCore,\n ModelContextExtensions,\n ModelContextOptions,\n ResourceContents,\n ToolDescriptor,\n ToolListItem,\n ToolResponse,\n} from '@mcp-b/webmcp-types';\nimport type { ServerOptions } from '@modelcontextprotocol/sdk/server/index.js';\nimport { McpServer as BaseMcpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport {\n getParseErrorMessage,\n normalizeObjectSchema,\n safeParseAsync,\n} from '@modelcontextprotocol/sdk/server/zod-compat.js';\nimport { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js';\nimport type { RequestOptions } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport { mergeCapabilities } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport type {\n CreateMessageRequest,\n CreateMessageResult,\n ElicitRequest,\n ElicitResult,\n Implementation,\n PromptMessage,\n} from '@modelcontextprotocol/sdk/types.js';\nimport {\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListToolsRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { PolyfillJsonSchemaValidator } from './polyfill-validator.js';\n\nconst DEFAULT_INPUT_SCHEMA: InputSchema = { type: 'object', properties: {} };\nconst DEFAULT_CLIENT_REQUEST_TIMEOUT = 10_000;\n\nexport const SERVER_MARKER_PROPERTY = '__isBrowserMcpServer' as const;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isCallToolResult(value: unknown): value is ToolResponse {\n return isPlainObject(value) && Array.isArray(value.content);\n}\n\nfunction isJsonPrimitive(value: unknown): value is string | number | boolean | null {\n return (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n );\n}\n\nfunction isJsonValue(value: unknown): boolean {\n if (isJsonPrimitive(value)) {\n return Number.isFinite(value as number) || typeof value !== 'number';\n }\n\n if (Array.isArray(value)) {\n return value.every((entry) => isJsonValue(entry));\n }\n\n if (!isPlainObject(value)) {\n return false;\n }\n\n return Object.values(value).every((entry) => isJsonValue(entry));\n}\n\nfunction toStructuredContent(value: unknown): JsonObject | undefined {\n if (!isPlainObject(value) || !isJsonValue(value)) {\n return undefined;\n }\n\n return value as JsonObject;\n}\n\nfunction serializeTextContent(value: unknown): string {\n if (typeof value === 'string') {\n return value;\n }\n\n try {\n const candidate = JSON.stringify(value);\n return candidate ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction normalizeToolResponse(value: unknown): ToolResponse {\n if (isCallToolResult(value)) {\n return value;\n }\n\n const structuredContent = toStructuredContent(value);\n\n return {\n content: [{ type: 'text', text: serializeTextContent(value) }],\n ...(structuredContent ? { structuredContent } : {}),\n isError: false,\n };\n}\n\nfunction withDefaultTimeout(options?: RequestOptions): RequestOptions {\n if (options?.signal) return options;\n return { ...options, signal: AbortSignal.timeout(DEFAULT_CLIENT_REQUEST_TIMEOUT) };\n}\n\ninterface ParentRegisteredTool {\n description?: string;\n inputSchema?: unknown;\n outputSchema?: unknown;\n annotations?: unknown;\n handler: (args: Record<string, unknown>, extra: unknown) => Promise<ToolResponse>;\n enabled: boolean;\n remove: () => void;\n}\n\ninterface ParentRegisteredResource {\n name: string;\n metadata?: { description?: string; mimeType?: string; title?: string };\n readCallback: (uri: URL, extra: unknown) => Promise<{ contents: ResourceContents[] }>;\n enabled: boolean;\n remove: () => void;\n}\n\ninterface ParentRegisteredPrompt {\n title?: string;\n description?: string;\n argsSchema?: unknown;\n callback: (\n args: Record<string, unknown>,\n extra: unknown\n ) => Promise<{ messages: PromptMessage[] }>;\n enabled: boolean;\n remove: () => void;\n}\n\nexport interface BrowserMcpServerOptions extends ServerOptions {\n native?: ModelContextCore;\n}\n\ntype ParentRegisterToolFn = (\n name: string,\n config: Record<string, unknown>,\n cb: (args: Record<string, unknown>, extra: unknown) => Promise<ToolResponse>\n) => void;\n\ntype ParentRegisterResourceFn = (\n name: string,\n uri: string,\n config: Record<string, unknown>,\n cb: (uri: URL, extra: unknown) => Promise<{ contents: ResourceContents[] }>\n) => { remove: () => void };\n\ntype ParentRegisterPromptFn = (\n name: string,\n config: Record<string, unknown>,\n cb: (args: Record<string, unknown>, extra: unknown) => Promise<{ messages: PromptMessage[] }>\n) => { remove: () => void };\n\ntype NativeToolsApi = ModelContextCore & Pick<ModelContextExtensions, 'listTools' | 'callTool'>;\n\n/**\n * Browser-optimized MCP Server that speaks WebMCP natively.\n *\n * This server IS navigator.modelContext — it implements the WebMCP standard API\n * (provideContext, registerTool, unregisterTool, clearContext) while retaining\n * full MCP protocol capabilities (resources, prompts, elicitation, sampling)\n * via the inherited BaseMcpServer surface.\n *\n * When `native` is provided, all tool operations are mirrored to it so that\n * navigator.modelContextTesting (polyfill testing shim) stays in sync.\n */\nexport class BrowserMcpServer extends BaseMcpServer {\n readonly [SERVER_MARKER_PROPERTY] = true as const;\n\n private native: ModelContextCore | undefined;\n private _promptSchemas = new Map<string, InputSchema>();\n private _jsonValidator: PolyfillJsonSchemaValidator;\n private _publicMethodsBound = false;\n\n constructor(serverInfo: Implementation, options?: BrowserMcpServerOptions) {\n const validator = new PolyfillJsonSchemaValidator();\n const enhancedOptions: ServerOptions = {\n capabilities: mergeCapabilities(options?.capabilities || {}, {\n tools: { listChanged: true },\n resources: { listChanged: true },\n prompts: { listChanged: true },\n }),\n jsonSchemaValidator: options?.jsonSchemaValidator ?? validator,\n };\n\n super(serverInfo, enhancedOptions);\n this._jsonValidator = validator;\n this.native = options?.native;\n this.bindPublicApiMethods();\n }\n\n /**\n * navigator.modelContext consumers may destructure methods (e.g. const { registerTool } = ...).\n * Bind methods once so they remain callable outside instance-method invocation syntax.\n */\n private bindPublicApiMethods(): void {\n if (this._publicMethodsBound) {\n return;\n }\n\n this.registerTool = this.registerTool.bind(this);\n this.unregisterTool = this.unregisterTool.bind(this);\n this.provideContext = this.provideContext.bind(this);\n this.clearContext = this.clearContext.bind(this);\n this.listTools = this.listTools.bind(this);\n this.callTool = this.callTool.bind(this);\n this.executeTool = this.executeTool.bind(this);\n\n this.registerResource = this.registerResource.bind(this);\n this.listResources = this.listResources.bind(this);\n this.readResource = this.readResource.bind(this);\n\n this.registerPrompt = this.registerPrompt.bind(this);\n this.listPrompts = this.listPrompts.bind(this);\n this.getPrompt = this.getPrompt.bind(this);\n\n this.createMessage = this.createMessage.bind(this);\n this.elicitInput = this.elicitInput.bind(this);\n\n this._publicMethodsBound = true;\n }\n\n private get _parentTools(): Record<string, ParentRegisteredTool> {\n return (this as unknown as { _registeredTools: Record<string, ParentRegisteredTool> })\n ._registeredTools;\n }\n\n private get _parentResources(): Record<string, ParentRegisteredResource> {\n return (this as unknown as { _registeredResources: Record<string, ParentRegisteredResource> })\n ._registeredResources;\n }\n\n private get _parentPrompts(): Record<string, ParentRegisteredPrompt> {\n return (this as unknown as { _registeredPrompts: Record<string, ParentRegisteredPrompt> })\n ._registeredPrompts;\n }\n\n /**\n * Converts a schema (Zod or plain JSON Schema) to a transport-ready JSON Schema.\n * When `requireObjectType` is true (the default, for inputSchema), empty `{}` schemas\n * are normalized to `{ type: \"object\", properties: {} }` and schemas missing a root\n * `type` get `type: \"object\"` prepended — per MCP spec requirements.\n * When false (for outputSchema), no object-type normalization is applied.\n */\n private toTransportSchema(schema: unknown, requireObjectType = true): InputSchema {\n if (!schema || typeof schema !== 'object') {\n if (requireObjectType) {\n console.warn(\n `[BrowserMcpServer] toTransportSchema received non-object schema (${typeof schema}), using default`\n );\n return DEFAULT_INPUT_SCHEMA;\n }\n return {} as InputSchema;\n }\n\n const normalized = normalizeObjectSchema(schema as Parameters<typeof normalizeObjectSchema>[0]);\n const jsonSchema = normalized\n ? (toJsonSchemaCompat(normalized, {\n strictUnions: true,\n pipeStrategy: 'input',\n }) as unknown as Record<string, unknown>)\n : (schema as Record<string, unknown>);\n\n if (Object.keys(jsonSchema).length === 0) {\n if (requireObjectType) {\n return DEFAULT_INPUT_SCHEMA;\n }\n return jsonSchema as InputSchema;\n }\n\n if (requireObjectType && jsonSchema.type === undefined) {\n return { type: 'object', ...jsonSchema } as InputSchema;\n }\n\n return jsonSchema as InputSchema;\n }\n\n private isZodSchema(schema: unknown): boolean {\n if (!schema || typeof schema !== 'object') return false;\n const s = schema as Record<string, unknown>;\n return '_zod' in s || '_def' in s;\n }\n\n private getNativeToolsApi(): NativeToolsApi | undefined {\n if (!this.native) {\n return undefined;\n }\n\n const candidate = this.native as ModelContextCore &\n Partial<Pick<ModelContextExtensions, 'listTools' | 'callTool'>>;\n if (typeof candidate.listTools !== 'function' || typeof candidate.callTool !== 'function') {\n return undefined;\n }\n\n return candidate as NativeToolsApi;\n }\n\n private registerToolInServer(tool: ToolDescriptor): { unregister: () => void } {\n const inputSchema = this.toTransportSchema(tool.inputSchema);\n\n // Cast needed: parent expects Zod-compatible schemas, we pass JSON Schema objects.\n (super.registerTool as unknown as ParentRegisterToolFn)(\n tool.name,\n {\n description: tool.description,\n inputSchema,\n ...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),\n ...(tool.annotations ? { annotations: tool.annotations } : {}),\n },\n async (args: Record<string, unknown>) => {\n const client: ModelContextClient = {\n requestUserInteraction: async (cb: () => Promise<unknown>) => cb(),\n };\n return normalizeToolResponse(await tool.execute(args, client));\n }\n );\n return {\n unregister: () => this.unregisterTool(tool.name),\n };\n }\n\n backfillTools(\n tools: readonly ToolListItem[],\n execute: (name: string, args: Record<string, unknown>) => Promise<ToolResponse>\n ): number {\n let synced = 0;\n\n for (const sourceTool of tools) {\n if (!sourceTool?.name || this._parentTools[sourceTool.name]) {\n continue;\n }\n\n const toolDescriptor: ToolDescriptor = {\n name: sourceTool.name,\n description: sourceTool.description ?? '',\n inputSchema: sourceTool.inputSchema ?? DEFAULT_INPUT_SCHEMA,\n execute: async (args: Record<string, unknown>) => execute(sourceTool.name, args),\n };\n\n if (sourceTool.outputSchema) {\n toolDescriptor.outputSchema = sourceTool.outputSchema;\n }\n if (sourceTool.annotations) {\n toolDescriptor.annotations = sourceTool.annotations;\n }\n\n this.registerToolInServer(toolDescriptor);\n synced++;\n }\n\n return synced;\n }\n\n // --- WebMCP standard API (primary surface) ---\n\n // @ts-expect-error -- WebMCP API: (ToolDescriptor) vs MCP SDK: (name, config, cb)\n override registerTool(tool: ToolDescriptor): { unregister: () => void } {\n // Mirror to native first — the polyfill validates the descriptor\n if (this.native) {\n (this.native.registerTool as (tool: ToolDescriptor) => void)(tool);\n }\n\n try {\n return this.registerToolInServer(tool);\n } catch (error) {\n // Rollback native registration on server failure\n if (this.native) {\n try {\n this.native.unregisterTool(tool.name);\n } catch (rollbackError) {\n console.error(\n '[BrowserMcpServer] Rollback of native tool registration failed:',\n rollbackError\n );\n }\n }\n throw error;\n }\n }\n\n /**\n * Backfill tools that were already registered on the native/polyfill context\n * before this BrowserMcpServer wrapper was installed.\n */\n syncNativeTools(): number {\n const nativeToolsApi = this.getNativeToolsApi();\n if (!nativeToolsApi) {\n return 0;\n }\n\n const nativeCallTool = nativeToolsApi.callTool.bind(nativeToolsApi);\n return this.backfillTools(\n nativeToolsApi.listTools(),\n async (name: string, args: Record<string, unknown>) =>\n nativeCallTool({\n name,\n arguments: args,\n })\n );\n }\n\n unregisterTool(name: string): void {\n this._parentTools[name]?.remove();\n\n if (this.native) {\n this.native.unregisterTool(name);\n }\n }\n\n // @ts-expect-error -- WebMCP API: (descriptor) vs MCP SDK: (name, uri, config, readCallback)\n override registerResource(descriptor: {\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n read: (uri: URL, params?: Record<string, string>) => Promise<{ contents: ResourceContents[] }>;\n }): { unregister: () => void } {\n const registered = (super.registerResource as unknown as ParentRegisterResourceFn)(\n descriptor.name,\n descriptor.uri,\n {\n ...(descriptor.description !== undefined && { description: descriptor.description }),\n ...(descriptor.mimeType !== undefined && { mimeType: descriptor.mimeType }),\n },\n async (uri: URL) => ({\n contents: (await descriptor.read(uri)).contents,\n })\n );\n\n return {\n unregister: () => registered.remove(),\n };\n }\n\n // @ts-expect-error -- WebMCP API: (descriptor) vs MCP SDK: (name, config, cb)\n override registerPrompt(descriptor: {\n name: string;\n description?: string;\n argsSchema?: InputSchema;\n get: (args: Record<string, unknown>) => Promise<{ messages: PromptMessage[] }>;\n }): { unregister: () => void } {\n // Store argsSchema locally — the parent SDK's _createRegisteredPrompt corrupts\n // plain JSON Schema objects via objectFromShape() which expects Zod schemas.\n if (descriptor.argsSchema) {\n this._promptSchemas.set(descriptor.name, descriptor.argsSchema);\n }\n\n const registered = (super.registerPrompt as unknown as ParentRegisterPromptFn)(\n descriptor.name,\n {\n ...(descriptor.description !== undefined && { description: descriptor.description }),\n // Do NOT pass argsSchema to parent — it gets corrupted by Zod's objectFromShape\n },\n async (args: Record<string, unknown>) => ({\n messages: (await descriptor.get(args)).messages,\n })\n );\n\n return {\n unregister: () => {\n this._promptSchemas.delete(descriptor.name);\n registered.remove();\n },\n };\n }\n\n provideContext(options?: ModelContextOptions): void {\n for (const tool of Object.values(this._parentTools)) {\n tool.remove();\n }\n\n if (this.native) {\n this.native.clearContext();\n }\n\n for (const tool of options?.tools ?? []) {\n this.registerTool(tool);\n }\n }\n\n clearContext(): void {\n for (const tool of Object.values(this._parentTools)) {\n tool.remove();\n }\n // Note: _promptSchemas is NOT cleared here. clearContext() is a WebMCP standard\n // method that only handles tools. Prompt schemas are cleaned up individually\n // via the unregister() callback returned by registerPrompt().\n\n if (this.native) {\n this.native.clearContext();\n }\n }\n\n // --- Extension methods ---\n\n listResources(): Array<{\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n }> {\n return Object.entries(this._parentResources)\n .filter(([, resource]) => resource.enabled)\n .map(([uri, resource]) => ({\n uri,\n name: resource.name,\n ...resource.metadata,\n }));\n }\n\n async readResource(uri: string): Promise<{ contents: ResourceContents[] }> {\n const resource = this._parentResources[uri];\n if (!resource) {\n throw new Error(`Resource not found: ${uri}`);\n }\n\n return resource.readCallback(new URL(uri), {});\n }\n\n listPrompts(): Array<{\n name: string;\n description?: string;\n arguments?: Array<{ name: string; description?: string; required?: boolean }>;\n }> {\n return Object.entries(this._parentPrompts)\n .filter(([, prompt]) => prompt.enabled)\n .map(([name, prompt]) => {\n const schema = this._promptSchemas.get(name);\n return {\n name,\n ...(prompt.description !== undefined && { description: prompt.description }),\n ...(schema?.properties\n ? {\n arguments: Object.entries(schema.properties).map(([argName, prop]) => ({\n name: argName,\n ...(typeof prop === 'object' && prop !== null && 'description' in prop\n ? { description: (prop as { description: string }).description }\n : {}),\n ...(schema.required?.includes(argName) ? { required: true } : {}),\n })),\n }\n : {}),\n };\n });\n }\n\n async getPrompt(\n name: string,\n args: Record<string, unknown> = {}\n ): Promise<{ messages: PromptMessage[] }> {\n const prompt = this._parentPrompts[name];\n if (!prompt) {\n throw new Error(`Prompt not found: ${name}`);\n }\n\n const schema = this._promptSchemas.get(name);\n if (schema) {\n const validator = this._jsonValidator.getValidator(schema);\n const result = validator(args);\n if (!result.valid) {\n throw new Error(`Invalid arguments for prompt ${name}: ${result.errorMessage}`);\n }\n }\n\n return prompt.callback(args, {});\n }\n\n listTools(): ToolListItem[] {\n return Object.entries(this._parentTools)\n .filter(([, tool]) => tool.enabled)\n .map(([name, tool]) => {\n const item: ToolListItem = {\n name,\n description: tool.description ?? '',\n inputSchema: this.toTransportSchema(tool.inputSchema ?? DEFAULT_INPUT_SCHEMA),\n };\n if (tool.outputSchema) item.outputSchema = this.toTransportSchema(tool.outputSchema, false);\n if (tool.annotations)\n item.annotations = tool.annotations as NonNullable<ToolListItem['annotations']>;\n return item;\n });\n }\n\n /**\n * Override SDK's validateToolInput to handle both Zod schemas and plain JSON Schema.\n * Zod schemas use the SDK's safeParseAsync; plain JSON Schema uses PolyfillJsonSchemaValidator.\n */\n override async validateToolInput(\n tool: { inputSchema?: unknown },\n args: Record<string, unknown> | undefined,\n toolName: string\n ): Promise<Record<string, unknown> | undefined> {\n if (!tool.inputSchema) return undefined;\n\n // Zod schemas → use SDK's safeParseAsync\n if (this.isZodSchema(tool.inputSchema)) {\n const result = await safeParseAsync(\n tool.inputSchema as Parameters<typeof safeParseAsync>[0],\n args ?? {}\n );\n if (!result.success) {\n throw new Error(\n `Invalid arguments for tool ${toolName}: ${getParseErrorMessage(result.error)}`\n );\n }\n return result.data as Record<string, unknown>;\n }\n\n // Plain JSON Schema → use PolyfillJsonSchemaValidator\n const validator = this._jsonValidator.getValidator(tool.inputSchema);\n const result = validator(args ?? {});\n if (!result.valid) {\n throw new Error(`Invalid arguments for tool ${toolName}: ${result.errorMessage}`);\n }\n return result.data as Record<string, unknown>;\n }\n\n /**\n * Override SDK's validateToolOutput to handle both Zod schemas and plain JSON Schema.\n */\n override async validateToolOutput(\n tool: { outputSchema?: unknown },\n result: unknown,\n toolName: string\n ): Promise<void> {\n if (!tool.outputSchema) return;\n\n const r = result as Record<string, unknown>;\n if (!('content' in r) || r.isError || !r.structuredContent) return;\n\n // Zod schemas → use SDK's safeParseAsync\n if (this.isZodSchema(tool.outputSchema)) {\n const parseResult = await safeParseAsync(\n tool.outputSchema as Parameters<typeof safeParseAsync>[0],\n r.structuredContent\n );\n if (!parseResult.success) {\n throw new Error(\n `Output validation error: Invalid structured content for tool ${toolName}: ${getParseErrorMessage(parseResult.error)}`\n );\n }\n return;\n }\n\n // Plain JSON Schema → use PolyfillJsonSchemaValidator\n const validator = this._jsonValidator.getValidator(tool.outputSchema);\n const validationResult = validator(r.structuredContent);\n if (!validationResult.valid) {\n throw new Error(\n `Output validation error: Invalid structured content for tool ${toolName}: ${validationResult.errorMessage}`\n );\n }\n }\n\n async callTool(params: {\n name: string;\n arguments?: Record<string, unknown>;\n }): Promise<ToolResponse> {\n const tool = this._parentTools[params.name];\n if (!tool) {\n throw new Error(`Tool not found: ${params.name}`);\n }\n\n return tool.handler(params.arguments ?? {}, {});\n }\n\n async executeTool(name: string, args: Record<string, unknown> = {}): Promise<ToolResponse> {\n return this.callTool({ name, arguments: args });\n }\n\n /**\n * Override connect to initialize request handlers BEFORE the transport connection.\n * This prevents \"Cannot register capabilities after connecting to transport\" errors\n * when tools are registered dynamically after connection.\n *\n * After the parent sets up its Zod-based handlers, we replace the ones that break\n * with plain JSON Schema objects (ListTools, ListPrompts, GetPrompt).\n */\n override async connect(transport: Transport): Promise<void> {\n // Let parent set up its handlers (including CallTool which uses our validateToolInput override)\n (this as unknown as { setToolRequestHandlers: () => void }).setToolRequestHandlers();\n (this as unknown as { setResourceRequestHandlers: () => void }).setResourceRequestHandlers();\n (this as unknown as { setPromptRequestHandlers: () => void }).setPromptRequestHandlers();\n\n // Replace ListTools handler — parent tries toJsonSchemaCompat (Zod → JSON Schema) on\n // inputSchema, but ours are already JSON Schema, so it falls back to empty {}.\n this.server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: this.listTools(),\n }));\n\n // Replace ListPrompts handler — parent calls promptArgumentsFromSchema which expects\n // Zod shapes. We use _promptSchemas which has the real JSON Schema.\n this.server.setRequestHandler(ListPromptsRequestSchema, () => ({\n prompts: this.listPrompts(),\n }));\n\n // Replace GetPrompt handler — parent calls safeParseAsync on argsSchema.\n // We validate with PolyfillJsonSchemaValidator instead.\n this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {\n const prompt = this._parentPrompts[request.params.name];\n if (!prompt) {\n throw new Error(`Prompt ${request.params.name} not found`);\n }\n if (!prompt.enabled) {\n throw new Error(`Prompt ${request.params.name} disabled`);\n }\n\n const schema = this._promptSchemas.get(request.params.name);\n if (schema) {\n const validator = this._jsonValidator.getValidator(schema);\n const result = validator(request.params.arguments ?? {});\n if (!result.valid) {\n throw new Error(\n `Invalid arguments for prompt ${request.params.name}: ${result.errorMessage}`\n );\n }\n return prompt.callback(request.params.arguments as Record<string, unknown>, {});\n }\n\n return prompt.callback({}, {});\n });\n\n return super.connect(transport);\n }\n\n // --- Sampling & Elicitation (delegated to Server) ---\n\n async createMessage(\n params: CreateMessageRequest['params'],\n options?: RequestOptions\n ): Promise<CreateMessageResult> {\n return this.server.createMessage(params, withDefaultTimeout(options));\n }\n\n async elicitInput(\n params: ElicitRequest['params'],\n options?: RequestOptions\n ): Promise<ElicitResult> {\n return this.server.elicitInput(params, withDefaultTimeout(options));\n }\n}\n\n// --- Exported descriptor types for consumers ---\n\nexport interface ResourceDescriptor {\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n read: (uri: URL, params?: Record<string, string>) => Promise<{ contents: ResourceContents[] }>;\n}\n\nexport interface PromptDescriptor {\n name: string;\n description?: string;\n argsSchema?: InputSchema;\n get: (args: Record<string, unknown>) => Promise<{ messages: PromptMessage[] }>;\n}\n","/**\n * No-op JSON Schema validator for browser environments.\n *\n * This validator bypasses the MCP SDK's internal ajv-based validation which causes\n * \"Error compiling schema\" errors in browser extensions due to ajv's use of\n * eval/Function constructor.\n *\n * Validation is handled externally by Zod in @mcp-b/global, making the SDK's\n * internal validation redundant. This no-op validator allows the SDK to function\n * without the ajv dependency issues.\n */\n\n/**\n * Interface for JSON Schema validators.\n * This matches the MCP SDK's jsonSchemaValidator interface.\n */\ninterface JsonSchemaValidator {\n getValidator<T>(schema: unknown): (input: unknown) => JsonSchemaValidatorResult<T>;\n}\n\n/**\n * Result type for JSON Schema validation\n */\ntype JsonSchemaValidatorResult<T> =\n | { valid: true; data: T; errorMessage: undefined }\n | { valid: false; data: undefined; errorMessage: string };\n\n/**\n * A no-op JSON Schema validator that always returns valid.\n *\n * Use this in browser environments where:\n * - ajv causes \"Error compiling schema\" errors\n * - Validation is already handled elsewhere (e.g., by Zod)\n * - You need to avoid eval/Function constructor restrictions\n *\n * @example\n * ```typescript\n * import { BrowserMcpServer } from '@mcp-b/webmcp-ts-sdk';\n * import { NoOpJsonSchemaValidator } from '@mcp-b/webmcp-ts-sdk/no-op-validator';\n *\n * const server = new BrowserMcpServer(\n * { name: 'my-server', version: '1.0.0' },\n * { jsonSchemaValidator: new NoOpJsonSchemaValidator() }\n * );\n * ```\n */\nexport class NoOpJsonSchemaValidator implements JsonSchemaValidator {\n /**\n * Returns a validator function that always passes.\n * The input data is passed through unchanged.\n *\n * @param _schema - The JSON Schema (ignored)\n * @returns A validator function that always returns valid\n */\n getValidator<T>(_schema: unknown): (input: unknown) => JsonSchemaValidatorResult<T> {\n return (input: unknown): JsonSchemaValidatorResult<T> => ({\n valid: true,\n data: input as T,\n errorMessage: undefined,\n });\n }\n}\n"],"x_google_ignoreList":[0,1,2,3,4,7,8,9,10,11,12,13,14,15,16,17],"mappings":";;;;;;;;AAOA,SAAgB,WAAW,GAAG;AAG1B,QAAO,CAAC,CADO,EACC;;AAGpB,SAAgB,gBAAgB,OAAO;CACnC,MAAM,SAAS,OAAO,OAAO,MAAM;AACnC,KAAI,OAAO,WAAW,EAClB,QAAO,OAAO,OAAO,EAAE,CAAC;CAC5B,MAAM,QAAQ,OAAO,MAAM,WAAW;CACtC,MAAM,QAAQ,OAAO,OAAM,MAAK,CAAC,WAAW,EAAE,CAAC;AAC/C,KAAI,MACA,QAAO,OAAO,OAAO,MAAM;AAC/B,KAAI,MACA,QAAO,KAAK,OAAO,MAAM;AAC7B,OAAM,IAAI,MAAM,+CAA+C;;AAGnE,SAAgB,UAAU,QAAQ,MAAM;AACpC,KAAI,WAAW,OAAO,CAGlB,QADe,OAAO,UAAU,QAAQ,KAAK;AAKjD,QAFiB,OACO,UAAU,KAAK;;AAG3C,eAAsB,eAAe,QAAQ,MAAM;AAC/C,KAAI,WAAW,OAAO,CAGlB,QADe,MAAM,OAAO,eAAe,QAAQ,KAAK;AAK5D,QADe,MADE,OACa,eAAe,KAAK;;AAItD,SAAgB,eAAe,QAAQ;AACnC,KAAI,CAAC,OACD,QAAO;CAEX,IAAI;AACJ,KAAI,WAAW,OAAO,CAElB,YADiB,OACG,MAAM,KAAK;KAI/B,YADiB,OACG;AAExB,KAAI,CAAC,S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AAC3D,OAAI,QAAQ;IAEV,MAAM,SADY,KAAK,eAAe,aAAa,OAAO,CACjC,QAAQ,OAAO,aAAa,EAAE,CAAC;AACxD,QAAI,CAAC,OAAO,MACV,OAAM,IAAI,MACR,gCAAgC,QAAQ,OAAO,KAAK,IAAI,OAAO,eAChE;AAEH,WAAO,OAAO,SAAS,QAAQ,OAAO,WAAsC,EAAE,CAAC;;AAGjF,UAAO,OAAO,SAAS,EAAE,EAAE,EAAE,CAAC;IAC9B;AAEF,SAAO,MAAM,QAAQ,UAAU;;CAKjC,MAAM,cACJ,QACA,SAC8B;AAC9B,SAAO,KAAK,OAAO,cAAc,QAAQ,mBAAmB,QAAQ,CAAC;;CAGvE,MAAM,YACJ,QACA,SACuB;AACvB,SAAO,KAAK,OAAO,YAAY,QAAQ,mBAAmB,QAAQ,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;ACpsBvE,IAAa,0BAAb,MAAoE;;;;;;;;CAQlE,aAAgB,SAAoE;AAClF,UAAQ,WAAkD;GACxD,OAAO;GACP,MAAM;GACN,cAAc;GACf"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["def","task","jsonrpcNotification","isPlainObject","Ajv","_addFormats","DEFAULT_INPUT_SCHEMA: InputSchema","isPlainObject","BaseMcpServer","enhancedOptions: ServerOptions","toolDescriptor: ToolDescriptor","item: ToolListItem","result"],"sources":["../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js","../src/stubs/ajv.ts","../src/stubs/ajv-formats.ts","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/server/completable.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/toolNameValidation.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/mcp-server.js","../../../node_modules/.pnpm/@modelcontextprotocol+sdk@1.26.0_@cfworker+json-schema@4.1.1_zod@4.3.5/node_modules/@modelcontextprotocol/sdk/dist/esm/server/mcp.js","../src/polyfill-validator.ts","../src/browser-server.ts","../src/no-op-validator.ts"],"sourcesContent":["// zod-compat.ts\n// ----------------------------------------------------\n// Unified types + helpers to accept Zod v3 and v4 (Mini)\n// ----------------------------------------------------\nimport * as z3rt from 'zod/v3';\nimport * as z4mini from 'zod/v4-mini';\n// --- Runtime detection ---\nexport function isZ4Schema(s) {\n // Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3\n const schema = s;\n return !!schema._zod;\n}\n// --- Schema construction ---\nexport function objectFromShape(shape) {\n const values = Object.values(shape);\n if (values.length === 0)\n return z4mini.object({}); // default to v4 Mini\n const allV4 = values.every(isZ4Schema);\n const allV3 = values.every(s => !isZ4Schema(s));\n if (allV4)\n return z4mini.object(shape);\n if (allV3)\n return z3rt.object(shape);\n throw new Error('Mixed Zod versions detected in object shape.');\n}\n// --- Unified parsing ---\nexport function safeParse(schema, data) {\n if (isZ4Schema(schema)) {\n // Mini exposes top-level safeParse\n const result = z4mini.safeParse(schema, data);\n return result;\n }\n const v3Schema = schema;\n const result = v3Schema.safeParse(data);\n return result;\n}\nexport async function safeParseAsync(schema, data) {\n if (isZ4Schema(schema)) {\n // Mini exposes top-level safeParseAsync\n const result = await z4mini.safeParseAsync(schema, data);\n return result;\n }\n const v3Schema = schema;\n const result = await v3Schema.safeParseAsync(data);\n return result;\n}\n// --- Shape extraction ---\nexport function getObjectShape(schema) {\n if (!schema)\n return undefined;\n // Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape`\n let rawShape;\n if (isZ4Schema(schema)) {\n const v4Schema = schema;\n rawShape = v4Schema._zod?.def?.shape;\n }\n else {\n const v3Schema = schema;\n rawShape = v3Schema.shape;\n }\n if (!rawShape)\n return undefined;\n if (typeof rawShape === 'function') {\n try {\n return rawShape();\n }\n catch {\n return undefined;\n }\n }\n return rawShape;\n}\n// --- Schema normalization ---\n/**\n * Normalizes a schema to an object schema. Handles both:\n * - Already-constructed object schemas (v3 or v4)\n * - Raw shapes that need to be wrapped into object schemas\n */\nexport function normalizeObjectSchema(schema) {\n if (!schema)\n return undefined;\n // First check if it's a raw shape (Record<string, AnySchema>)\n // Raw shapes don't have _def or _zod properties and aren't schemas themselves\n if (typeof schema === 'object') {\n // Check if it's actually a ZodRawShapeCompat (not a schema instance)\n // by checking if it lacks schema-like internal properties\n const asV3 = schema;\n const asV4 = schema;\n // If it's not a schema instance (no _def or _zod), it might be a raw shape\n if (!asV3._def && !asV4._zod) {\n // Check if all values are schemas (heuristic to confirm it's a raw shape)\n const values = Object.values(schema);\n if (values.length > 0 &&\n values.every(v => typeof v === 'object' &&\n v !== null &&\n (v._def !== undefined ||\n v._zod !== undefined ||\n typeof v.parse === 'function'))) {\n return objectFromShape(schema);\n }\n }\n }\n // If we get here, it should be an AnySchema (not a raw shape)\n // Check if it's already an object schema\n if (isZ4Schema(schema)) {\n // Check if it's a v4 object\n const v4Schema = schema;\n const def = v4Schema._zod?.def;\n if (def && (def.type === 'object' || def.shape !== undefined)) {\n return schema;\n }\n }\n else {\n // Check if it's a v3 object\n const v3Schema = schema;\n if (v3Schema.shape !== undefined) {\n return schema;\n }\n }\n return undefined;\n}\n// --- Error message extraction ---\n/**\n * Safely extracts an error message from a parse result error.\n * Zod errors can have different structures, so we handle various cases.\n */\nexport function getParseErrorMessage(error) {\n if (error && typeof error === 'object') {\n // Try common error structures\n if ('message' in error && typeof error.message === 'string') {\n return error.message;\n }\n if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) {\n const firstIssue = error.issues[0];\n if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) {\n return String(firstIssue.message);\n }\n }\n // Fallback: try to stringify the error\n try {\n return JSON.stringify(error);\n }\n catch {\n return String(error);\n }\n }\n return String(error);\n}\n// --- Schema metadata access ---\n/**\n * Gets the description from a schema, if available.\n * Works with both Zod v3 and v4.\n *\n * Both versions expose a `.description` getter that returns the description\n * from their respective internal storage (v3: _def, v4: globalRegistry).\n */\nexport function getSchemaDescription(schema) {\n return schema.description;\n}\n/**\n * Checks if a schema is optional.\n * Works with both Zod v3 and v4.\n */\nexport function isSchemaOptional(schema) {\n if (isZ4Schema(schema)) {\n const v4Schema = schema;\n return v4Schema._zod?.def?.type === 'optional';\n }\n const v3Schema = schema;\n // v3 has isOptional() method\n if (typeof schema.isOptional === 'function') {\n return schema.isOptional();\n }\n return v3Schema._def?.typeName === 'ZodOptional';\n}\n/**\n * Gets the literal value from a schema, if it's a literal schema.\n * Works with both Zod v3 and v4.\n * Returns undefined if the schema is not a literal or the value cannot be determined.\n */\nexport function getLiteralValue(schema) {\n if (isZ4Schema(schema)) {\n const v4Schema = schema;\n const def = v4Schema._zod?.def;\n if (def) {\n // Try various ways to get the literal value\n if (def.value !== undefined)\n return def.value;\n if (Array.isArray(def.values) && def.values.length > 0) {\n return def.values[0];\n }\n }\n }\n const v3Schema = schema;\n const def = v3Schema._def;\n if (def) {\n if (def.value !== undefined)\n return def.value;\n if (Array.isArray(def.values) && def.values.length > 0) {\n return def.values[0];\n }\n }\n // Fallback: check for direct value property (some Zod versions)\n const directValue = schema.value;\n if (directValue !== undefined)\n return directValue;\n return undefined;\n}\n//# sourceMappingURL=zod-compat.js.map","import * as z from 'zod/v4';\nexport const LATEST_PROTOCOL_VERSION = '2025-11-25';\nexport const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26';\nexport const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07'];\nexport const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task';\n/* JSON-RPC types */\nexport const JSONRPC_VERSION = '2.0';\n/**\n * Assert 'object' type schema.\n *\n * @internal\n */\nconst AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function'));\n/**\n * A progress token, used to associate progress notifications with the original request.\n */\nexport const ProgressTokenSchema = z.union([z.string(), z.number().int()]);\n/**\n * An opaque token used to represent a cursor for pagination.\n */\nexport const CursorSchema = z.string();\n/**\n * Task creation parameters, used to ask that the server create a task to represent a request.\n */\nexport const TaskCreationParamsSchema = z.looseObject({\n /**\n * Time in milliseconds to keep task results available after completion.\n * If null, the task has unlimited lifetime until manually cleaned up.\n */\n ttl: z.union([z.number(), z.null()]).optional(),\n /**\n * Time in milliseconds to wait between task status requests.\n */\n pollInterval: z.number().optional()\n});\nexport const TaskMetadataSchema = z.object({\n ttl: z.number().optional()\n});\n/**\n * Metadata for associating messages with a task.\n * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.\n */\nexport const RelatedTaskMetadataSchema = z.object({\n taskId: z.string()\n});\nconst RequestMetaSchema = z.looseObject({\n /**\n * 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.\n */\n progressToken: ProgressTokenSchema.optional(),\n /**\n * If specified, this request is related to the provided task.\n */\n [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()\n});\n/**\n * Common params for any request.\n */\nconst BaseRequestParamsSchema = z.object({\n /**\n * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * Common params for any task-augmented request.\n */\nexport const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * If specified, the caller is requesting task-augmented execution for this request.\n * The request will return a CreateTaskResult immediately, and the actual result can be\n * retrieved later via tasks/result.\n *\n * Task augmentation is subject to capability negotiation - receivers MUST declare support\n * for task augmentation of specific request types in their capabilities.\n */\n task: TaskMetadataSchema.optional()\n});\n/**\n * Checks if a value is a valid TaskAugmentedRequestParams.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise.\n */\nexport const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;\nexport const RequestSchema = z.object({\n method: z.string(),\n params: BaseRequestParamsSchema.loose().optional()\n});\nconst NotificationsParamsSchema = z.object({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\nexport const NotificationSchema = z.object({\n method: z.string(),\n params: NotificationsParamsSchema.loose().optional()\n});\nexport const ResultSchema = z.looseObject({\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: RequestMetaSchema.optional()\n});\n/**\n * A uniquely identifying ID for a request in JSON-RPC.\n */\nexport const RequestIdSchema = z.union([z.string(), z.number().int()]);\n/**\n * A request that expects a response.\n */\nexport const JSONRPCRequestSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n ...RequestSchema.shape\n})\n .strict();\nexport const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;\n/**\n * A notification which does not expect a response.\n */\nexport const JSONRPCNotificationSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n ...NotificationSchema.shape\n})\n .strict();\nexport const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;\n/**\n * A successful (non-error) response to a request.\n */\nexport const JSONRPCResultResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema,\n result: ResultSchema\n})\n .strict();\n/**\n * Checks if a value is a valid JSONRPCResultResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCResultResponse, false otherwise.\n */\nexport const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCResultResponse} instead.\n *\n * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse})\n */\nexport const isJSONRPCResponse = isJSONRPCResultResponse;\n/**\n * Error codes defined by the JSON-RPC specification.\n */\nexport var ErrorCode;\n(function (ErrorCode) {\n // SDK error codes\n ErrorCode[ErrorCode[\"ConnectionClosed\"] = -32000] = \"ConnectionClosed\";\n ErrorCode[ErrorCode[\"RequestTimeout\"] = -32001] = \"RequestTimeout\";\n // Standard JSON-RPC error codes\n ErrorCode[ErrorCode[\"ParseError\"] = -32700] = \"ParseError\";\n ErrorCode[ErrorCode[\"InvalidRequest\"] = -32600] = \"InvalidRequest\";\n ErrorCode[ErrorCode[\"MethodNotFound\"] = -32601] = \"MethodNotFound\";\n ErrorCode[ErrorCode[\"InvalidParams\"] = -32602] = \"InvalidParams\";\n ErrorCode[ErrorCode[\"InternalError\"] = -32603] = \"InternalError\";\n // MCP-specific error codes\n ErrorCode[ErrorCode[\"UrlElicitationRequired\"] = -32042] = \"UrlElicitationRequired\";\n})(ErrorCode || (ErrorCode = {}));\n/**\n * A response to a request that indicates an error occurred.\n */\nexport const JSONRPCErrorResponseSchema = z\n .object({\n jsonrpc: z.literal(JSONRPC_VERSION),\n id: RequestIdSchema.optional(),\n error: z.object({\n /**\n * The error type that occurred.\n */\n code: z.number().int(),\n /**\n * A short description of the error. The message SHOULD be limited to a concise single sentence.\n */\n message: z.string(),\n /**\n * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).\n */\n data: z.unknown().optional()\n })\n})\n .strict();\n/**\n * @deprecated Use {@link JSONRPCErrorResponseSchema} instead.\n */\nexport const JSONRPCErrorSchema = JSONRPCErrorResponseSchema;\n/**\n * Checks if a value is a valid JSONRPCErrorResponse.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise.\n */\nexport const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;\n/**\n * @deprecated Use {@link isJSONRPCErrorResponse} instead.\n */\nexport const isJSONRPCError = isJSONRPCErrorResponse;\nexport const JSONRPCMessageSchema = z.union([\n JSONRPCRequestSchema,\n JSONRPCNotificationSchema,\n JSONRPCResultResponseSchema,\n JSONRPCErrorResponseSchema\n]);\nexport const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);\n/* Empty result */\n/**\n * A response that indicates success but carries no data.\n */\nexport const EmptyResultSchema = ResultSchema.strict();\nexport const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the request to cancel.\n *\n * This MUST correspond to the ID of a request previously issued in the same direction.\n */\n requestId: RequestIdSchema.optional(),\n /**\n * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.\n */\n reason: z.string().optional()\n});\n/* Cancellation */\n/**\n * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.\n *\n * 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.\n *\n * This notification indicates that the result will be unused, so any associated processing SHOULD cease.\n *\n * A client MUST NOT attempt to cancel its `initialize` request.\n */\nexport const CancelledNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/cancelled'),\n params: CancelledNotificationParamsSchema\n});\n/* Base Metadata */\n/**\n * Icon schema for use in tools, prompts, resources, and implementations.\n */\nexport const IconSchema = z.object({\n /**\n * URL or data URI for the icon.\n */\n src: z.string(),\n /**\n * Optional MIME type for the icon.\n */\n mimeType: z.string().optional(),\n /**\n * Optional array of strings that specify sizes at which the icon can be used.\n * Each string should be in WxH format (e.g., `\"48x48\"`, `\"96x96\"`) or `\"any\"` for scalable formats like SVG.\n *\n * If not provided, the client should assume that the icon can be used at any size.\n */\n sizes: z.array(z.string()).optional(),\n /**\n * Optional specifier for the theme this icon is designed for. `light` indicates\n * the icon is designed to be used with a light background, and `dark` indicates\n * the icon is designed to be used with a dark background.\n *\n * If not provided, the client should assume the icon can be used with any theme.\n */\n theme: z.enum(['light', 'dark']).optional()\n});\n/**\n * Base schema to add `icons` property.\n *\n */\nexport const IconsSchema = z.object({\n /**\n * Optional set of sized icons that the client can display in a user interface.\n *\n * Clients that support rendering icons MUST support at least the following MIME types:\n * - `image/png` - PNG images (safe, universal compatibility)\n * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)\n *\n * Clients that support rendering icons SHOULD also support:\n * - `image/svg+xml` - SVG images (scalable but requires security precautions)\n * - `image/webp` - WebP images (modern, efficient format)\n */\n icons: z.array(IconSchema).optional()\n});\n/**\n * Base metadata interface for common properties across resources, tools, prompts, and implementations.\n */\nexport const BaseMetadataSchema = z.object({\n /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */\n name: z.string(),\n /**\n * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,\n * even by those unfamiliar with domain-specific terminology.\n *\n * If not provided, the name should be used for display (except for Tool,\n * where `annotations.title` should be given precedence over using `name`,\n * if present).\n */\n title: z.string().optional()\n});\n/* Initialization */\n/**\n * Describes the name and version of an MCP implementation.\n */\nexport const ImplementationSchema = BaseMetadataSchema.extend({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n version: z.string(),\n /**\n * An optional URL of the website for this implementation.\n */\n websiteUrl: z.string().optional(),\n /**\n * An optional human-readable description of what this implementation does.\n *\n * This can be used by clients or servers to provide context about their purpose\n * and capabilities. For example, a server might describe the types of resources\n * or tools it provides, while a client might describe its intended use case.\n */\n description: z.string().optional()\n});\nconst FormElicitationCapabilitySchema = z.intersection(z.object({\n applyDefaults: z.boolean().optional()\n}), z.record(z.string(), z.unknown()));\nconst ElicitationCapabilitySchema = z.preprocess(value => {\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n if (Object.keys(value).length === 0) {\n return { form: {} };\n }\n }\n return value;\n}, z.intersection(z.object({\n form: FormElicitationCapabilitySchema.optional(),\n url: AssertObjectSchema.optional()\n}), z.record(z.string(), z.unknown()).optional()));\n/**\n * Task capabilities for clients, indicating which request types support task creation.\n */\nexport const ClientTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the client supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the client supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for sampling requests.\n */\n sampling: z\n .looseObject({\n createMessage: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Task support for elicitation requests.\n */\n elicitation: z\n .looseObject({\n create: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * Task capabilities for servers, indicating which request types support task creation.\n */\nexport const ServerTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the server supports listing tasks.\n */\n list: AssertObjectSchema.optional(),\n /**\n * Present if the server supports cancelling tasks.\n */\n cancel: AssertObjectSchema.optional(),\n /**\n * Capabilities for task creation on specific request types.\n */\n requests: z\n .looseObject({\n /**\n * Task support for tool requests.\n */\n tools: z\n .looseObject({\n call: AssertObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n/**\n * 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.\n */\nexport const ClientCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the client supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the client supports sampling from an LLM.\n */\n sampling: z\n .object({\n /**\n * Present if the client supports context inclusion via includeContext parameter.\n * If not declared, servers SHOULD only use `includeContext: \"none\"` (or omit it).\n */\n context: AssertObjectSchema.optional(),\n /**\n * Present if the client supports tool use via tools and toolChoice parameters.\n */\n tools: AssertObjectSchema.optional()\n })\n .optional(),\n /**\n * Present if the client supports eliciting user input.\n */\n elicitation: ElicitationCapabilitySchema.optional(),\n /**\n * Present if the client supports listing roots.\n */\n roots: z\n .object({\n /**\n * Whether the client supports issuing notifications for changes to the roots list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the client supports task creation.\n */\n tasks: ClientTasksCapabilitySchema.optional()\n});\nexport const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.\n */\n protocolVersion: z.string(),\n capabilities: ClientCapabilitiesSchema,\n clientInfo: ImplementationSchema\n});\n/**\n * This request is sent from the client to the server when it first connects, asking it to begin initialization.\n */\nexport const InitializeRequestSchema = RequestSchema.extend({\n method: z.literal('initialize'),\n params: InitializeRequestParamsSchema\n});\nexport const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success;\n/**\n * 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.\n */\nexport const ServerCapabilitiesSchema = z.object({\n /**\n * Experimental, non-standard capabilities that the server supports.\n */\n experimental: z.record(z.string(), AssertObjectSchema).optional(),\n /**\n * Present if the server supports sending log messages to the client.\n */\n logging: AssertObjectSchema.optional(),\n /**\n * Present if the server supports sending completions to the client.\n */\n completions: AssertObjectSchema.optional(),\n /**\n * Present if the server offers any prompt templates.\n */\n prompts: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the prompt list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any resources to read.\n */\n resources: z\n .object({\n /**\n * Whether this server supports clients subscribing to resource updates.\n */\n subscribe: z.boolean().optional(),\n /**\n * Whether this server supports issuing notifications for changes to the resource list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server offers any tools to call.\n */\n tools: z\n .object({\n /**\n * Whether this server supports issuing notifications for changes to the tool list.\n */\n listChanged: z.boolean().optional()\n })\n .optional(),\n /**\n * Present if the server supports task creation.\n */\n tasks: ServerTasksCapabilitySchema.optional()\n});\n/**\n * After receiving an initialize request from the client, the server sends this response.\n */\nexport const InitializeResultSchema = ResultSchema.extend({\n /**\n * 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.\n */\n protocolVersion: z.string(),\n capabilities: ServerCapabilitiesSchema,\n serverInfo: ImplementationSchema,\n /**\n * Instructions describing how to use the server and its features.\n *\n * 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.\n */\n instructions: z.string().optional()\n});\n/**\n * This notification is sent from the client to the server after initialization has finished.\n */\nexport const InitializedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/initialized'),\n params: NotificationsParamsSchema.optional()\n});\nexport const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;\n/* Ping */\n/**\n * 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.\n */\nexport const PingRequestSchema = RequestSchema.extend({\n method: z.literal('ping'),\n params: BaseRequestParamsSchema.optional()\n});\n/* Progress notifications */\nexport const ProgressSchema = z.object({\n /**\n * The progress thus far. This should increase every time progress is made, even if the total is unknown.\n */\n progress: z.number(),\n /**\n * Total number of items to process (or total progress required), if known.\n */\n total: z.optional(z.number()),\n /**\n * An optional message describing the current progress.\n */\n message: z.optional(z.string())\n});\nexport const ProgressNotificationParamsSchema = z.object({\n ...NotificationsParamsSchema.shape,\n ...ProgressSchema.shape,\n /**\n * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.\n */\n progressToken: ProgressTokenSchema\n});\n/**\n * An out-of-band notification used to inform the receiver of a progress update for a long-running request.\n *\n * @category notifications/progress\n */\nexport const ProgressNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/progress'),\n params: ProgressNotificationParamsSchema\n});\nexport const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * An opaque token representing the current pagination position.\n * If provided, the server should return results starting after this cursor.\n */\n cursor: CursorSchema.optional()\n});\n/* Pagination */\nexport const PaginatedRequestSchema = RequestSchema.extend({\n params: PaginatedRequestParamsSchema.optional()\n});\nexport const PaginatedResultSchema = ResultSchema.extend({\n /**\n * An opaque token representing the pagination position after the last returned result.\n * If present, there may be more results available.\n */\n nextCursor: CursorSchema.optional()\n});\n/**\n * The status of a task.\n * */\nexport const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']);\n/* Tasks */\n/**\n * A pollable state object associated with a request.\n */\nexport const TaskSchema = z.object({\n taskId: z.string(),\n status: TaskStatusSchema,\n /**\n * Time in milliseconds to keep task results available after completion.\n * If null, the task has unlimited lifetime until manually cleaned up.\n */\n ttl: z.union([z.number(), z.null()]),\n /**\n * ISO 8601 timestamp when the task was created.\n */\n createdAt: z.string(),\n /**\n * ISO 8601 timestamp when the task was last updated.\n */\n lastUpdatedAt: z.string(),\n pollInterval: z.optional(z.number()),\n /**\n * Optional diagnostic message for failed tasks or other status information.\n */\n statusMessage: z.optional(z.string())\n});\n/**\n * Result returned when a task is created, containing the task data wrapped in a task field.\n */\nexport const CreateTaskResultSchema = ResultSchema.extend({\n task: TaskSchema\n});\n/**\n * Parameters for task status notification.\n */\nexport const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);\n/**\n * A notification sent when a task's status changes.\n */\nexport const TaskStatusNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tasks/status'),\n params: TaskStatusNotificationParamsSchema\n});\n/**\n * A request to get the state of a specific task.\n */\nexport const GetTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/get'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/get request.\n */\nexport const GetTaskResultSchema = ResultSchema.merge(TaskSchema);\n/**\n * A request to get the result of a specific task.\n */\nexport const GetTaskPayloadRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/result'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/result request.\n * The structure matches the result type of the original request.\n * For example, a tools/call task would return the CallToolResult structure.\n *\n */\nexport const GetTaskPayloadResultSchema = ResultSchema.loose();\n/**\n * A request to list tasks.\n */\nexport const ListTasksRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tasks/list')\n});\n/**\n * The response to a tasks/list request.\n */\nexport const ListTasksResultSchema = PaginatedResultSchema.extend({\n tasks: z.array(TaskSchema)\n});\n/**\n * A request to cancel a specific task.\n */\nexport const CancelTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/cancel'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n/**\n * The response to a tasks/cancel request.\n */\nexport const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);\n/* Resources */\n/**\n * The contents of a specific resource or sub-resource.\n */\nexport const ResourceContentsSchema = z.object({\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\nexport const TextResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * The text of the item. This must only be set if the item can actually be represented as text (not binary data).\n */\n text: z.string()\n});\n/**\n * A Zod schema for validating Base64 strings that is more performant and\n * robust for very large inputs than the default regex-based check. It avoids\n * stack overflows by using the native `atob` function for validation.\n */\nconst Base64Schema = z.string().refine(val => {\n try {\n // atob throws a DOMException if the string contains characters\n // that are not part of the Base64 character set.\n atob(val);\n return true;\n }\n catch {\n return false;\n }\n}, { message: 'Invalid Base64 string' });\nexport const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n /**\n * A base64-encoded string representing the binary data of the item.\n */\n blob: Base64Schema\n});\n/**\n * The sender or recipient of messages and data in a conversation.\n */\nexport const RoleSchema = z.enum(['user', 'assistant']);\n/**\n * Optional annotations providing clients additional context about a resource.\n */\nexport const AnnotationsSchema = z.object({\n /**\n * Intended audience(s) for the resource.\n */\n audience: z.array(RoleSchema).optional(),\n /**\n * Importance hint for the resource, from 0 (least) to 1 (most).\n */\n priority: z.number().min(0).max(1).optional(),\n /**\n * ISO 8601 timestamp for the most recent modification.\n */\n lastModified: z.iso.datetime({ offset: true }).optional()\n});\n/**\n * A known resource that the server is capable of reading.\n */\nexport const ResourceSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * The URI of this resource.\n */\n uri: z.string(),\n /**\n * A description of what this resource represents.\n *\n * 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.\n */\n description: z.optional(z.string()),\n /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * A template description for resources available on the server.\n */\nexport const ResourceTemplateSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A URI template (according to RFC 6570) that can be used to construct resource URIs.\n */\n uriTemplate: z.string(),\n /**\n * A description of what this template is for.\n *\n * 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.\n */\n description: z.optional(z.string()),\n /**\n * 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.\n */\n mimeType: z.optional(z.string()),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of resources the server has.\n */\nexport const ListResourcesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/list')\n});\n/**\n * The server's response to a resources/list request from the client.\n */\nexport const ListResourcesResultSchema = PaginatedResultSchema.extend({\n resources: z.array(ResourceSchema)\n});\n/**\n * Sent from the client to request a list of resource templates the server has.\n */\nexport const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('resources/templates/list')\n});\n/**\n * The server's response to a resources/templates/list request from the client.\n */\nexport const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({\n resourceTemplates: z.array(ResourceTemplateSchema)\n});\nexport const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.\n *\n * @format uri\n */\n uri: z.string()\n});\n/**\n * Parameters for a `resources/read` request.\n */\nexport const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to the server, to read a specific resource URI.\n */\nexport const ReadResourceRequestSchema = RequestSchema.extend({\n method: z.literal('resources/read'),\n params: ReadResourceRequestParamsSchema\n});\n/**\n * The server's response to a resources/read request from the client.\n */\nexport const ReadResourceResultSchema = ResultSchema.extend({\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n});\n/**\n * 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.\n */\nexport const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\nexport const SubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes.\n */\nexport const SubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/subscribe'),\n params: SubscribeRequestParamsSchema\n});\nexport const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request.\n */\nexport const UnsubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/unsubscribe'),\n params: UnsubscribeRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/resources/updated` notification.\n */\nexport const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.\n */\n uri: z.string()\n});\n/**\n * 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.\n */\nexport const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/updated'),\n params: ResourceUpdatedNotificationParamsSchema\n});\n/* Prompts */\n/**\n * Describes an argument that a prompt can accept.\n */\nexport const PromptArgumentSchema = z.object({\n /**\n * The name of the argument.\n */\n name: z.string(),\n /**\n * A human-readable description of the argument.\n */\n description: z.optional(z.string()),\n /**\n * Whether this argument must be provided.\n */\n required: z.optional(z.boolean())\n});\n/**\n * A prompt or prompt template that the server offers.\n */\nexport const PromptSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * An optional description of what this prompt provides\n */\n description: z.optional(z.string()),\n /**\n * A list of arguments to use for templating the prompt.\n */\n arguments: z.optional(z.array(PromptArgumentSchema)),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.optional(z.looseObject({}))\n});\n/**\n * Sent from the client to request a list of prompts and prompt templates the server has.\n */\nexport const ListPromptsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('prompts/list')\n});\n/**\n * The server's response to a prompts/list request from the client.\n */\nexport const ListPromptsResultSchema = PaginatedResultSchema.extend({\n prompts: z.array(PromptSchema)\n});\n/**\n * Parameters for a `prompts/get` request.\n */\nexport const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The name of the prompt or prompt template.\n */\n name: z.string(),\n /**\n * Arguments to use for templating the prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n});\n/**\n * Used by the client to get a prompt provided by the server.\n */\nexport const GetPromptRequestSchema = RequestSchema.extend({\n method: z.literal('prompts/get'),\n params: GetPromptRequestParamsSchema\n});\n/**\n * Text provided to or from an LLM.\n */\nexport const TextContentSchema = z.object({\n type: z.literal('text'),\n /**\n * The text content of the message.\n */\n text: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An image provided to or from an LLM.\n */\nexport const ImageContentSchema = z.object({\n type: z.literal('image'),\n /**\n * The base64-encoded image data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the image. Different providers may support different image types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * An Audio provided to or from an LLM.\n */\nexport const AudioContentSchema = z.object({\n type: z.literal('audio'),\n /**\n * The base64-encoded audio data.\n */\n data: Base64Schema,\n /**\n * The MIME type of the audio. Different providers may support different audio types.\n */\n mimeType: z.string(),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A tool call request from an assistant (LLM).\n * Represents the assistant's request to use a tool.\n */\nexport const ToolUseContentSchema = z.object({\n type: z.literal('tool_use'),\n /**\n * The name of the tool to invoke.\n * Must match a tool name from the request's tools array.\n */\n name: z.string(),\n /**\n * Unique identifier for this tool call.\n * Used to correlate with ToolResultContent in subsequent messages.\n */\n id: z.string(),\n /**\n * Arguments to pass to the tool.\n * Must conform to the tool's inputSchema.\n */\n input: z.record(z.string(), z.unknown()),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * The contents of a resource, embedded into a prompt or tool call result.\n */\nexport const EmbeddedResourceSchema = z.object({\n type: z.literal('resource'),\n resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * A resource that the server is capable of reading, included in a prompt or tool call result.\n *\n * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.\n */\nexport const ResourceLinkSchema = ResourceSchema.extend({\n type: z.literal('resource_link')\n});\n/**\n * A content block that can be used in prompts and tool results.\n */\nexport const ContentBlockSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ResourceLinkSchema,\n EmbeddedResourceSchema\n]);\n/**\n * Describes a message returned as part of a prompt.\n */\nexport const PromptMessageSchema = z.object({\n role: RoleSchema,\n content: ContentBlockSchema\n});\n/**\n * The server's response to a prompts/get request from the client.\n */\nexport const GetPromptResultSchema = ResultSchema.extend({\n /**\n * An optional description for the prompt.\n */\n description: z.string().optional(),\n messages: z.array(PromptMessageSchema)\n});\n/**\n * 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.\n */\nexport const PromptListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/prompts/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Tools */\n/**\n * Additional properties describing a Tool to clients.\n *\n * NOTE: all properties in ToolAnnotations are **hints**.\n * They are not guaranteed to provide a faithful description of\n * tool behavior (including descriptive properties like `title`).\n *\n * Clients should never make tool use decisions based on ToolAnnotations\n * received from untrusted servers.\n */\nexport const ToolAnnotationsSchema = z.object({\n /**\n * A human-readable title for the tool.\n */\n title: z.string().optional(),\n /**\n * If true, the tool does not modify its environment.\n *\n * Default: false\n */\n readOnlyHint: z.boolean().optional(),\n /**\n * If true, the tool may perform destructive updates to its environment.\n * If false, the tool performs only additive updates.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: true\n */\n destructiveHint: z.boolean().optional(),\n /**\n * If true, calling the tool repeatedly with the same arguments\n * will have no additional effect on the its environment.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: false\n */\n idempotentHint: z.boolean().optional(),\n /**\n * If true, this tool may interact with an \"open world\" of external\n * entities. If false, the tool's domain of interaction is closed.\n * For example, the world of a web search tool is open, whereas that\n * of a memory tool is not.\n *\n * Default: true\n */\n openWorldHint: z.boolean().optional()\n});\n/**\n * Execution-related properties for a tool.\n */\nexport const ToolExecutionSchema = z.object({\n /**\n * Indicates the tool's preference for task-augmented execution.\n * - \"required\": Clients MUST invoke the tool as a task\n * - \"optional\": Clients MAY invoke the tool as a task or normal request\n * - \"forbidden\": Clients MUST NOT attempt to invoke the tool as a task\n *\n * If not present, defaults to \"forbidden\".\n */\n taskSupport: z.enum(['required', 'optional', 'forbidden']).optional()\n});\n/**\n * Definition for a tool the client can call.\n */\nexport const ToolSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n /**\n * A human-readable description of the tool.\n */\n description: z.string().optional(),\n /**\n * A JSON Schema 2020-12 object defining the expected parameters for the tool.\n * Must have type: 'object' at the root level per MCP spec.\n */\n inputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown()),\n /**\n * An optional JSON Schema 2020-12 object defining the structure of the tool's output\n * returned in the structuredContent field of a CallToolResult.\n * Must have type: 'object' at the root level per MCP spec.\n */\n outputSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), AssertObjectSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown())\n .optional(),\n /**\n * Optional additional tool information.\n */\n annotations: ToolAnnotationsSchema.optional(),\n /**\n * Execution-related properties for this tool.\n */\n execution: ToolExecutionSchema.optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the client to request a list of tools the server has.\n */\nexport const ListToolsRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tools/list')\n});\n/**\n * The server's response to a tools/list request from the client.\n */\nexport const ListToolsResultSchema = PaginatedResultSchema.extend({\n tools: z.array(ToolSchema)\n});\n/**\n * The server's response to a tool call.\n */\nexport const CallToolResultSchema = ResultSchema.extend({\n /**\n * A list of content objects that represent the result of the tool call.\n *\n * If the Tool does not define an outputSchema, this field MUST be present in the result.\n * For backwards compatibility, this field is always present, but it may be empty.\n */\n content: z.array(ContentBlockSchema).default([]),\n /**\n * An object containing structured tool output.\n *\n * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.\n */\n structuredContent: z.record(z.string(), z.unknown()).optional(),\n /**\n * Whether the tool call ended in an error.\n *\n * If not set, this is assumed to be false (the call was successful).\n *\n * Any errors that originate from the tool SHOULD be reported inside the result\n * object, with `isError` set to true, _not_ as an MCP protocol-level error\n * response. Otherwise, the LLM would not be able to see that an error occurred\n * and self-correct.\n *\n * However, any errors in _finding_ the tool, an error indicating that the\n * server does not support tool calls, or any other exceptional conditions,\n * should be reported as an MCP error response.\n */\n isError: z.boolean().optional()\n});\n/**\n * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07.\n */\nexport const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({\n toolResult: z.unknown()\n}));\n/**\n * Parameters for a `tools/call` request.\n */\nexport const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The name of the tool to call.\n */\n name: z.string(),\n /**\n * Arguments to pass to the tool.\n */\n arguments: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Used by the client to invoke a tool provided by the server.\n */\nexport const CallToolRequestSchema = RequestSchema.extend({\n method: z.literal('tools/call'),\n params: CallToolRequestParamsSchema\n});\n/**\n * 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.\n */\nexport const ToolListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tools/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/**\n * Base schema for list changed subscription options (without callback).\n * Used internally for Zod validation of autoRefresh and debounceMs.\n */\nexport const ListChangedOptionsBaseSchema = z.object({\n /**\n * If true, the list will be refreshed automatically when a list changed notification is received.\n * The callback will be called with the updated list.\n *\n * If false, the callback will be called with null items, allowing manual refresh.\n *\n * @default true\n */\n autoRefresh: z.boolean().default(true),\n /**\n * Debounce time in milliseconds for list changed notification processing.\n *\n * Multiple notifications received within this timeframe will only trigger one refresh.\n * Set to 0 to disable debouncing.\n *\n * @default 300\n */\n debounceMs: z.number().int().nonnegative().default(300)\n});\n/* Logging */\n/**\n * The severity of a log message.\n */\nexport const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n/**\n * Parameters for a `logging/setLevel` request.\n */\nexport const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * 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.\n */\n level: LoggingLevelSchema\n});\n/**\n * A request from the client to the server, to enable or adjust logging.\n */\nexport const SetLevelRequestSchema = RequestSchema.extend({\n method: z.literal('logging/setLevel'),\n params: SetLevelRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/message` notification.\n */\nexport const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The severity of this log message.\n */\n level: LoggingLevelSchema,\n /**\n * An optional name of the logger issuing this message.\n */\n logger: z.string().optional(),\n /**\n * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.\n */\n data: z.unknown()\n});\n/**\n * 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.\n */\nexport const LoggingMessageNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/message'),\n params: LoggingMessageNotificationParamsSchema\n});\n/* Sampling */\n/**\n * Hints to use for model selection.\n */\nexport const ModelHintSchema = z.object({\n /**\n * A hint for a model name.\n */\n name: z.string().optional()\n});\n/**\n * The server's preferences for model selection, requested of the client during sampling.\n */\nexport const ModelPreferencesSchema = z.object({\n /**\n * Optional hints to use for model selection.\n */\n hints: z.array(ModelHintSchema).optional(),\n /**\n * How much to prioritize cost when selecting a model.\n */\n costPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize sampling speed (latency) when selecting a model.\n */\n speedPriority: z.number().min(0).max(1).optional(),\n /**\n * How much to prioritize intelligence and capabilities when selecting a model.\n */\n intelligencePriority: z.number().min(0).max(1).optional()\n});\n/**\n * Controls tool usage behavior in sampling requests.\n */\nexport const ToolChoiceSchema = z.object({\n /**\n * Controls when tools are used:\n * - \"auto\": Model decides whether to use tools (default)\n * - \"required\": Model MUST use at least one tool before completing\n * - \"none\": Model MUST NOT use any tools\n */\n mode: z.enum(['auto', 'required', 'none']).optional()\n});\n/**\n * The result of a tool execution, provided by the user (server).\n * Represents the outcome of invoking a tool requested via ToolUseContent.\n */\nexport const ToolResultContentSchema = z.object({\n type: z.literal('tool_result'),\n toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'),\n content: z.array(ContentBlockSchema).default([]),\n structuredContent: z.object({}).loose().optional(),\n isError: z.boolean().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Basic content types for sampling responses (without tool use).\n * Used for backwards-compatible CreateMessageResult when tools are not used.\n */\nexport const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);\n/**\n * Content block types allowed in sampling messages.\n * This includes text, image, audio, tool use requests, and tool results.\n */\nexport const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n ToolResultContentSchema\n]);\n/**\n * Describes a message issued to or received from an LLM API.\n */\nexport const SamplingMessageSchema = z.object({\n role: RoleSchema,\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Parameters for a `sampling/createMessage` request.\n */\nexport const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n messages: z.array(SamplingMessageSchema),\n /**\n * The server's preferences for which model to select. The client MAY modify or omit this request.\n */\n modelPreferences: ModelPreferencesSchema.optional(),\n /**\n * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.\n */\n systemPrompt: z.string().optional(),\n /**\n * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.\n * The client MAY ignore this request.\n *\n * Default is \"none\". Values \"thisServer\" and \"allServers\" are soft-deprecated. Servers SHOULD only use these values if the client\n * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.\n */\n includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n temperature: z.number().optional(),\n /**\n * The requested maximum number of tokens to sample (to prevent runaway completions).\n *\n * The client MAY choose to sample fewer tokens than the requested maximum.\n */\n maxTokens: z.number().int(),\n stopSequences: z.array(z.string()).optional(),\n /**\n * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.\n */\n metadata: AssertObjectSchema.optional(),\n /**\n * Tools that the model may use during generation.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n */\n tools: z.array(ToolSchema).optional(),\n /**\n * Controls how the model uses tools.\n * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.\n * Default is `{ mode: \"auto\" }`.\n */\n toolChoice: ToolChoiceSchema.optional()\n});\n/**\n * 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.\n */\nexport const CreateMessageRequestSchema = RequestSchema.extend({\n method: z.literal('sampling/createMessage'),\n params: CreateMessageRequestParamsSchema\n});\n/**\n * The client's response to a sampling/create_message request from the server.\n * This is the backwards-compatible version that returns single content (no arrays).\n * Used when the request does not include tools.\n */\nexport const CreateMessageResultSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. Single content block (text, image, or audio).\n */\n content: SamplingContentSchema\n});\n/**\n * The client's response to a sampling/create_message request when tools were provided.\n * This version supports array content for tool use flows.\n */\nexport const CreateMessageResultWithToolsSchema = ResultSchema.extend({\n /**\n * The name of the model that generated the message.\n */\n model: z.string(),\n /**\n * The reason why sampling stopped, if known.\n *\n * Standard values:\n * - \"endTurn\": Natural end of the assistant's turn\n * - \"stopSequence\": A stop sequence was encountered\n * - \"maxTokens\": Maximum token limit was reached\n * - \"toolUse\": The model wants to use one or more tools\n *\n * This field is an open string to allow for provider-specific stop reasons.\n */\n stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())),\n role: RoleSchema,\n /**\n * Response content. May be a single block or array. May include ToolUseContent if stopReason is \"toolUse\".\n */\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)])\n});\n/* Elicitation */\n/**\n * Primitive schema definition for boolean fields.\n */\nexport const BooleanSchemaSchema = z.object({\n type: z.literal('boolean'),\n title: z.string().optional(),\n description: z.string().optional(),\n default: z.boolean().optional()\n});\n/**\n * Primitive schema definition for string fields.\n */\nexport const StringSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n minLength: z.number().optional(),\n maxLength: z.number().optional(),\n format: z.enum(['email', 'uri', 'date', 'date-time']).optional(),\n default: z.string().optional()\n});\n/**\n * Primitive schema definition for number fields.\n */\nexport const NumberSchemaSchema = z.object({\n type: z.enum(['number', 'integer']),\n title: z.string().optional(),\n description: z.string().optional(),\n minimum: z.number().optional(),\n maximum: z.number().optional(),\n default: z.number().optional()\n});\n/**\n * Schema for single-selection enumeration without display titles for options.\n */\nexport const UntitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n default: z.string().optional()\n});\n/**\n * Schema for single-selection enumeration with display titles for each option.\n */\nexport const TitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n oneOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n })),\n default: z.string().optional()\n});\n/**\n * Use TitledSingleSelectEnumSchema instead.\n * This interface will be removed in a future version.\n */\nexport const LegacyTitledEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n enum: z.array(z.string()),\n enumNames: z.array(z.string()).optional(),\n default: z.string().optional()\n});\n// Combined single selection enumeration\nexport const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n/**\n * Schema for multiple-selection enumeration without display titles for options.\n */\nexport const UntitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n type: z.literal('string'),\n enum: z.array(z.string())\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Schema for multiple-selection enumeration with display titles for each option.\n */\nexport const TitledMultiSelectEnumSchemaSchema = z.object({\n type: z.literal('array'),\n title: z.string().optional(),\n description: z.string().optional(),\n minItems: z.number().optional(),\n maxItems: z.number().optional(),\n items: z.object({\n anyOf: z.array(z.object({\n const: z.string(),\n title: z.string()\n }))\n }),\n default: z.array(z.string()).optional()\n});\n/**\n * Combined schema for multiple-selection enumeration\n */\nexport const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n/**\n * Primitive schema definition for enum fields.\n */\nexport const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n/**\n * Union of all primitive schema definitions.\n */\nexport const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n/**\n * Parameters for an `elicitation/create` request for form-based elicitation.\n */\nexport const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n *\n * Optional for backward compatibility. Clients MUST treat missing mode as \"form\".\n */\n mode: z.literal('form').optional(),\n /**\n * The message to present to the user describing what information is being requested.\n */\n message: z.string(),\n /**\n * A restricted subset of JSON Schema.\n * Only top-level properties are allowed, without nesting.\n */\n requestedSchema: z.object({\n type: z.literal('object'),\n properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n required: z.array(z.string()).optional()\n })\n});\n/**\n * Parameters for an `elicitation/create` request for URL-based elicitation.\n */\nexport const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n /**\n * The elicitation mode.\n */\n mode: z.literal('url'),\n /**\n * The message to present to the user explaining why the interaction is needed.\n */\n message: z.string(),\n /**\n * The ID of the elicitation, which must be unique within the context of the server.\n * The client MUST treat this ID as an opaque value.\n */\n elicitationId: z.string(),\n /**\n * The URL that the user should navigate to.\n */\n url: z.string().url()\n});\n/**\n * The parameters for a request to elicit additional information from the user via the client.\n */\nexport const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n/**\n * A request from the server to elicit user input via the client.\n * The client should present the message and form fields to the user (form mode)\n * or navigate to a URL (URL mode).\n */\nexport const ElicitRequestSchema = RequestSchema.extend({\n method: z.literal('elicitation/create'),\n params: ElicitRequestParamsSchema\n});\n/**\n * Parameters for a `notifications/elicitation/complete` notification.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the elicitation that completed.\n */\n elicitationId: z.string()\n});\n/**\n * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request.\n *\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/elicitation/complete'),\n params: ElicitationCompleteNotificationParamsSchema\n});\n/**\n * The client's response to an elicitation/create request from the server.\n */\nexport const ElicitResultSchema = ResultSchema.extend({\n /**\n * The user action in response to the elicitation.\n * - \"accept\": User submitted the form/confirmed the action\n * - \"decline\": User explicitly decline the action\n * - \"cancel\": User dismissed without making an explicit choice\n */\n action: z.enum(['accept', 'decline', 'cancel']),\n /**\n * The submitted form data, only present when action is \"accept\".\n * Contains values matching the requested schema.\n * Per MCP spec, content is \"typically omitted\" for decline/cancel actions.\n * We normalize null to undefined for leniency while maintaining type compatibility.\n */\n content: z.preprocess(val => (val === null ? undefined : val), z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional())\n});\n/* Autocomplete */\n/**\n * A reference to a resource or resource template definition.\n */\nexport const ResourceTemplateReferenceSchema = z.object({\n type: z.literal('ref/resource'),\n /**\n * The URI or URI template of the resource.\n */\n uri: z.string()\n});\n/**\n * @deprecated Use ResourceTemplateReferenceSchema instead\n */\nexport const ResourceReferenceSchema = ResourceTemplateReferenceSchema;\n/**\n * Identifies a prompt.\n */\nexport const PromptReferenceSchema = z.object({\n type: z.literal('ref/prompt'),\n /**\n * The name of the prompt or prompt template\n */\n name: z.string()\n});\n/**\n * Parameters for a `completion/complete` request.\n */\nexport const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({\n ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n /**\n * The argument's information\n */\n argument: z.object({\n /**\n * The name of the argument\n */\n name: z.string(),\n /**\n * The value of the argument to use for completion matching.\n */\n value: z.string()\n }),\n context: z\n .object({\n /**\n * Previously-resolved variables in a URI template or prompt.\n */\n arguments: z.record(z.string(), z.string()).optional()\n })\n .optional()\n});\n/**\n * A request from the client to the server, to ask for completion options.\n */\nexport const CompleteRequestSchema = RequestSchema.extend({\n method: z.literal('completion/complete'),\n params: CompleteRequestParamsSchema\n});\nexport function assertCompleteRequestPrompt(request) {\n if (request.params.ref.type !== 'ref/prompt') {\n throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);\n }\n void request;\n}\nexport function assertCompleteRequestResourceTemplate(request) {\n if (request.params.ref.type !== 'ref/resource') {\n throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);\n }\n void request;\n}\n/**\n * The server's response to a completion/complete request\n */\nexport const CompleteResultSchema = ResultSchema.extend({\n completion: z.looseObject({\n /**\n * An array of completion values. Must not exceed 100 items.\n */\n values: z.array(z.string()).max(100),\n /**\n * The total number of completion options available. This can exceed the number of values actually sent in the response.\n */\n total: z.optional(z.number().int()),\n /**\n * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.\n */\n hasMore: z.optional(z.boolean())\n })\n});\n/* Roots */\n/**\n * Represents a root directory or file that the server can operate on.\n */\nexport const RootSchema = z.object({\n /**\n * The URI identifying the root. This *must* start with file:// for now.\n */\n uri: z.string().startsWith('file://'),\n /**\n * An optional name for the root.\n */\n name: z.string().optional(),\n /**\n * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)\n * for notes on _meta usage.\n */\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n/**\n * Sent from the server to request a list of root URIs from the client.\n */\nexport const ListRootsRequestSchema = RequestSchema.extend({\n method: z.literal('roots/list'),\n params: BaseRequestParamsSchema.optional()\n});\n/**\n * The client's response to a roots/list request from the server.\n */\nexport const ListRootsResultSchema = ResultSchema.extend({\n roots: z.array(RootSchema)\n});\n/**\n * A notification from the client to the server, informing it that the list of roots has changed.\n */\nexport const RootsListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/roots/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n/* Client messages */\nexport const ClientRequestSchema = z.union([\n PingRequestSchema,\n InitializeRequestSchema,\n CompleteRequestSchema,\n SetLevelRequestSchema,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ReadResourceRequestSchema,\n SubscribeRequestSchema,\n UnsubscribeRequestSchema,\n CallToolRequestSchema,\n ListToolsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ClientNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n InitializedNotificationSchema,\n RootsListChangedNotificationSchema,\n TaskStatusNotificationSchema\n]);\nexport const ClientResultSchema = z.union([\n EmptyResultSchema,\n CreateMessageResultSchema,\n CreateMessageResultWithToolsSchema,\n ElicitResultSchema,\n ListRootsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\n/* Server messages */\nexport const ServerRequestSchema = z.union([\n PingRequestSchema,\n CreateMessageRequestSchema,\n ElicitRequestSchema,\n ListRootsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\nexport const ServerNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n LoggingMessageNotificationSchema,\n ResourceUpdatedNotificationSchema,\n ResourceListChangedNotificationSchema,\n ToolListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n TaskStatusNotificationSchema,\n ElicitationCompleteNotificationSchema\n]);\nexport const ServerResultSchema = z.union([\n EmptyResultSchema,\n InitializeResultSchema,\n CompleteResultSchema,\n GetPromptResultSchema,\n ListPromptsResultSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesResultSchema,\n ReadResourceResultSchema,\n CallToolResultSchema,\n ListToolsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\nexport class McpError extends Error {\n constructor(code, message, data) {\n super(`MCP error ${code}: ${message}`);\n this.code = code;\n this.data = data;\n this.name = 'McpError';\n }\n /**\n * Factory method to create the appropriate error type based on the error code and data\n */\n static fromError(code, message, data) {\n // Check for specific error types\n if (code === ErrorCode.UrlElicitationRequired && data) {\n const errorData = data;\n if (errorData.elicitations) {\n return new UrlElicitationRequiredError(errorData.elicitations, message);\n }\n }\n // Default to generic McpError\n return new McpError(code, message, data);\n }\n}\n/**\n * Specialized error type when a tool requires a URL mode elicitation.\n * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against.\n */\nexport class UrlElicitationRequiredError extends McpError {\n constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) {\n super(ErrorCode.UrlElicitationRequired, message, {\n elicitations: elicitations\n });\n }\n get elicitations() {\n return this.data?.elicitations ?? [];\n }\n}\n//# sourceMappingURL=types.js.map","/**\n * Experimental task interfaces for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n */\n/**\n * Checks if a task status represents a terminal state.\n * Terminal states are those where the task has finished and will not change.\n *\n * @param status - The task status to check\n * @returns True if the status is terminal (completed, failed, or cancelled)\n * @experimental\n */\nexport function isTerminal(status) {\n return status === 'completed' || status === 'failed' || status === 'cancelled';\n}\n//# sourceMappingURL=interfaces.js.map","// zod-json-schema-compat.ts\n// ----------------------------------------------------\n// JSON Schema conversion for both Zod v3 and Zod v4 (Mini)\n// v3 uses your vendored converter; v4 uses Mini's toJSONSchema\n// ----------------------------------------------------\nimport * as z4mini from 'zod/v4-mini';\nimport { getObjectShape, safeParse, isZ4Schema, getLiteralValue } from './zod-compat.js';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\nfunction mapMiniTarget(t) {\n if (!t)\n return 'draft-7';\n if (t === 'jsonSchema7' || t === 'draft-7')\n return 'draft-7';\n if (t === 'jsonSchema2019-09' || t === 'draft-2020-12')\n return 'draft-2020-12';\n return 'draft-7'; // fallback\n}\nexport function toJsonSchemaCompat(schema, opts) {\n if (isZ4Schema(schema)) {\n // v4 branch — use Mini's built-in toJSONSchema\n return z4mini.toJSONSchema(schema, {\n target: mapMiniTarget(opts?.target),\n io: opts?.pipeStrategy ?? 'input'\n });\n }\n // v3 branch — use vendored converter\n return zodToJsonSchema(schema, {\n strictUnions: opts?.strictUnions ?? true,\n pipeStrategy: opts?.pipeStrategy ?? 'input'\n });\n}\nexport function getMethodLiteral(schema) {\n const shape = getObjectShape(schema);\n const methodSchema = shape?.method;\n if (!methodSchema) {\n throw new Error('Schema is missing a method literal');\n }\n const value = getLiteralValue(methodSchema);\n if (typeof value !== 'string') {\n throw new Error('Schema method literal must be a string');\n }\n return value;\n}\nexport function parseWithCompat(schema, data) {\n const result = safeParse(schema, data);\n if (!result.success) {\n throw result.error;\n }\n return result.data;\n}\n//# sourceMappingURL=zod-json-schema-compat.js.map","import { safeParse } from '../server/zod-compat.js';\nimport { CancelledNotificationSchema, CreateTaskResultSchema, ErrorCode, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse, isJSONRPCNotification, McpError, PingRequestSchema, ProgressNotificationSchema, RELATED_TASK_META_KEY, TaskStatusNotificationSchema, isTaskAugmentedRequestParams } from '../types.js';\nimport { isTerminal } from '../experimental/tasks/interfaces.js';\nimport { getMethodLiteral, parseWithCompat } from '../server/zod-json-schema-compat.js';\n/**\n * The default request timeout, in miliseconds.\n */\nexport const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000;\n/**\n * Implements MCP protocol framing on top of a pluggable transport, including\n * features like request/response linking, notifications, and progress.\n */\nexport class Protocol {\n constructor(_options) {\n this._options = _options;\n this._requestMessageId = 0;\n this._requestHandlers = new Map();\n this._requestHandlerAbortControllers = new Map();\n this._notificationHandlers = new Map();\n this._responseHandlers = new Map();\n this._progressHandlers = new Map();\n this._timeoutInfo = new Map();\n this._pendingDebouncedNotifications = new Set();\n // Maps task IDs to progress tokens to keep handlers alive after CreateTaskResult\n this._taskProgressTokens = new Map();\n this._requestResolvers = new Map();\n this.setNotificationHandler(CancelledNotificationSchema, notification => {\n this._oncancel(notification);\n });\n this.setNotificationHandler(ProgressNotificationSchema, notification => {\n this._onprogress(notification);\n });\n this.setRequestHandler(PingRequestSchema, \n // Automatic pong by default.\n _request => ({}));\n // Install task handlers if TaskStore is provided\n this._taskStore = _options?.taskStore;\n this._taskMessageQueue = _options?.taskMessageQueue;\n if (this._taskStore) {\n this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {\n const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found');\n }\n // Per spec: tasks/get responses SHALL NOT include related-task metadata\n // as the taskId parameter is the source of truth\n // @ts-expect-error SendResultT cannot contain GetTaskResult, but we include it in our derived types everywhere else\n return {\n ...task\n };\n });\n this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {\n const handleTaskResult = async () => {\n const taskId = request.params.taskId;\n // Deliver queued messages\n if (this._taskMessageQueue) {\n let queuedMessage;\n while ((queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId))) {\n // Handle response and error messages by routing them to the appropriate resolver\n if (queuedMessage.type === 'response' || queuedMessage.type === 'error') {\n const message = queuedMessage.message;\n const requestId = message.id;\n // Lookup resolver in _requestResolvers map\n const resolver = this._requestResolvers.get(requestId);\n if (resolver) {\n // Remove resolver from map after invocation\n this._requestResolvers.delete(requestId);\n // Invoke resolver with response or error\n if (queuedMessage.type === 'response') {\n resolver(message);\n }\n else {\n // Convert JSONRPCError to McpError\n const errorMessage = message;\n const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);\n resolver(error);\n }\n }\n else {\n // Handle missing resolver gracefully with error logging\n const messageType = queuedMessage.type === 'response' ? 'Response' : 'Error';\n this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));\n }\n // Continue to next message\n continue;\n }\n // Send the message on the response stream by passing the relatedRequestId\n // This tells the transport to write the message to the tasks/result response stream\n await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId });\n }\n }\n // Now check task status\n const task = await this._taskStore.getTask(taskId, extra.sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);\n }\n // Block if task is not terminal (we've already delivered all queued messages above)\n if (!isTerminal(task.status)) {\n // Wait for status change or new messages\n await this._waitForTaskUpdate(taskId, extra.signal);\n // After waking up, recursively call to deliver any new messages or result\n return await handleTaskResult();\n }\n // If task is terminal, return the result\n if (isTerminal(task.status)) {\n const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);\n this._clearTaskQueue(taskId);\n return {\n ...result,\n _meta: {\n ...result._meta,\n [RELATED_TASK_META_KEY]: {\n taskId: taskId\n }\n }\n };\n }\n return await handleTaskResult();\n };\n return await handleTaskResult();\n });\n this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {\n try {\n const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId);\n // @ts-expect-error SendResultT cannot contain ListTasksResult, but we include it in our derived types everywhere else\n return {\n tasks,\n nextCursor,\n _meta: {}\n };\n }\n catch (error) {\n throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`);\n }\n });\n this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {\n try {\n // Get the current task to check if it's in a terminal state, in case the implementation is not atomic\n const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);\n }\n // Reject cancellation of terminal tasks\n if (isTerminal(task.status)) {\n throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);\n }\n await this._taskStore.updateTaskStatus(request.params.taskId, 'cancelled', 'Client cancelled task execution.', extra.sessionId);\n this._clearTaskQueue(request.params.taskId);\n const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);\n if (!cancelledTask) {\n // Task was deleted during cancellation (e.g., cleanup happened)\n throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);\n }\n return {\n _meta: {},\n ...cancelledTask\n };\n }\n catch (error) {\n // Re-throw McpError as-is\n if (error instanceof McpError) {\n throw error;\n }\n throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`);\n }\n });\n }\n }\n async _oncancel(notification) {\n if (!notification.params.requestId) {\n return;\n }\n // Handle request cancellation\n const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);\n controller?.abort(notification.params.reason);\n }\n _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {\n this._timeoutInfo.set(messageId, {\n timeoutId: setTimeout(onTimeout, timeout),\n startTime: Date.now(),\n timeout,\n maxTotalTimeout,\n resetTimeoutOnProgress,\n onTimeout\n });\n }\n _resetTimeout(messageId) {\n const info = this._timeoutInfo.get(messageId);\n if (!info)\n return false;\n const totalElapsed = Date.now() - info.startTime;\n if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {\n this._timeoutInfo.delete(messageId);\n throw McpError.fromError(ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', {\n maxTotalTimeout: info.maxTotalTimeout,\n totalElapsed\n });\n }\n clearTimeout(info.timeoutId);\n info.timeoutId = setTimeout(info.onTimeout, info.timeout);\n return true;\n }\n _cleanupTimeout(messageId) {\n const info = this._timeoutInfo.get(messageId);\n if (info) {\n clearTimeout(info.timeoutId);\n this._timeoutInfo.delete(messageId);\n }\n }\n /**\n * Attaches to the given transport, starts it, and starts listening for messages.\n *\n * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.\n */\n async connect(transport) {\n if (this._transport) {\n throw new Error('Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.');\n }\n this._transport = transport;\n const _onclose = this.transport?.onclose;\n this._transport.onclose = () => {\n _onclose?.();\n this._onclose();\n };\n const _onerror = this.transport?.onerror;\n this._transport.onerror = (error) => {\n _onerror?.(error);\n this._onerror(error);\n };\n const _onmessage = this._transport?.onmessage;\n this._transport.onmessage = (message, extra) => {\n _onmessage?.(message, extra);\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n this._onresponse(message);\n }\n else if (isJSONRPCRequest(message)) {\n this._onrequest(message, extra);\n }\n else if (isJSONRPCNotification(message)) {\n this._onnotification(message);\n }\n else {\n this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));\n }\n };\n await this._transport.start();\n }\n _onclose() {\n const responseHandlers = this._responseHandlers;\n this._responseHandlers = new Map();\n this._progressHandlers.clear();\n this._taskProgressTokens.clear();\n this._pendingDebouncedNotifications.clear();\n // Abort all in-flight request handlers so they stop sending messages\n for (const controller of this._requestHandlerAbortControllers.values()) {\n controller.abort();\n }\n this._requestHandlerAbortControllers.clear();\n const error = McpError.fromError(ErrorCode.ConnectionClosed, 'Connection closed');\n this._transport = undefined;\n this.onclose?.();\n for (const handler of responseHandlers.values()) {\n handler(error);\n }\n }\n _onerror(error) {\n this.onerror?.(error);\n }\n _onnotification(notification) {\n const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler;\n // Ignore notifications not being subscribed to.\n if (handler === undefined) {\n return;\n }\n // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n Promise.resolve()\n .then(() => handler(notification))\n .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));\n }\n _onrequest(request, extra) {\n const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;\n // Capture the current transport at request time to ensure responses go to the correct client\n const capturedTransport = this._transport;\n // Extract taskId from request metadata if present (needed early for method not found case)\n const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId;\n if (handler === undefined) {\n const errorResponse = {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: ErrorCode.MethodNotFound,\n message: 'Method not found'\n }\n };\n // Queue or send the error response based on whether this is a task-related request\n if (relatedTaskId && this._taskMessageQueue) {\n this._enqueueTaskMessage(relatedTaskId, {\n type: 'error',\n message: errorResponse,\n timestamp: Date.now()\n }, capturedTransport?.sessionId).catch(error => this._onerror(new Error(`Failed to enqueue error response: ${error}`)));\n }\n else {\n capturedTransport\n ?.send(errorResponse)\n .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`)));\n }\n return;\n }\n const abortController = new AbortController();\n this._requestHandlerAbortControllers.set(request.id, abortController);\n const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : undefined;\n const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined;\n const fullExtra = {\n signal: abortController.signal,\n sessionId: capturedTransport?.sessionId,\n _meta: request.params?._meta,\n sendNotification: async (notification) => {\n if (abortController.signal.aborted)\n return;\n // Include related-task metadata if this request is part of a task\n const notificationOptions = { relatedRequestId: request.id };\n if (relatedTaskId) {\n notificationOptions.relatedTask = { taskId: relatedTaskId };\n }\n await this.notification(notification, notificationOptions);\n },\n sendRequest: async (r, resultSchema, options) => {\n if (abortController.signal.aborted) {\n throw new McpError(ErrorCode.ConnectionClosed, 'Request was cancelled');\n }\n // Include related-task metadata if this request is part of a task\n const requestOptions = { ...options, relatedRequestId: request.id };\n if (relatedTaskId && !requestOptions.relatedTask) {\n requestOptions.relatedTask = { taskId: relatedTaskId };\n }\n // Set task status to input_required when sending a request within a task context\n // Use the taskId from options (explicit) or fall back to relatedTaskId (inherited)\n const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId;\n if (effectiveTaskId && taskStore) {\n await taskStore.updateTaskStatus(effectiveTaskId, 'input_required');\n }\n return await this.request(r, resultSchema, requestOptions);\n },\n authInfo: extra?.authInfo,\n requestId: request.id,\n requestInfo: extra?.requestInfo,\n taskId: relatedTaskId,\n taskStore: taskStore,\n taskRequestedTtl: taskCreationParams?.ttl,\n closeSSEStream: extra?.closeSSEStream,\n closeStandaloneSSEStream: extra?.closeStandaloneSSEStream\n };\n // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n Promise.resolve()\n .then(() => {\n // If this request asked for task creation, check capability first\n if (taskCreationParams) {\n // Check if the request method supports task creation\n this.assertTaskHandlerCapability(request.method);\n }\n })\n .then(() => handler(request, fullExtra))\n .then(async (result) => {\n if (abortController.signal.aborted) {\n // Request was cancelled\n return;\n }\n const response = {\n result,\n jsonrpc: '2.0',\n id: request.id\n };\n // Queue or send the response based on whether this is a task-related request\n if (relatedTaskId && this._taskMessageQueue) {\n await this._enqueueTaskMessage(relatedTaskId, {\n type: 'response',\n message: response,\n timestamp: Date.now()\n }, capturedTransport?.sessionId);\n }\n else {\n await capturedTransport?.send(response);\n }\n }, async (error) => {\n if (abortController.signal.aborted) {\n // Request was cancelled\n return;\n }\n const errorResponse = {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode.InternalError,\n message: error.message ?? 'Internal error',\n ...(error['data'] !== undefined && { data: error['data'] })\n }\n };\n // Queue or send the error response based on whether this is a task-related request\n if (relatedTaskId && this._taskMessageQueue) {\n await this._enqueueTaskMessage(relatedTaskId, {\n type: 'error',\n message: errorResponse,\n timestamp: Date.now()\n }, capturedTransport?.sessionId);\n }\n else {\n await capturedTransport?.send(errorResponse);\n }\n })\n .catch(error => this._onerror(new Error(`Failed to send response: ${error}`)))\n .finally(() => {\n this._requestHandlerAbortControllers.delete(request.id);\n });\n }\n _onprogress(notification) {\n const { progressToken, ...params } = notification.params;\n const messageId = Number(progressToken);\n const handler = this._progressHandlers.get(messageId);\n if (!handler) {\n this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));\n return;\n }\n const responseHandler = this._responseHandlers.get(messageId);\n const timeoutInfo = this._timeoutInfo.get(messageId);\n if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {\n try {\n this._resetTimeout(messageId);\n }\n catch (error) {\n // Clean up if maxTotalTimeout was exceeded\n this._responseHandlers.delete(messageId);\n this._progressHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n responseHandler(error);\n return;\n }\n }\n handler(params);\n }\n _onresponse(response) {\n const messageId = Number(response.id);\n // Check if this is a response to a queued request\n const resolver = this._requestResolvers.get(messageId);\n if (resolver) {\n this._requestResolvers.delete(messageId);\n if (isJSONRPCResultResponse(response)) {\n resolver(response);\n }\n else {\n const error = new McpError(response.error.code, response.error.message, response.error.data);\n resolver(error);\n }\n return;\n }\n const handler = this._responseHandlers.get(messageId);\n if (handler === undefined) {\n this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));\n return;\n }\n this._responseHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n // Keep progress handler alive for CreateTaskResult responses\n let isTaskResponse = false;\n if (isJSONRPCResultResponse(response) && response.result && typeof response.result === 'object') {\n const result = response.result;\n if (result.task && typeof result.task === 'object') {\n const task = result.task;\n if (typeof task.taskId === 'string') {\n isTaskResponse = true;\n this._taskProgressTokens.set(task.taskId, messageId);\n }\n }\n }\n if (!isTaskResponse) {\n this._progressHandlers.delete(messageId);\n }\n if (isJSONRPCResultResponse(response)) {\n handler(response);\n }\n else {\n const error = McpError.fromError(response.error.code, response.error.message, response.error.data);\n handler(error);\n }\n }\n get transport() {\n return this._transport;\n }\n /**\n * Closes the connection.\n */\n async close() {\n await this._transport?.close();\n }\n /**\n * Sends a request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * @example\n * ```typescript\n * const stream = protocol.requestStream(request, resultSchema, options);\n * for await (const message of stream) {\n * switch (message.type) {\n * case 'taskCreated':\n * console.log('Task created:', message.task.taskId);\n * break;\n * case 'taskStatus':\n * console.log('Task status:', message.task.status);\n * break;\n * case 'result':\n * console.log('Final result:', message.result);\n * break;\n * case 'error':\n * console.error('Error:', message.error);\n * break;\n * }\n * }\n * ```\n *\n * @experimental Use `client.experimental.tasks.requestStream()` to access this method.\n */\n async *requestStream(request, resultSchema, options) {\n const { task } = options ?? {};\n // For non-task requests, just yield the result\n if (!task) {\n try {\n const result = await this.request(request, resultSchema, options);\n yield { type: 'result', result };\n }\n catch (error) {\n yield {\n type: 'error',\n error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))\n };\n }\n return;\n }\n // For task-augmented requests, we need to poll for status\n // First, make the request to create the task\n let taskId;\n try {\n // Send the request and get the CreateTaskResult\n const createResult = await this.request(request, CreateTaskResultSchema, options);\n // Extract taskId from the result\n if (createResult.task) {\n taskId = createResult.task.taskId;\n yield { type: 'taskCreated', task: createResult.task };\n }\n else {\n throw new McpError(ErrorCode.InternalError, 'Task creation did not return a task');\n }\n // Poll for task completion\n while (true) {\n // Get current task status\n const task = await this.getTask({ taskId }, options);\n yield { type: 'taskStatus', task };\n // Check if task is terminal\n if (isTerminal(task.status)) {\n if (task.status === 'completed') {\n // Get the final result\n const result = await this.getTaskResult({ taskId }, resultSchema, options);\n yield { type: 'result', result };\n }\n else if (task.status === 'failed') {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)\n };\n }\n else if (task.status === 'cancelled') {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)\n };\n }\n return;\n }\n // When input_required, call tasks/result to deliver queued messages\n // (elicitation, sampling) via SSE and block until terminal\n if (task.status === 'input_required') {\n const result = await this.getTaskResult({ taskId }, resultSchema, options);\n yield { type: 'result', result };\n return;\n }\n // Wait before polling again\n const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1000;\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n // Check if cancelled\n options?.signal?.throwIfAborted();\n }\n }\n catch (error) {\n yield {\n type: 'error',\n error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error))\n };\n }\n }\n /**\n * Sends a request and waits for a response.\n *\n * Do not use this method to emit notifications! Use notification() instead.\n */\n request(request, resultSchema, options) {\n const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {};\n // Send the request\n return new Promise((resolve, reject) => {\n const earlyReject = (error) => {\n reject(error);\n };\n if (!this._transport) {\n earlyReject(new Error('Not connected'));\n return;\n }\n if (this._options?.enforceStrictCapabilities === true) {\n try {\n this.assertCapabilityForMethod(request.method);\n // If task creation is requested, also check task capabilities\n if (task) {\n this.assertTaskCapability(request.method);\n }\n }\n catch (e) {\n earlyReject(e);\n return;\n }\n }\n options?.signal?.throwIfAborted();\n const messageId = this._requestMessageId++;\n const jsonrpcRequest = {\n ...request,\n jsonrpc: '2.0',\n id: messageId\n };\n if (options?.onprogress) {\n this._progressHandlers.set(messageId, options.onprogress);\n jsonrpcRequest.params = {\n ...request.params,\n _meta: {\n ...(request.params?._meta || {}),\n progressToken: messageId\n }\n };\n }\n // Augment with task creation parameters if provided\n if (task) {\n jsonrpcRequest.params = {\n ...jsonrpcRequest.params,\n task: task\n };\n }\n // Augment with related task metadata if relatedTask is provided\n if (relatedTask) {\n jsonrpcRequest.params = {\n ...jsonrpcRequest.params,\n _meta: {\n ...(jsonrpcRequest.params?._meta || {}),\n [RELATED_TASK_META_KEY]: relatedTask\n }\n };\n }\n const cancel = (reason) => {\n this._responseHandlers.delete(messageId);\n this._progressHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n this._transport\n ?.send({\n jsonrpc: '2.0',\n method: 'notifications/cancelled',\n params: {\n requestId: messageId,\n reason: String(reason)\n }\n }, { relatedRequestId, resumptionToken, onresumptiontoken })\n .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`)));\n // Wrap the reason in an McpError if it isn't already\n const error = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));\n reject(error);\n };\n this._responseHandlers.set(messageId, response => {\n if (options?.signal?.aborted) {\n return;\n }\n if (response instanceof Error) {\n return reject(response);\n }\n try {\n const parseResult = safeParse(resultSchema, response.result);\n if (!parseResult.success) {\n // Type guard: if success is false, error is guaranteed to exist\n reject(parseResult.error);\n }\n else {\n resolve(parseResult.data);\n }\n }\n catch (error) {\n reject(error);\n }\n });\n options?.signal?.addEventListener('abort', () => {\n cancel(options?.signal?.reason);\n });\n const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;\n const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, 'Request timed out', { timeout }));\n this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);\n // Queue request if related to a task\n const relatedTaskId = relatedTask?.taskId;\n if (relatedTaskId) {\n // Store the response resolver for this request so responses can be routed back\n const responseResolver = (response) => {\n const handler = this._responseHandlers.get(messageId);\n if (handler) {\n handler(response);\n }\n else {\n // Log error when resolver is missing, but don't fail\n this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));\n }\n };\n this._requestResolvers.set(messageId, responseResolver);\n this._enqueueTaskMessage(relatedTaskId, {\n type: 'request',\n message: jsonrpcRequest,\n timestamp: Date.now()\n }).catch(error => {\n this._cleanupTimeout(messageId);\n reject(error);\n });\n // Don't send through transport - queued messages are delivered via tasks/result only\n // This prevents duplicate delivery for bidirectional transports\n }\n else {\n // No related task - send through transport normally\n this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => {\n this._cleanupTimeout(messageId);\n reject(error);\n });\n }\n });\n }\n /**\n * Gets the current status of a task.\n *\n * @experimental Use `client.experimental.tasks.getTask()` to access this method.\n */\n async getTask(params, options) {\n // @ts-expect-error SendRequestT cannot directly contain GetTaskRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/get', params }, GetTaskResultSchema, options);\n }\n /**\n * Retrieves the result of a completed task.\n *\n * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.\n */\n async getTaskResult(params, resultSchema, options) {\n // @ts-expect-error SendRequestT cannot directly contain GetTaskPayloadRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/result', params }, resultSchema, options);\n }\n /**\n * Lists tasks, optionally starting from a pagination cursor.\n *\n * @experimental Use `client.experimental.tasks.listTasks()` to access this method.\n */\n async listTasks(params, options) {\n // @ts-expect-error SendRequestT cannot directly contain ListTasksRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/list', params }, ListTasksResultSchema, options);\n }\n /**\n * Cancels a specific task.\n *\n * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.\n */\n async cancelTask(params, options) {\n // @ts-expect-error SendRequestT cannot directly contain CancelTaskRequest, but we ensure all type instantiations contain it anyways\n return this.request({ method: 'tasks/cancel', params }, CancelTaskResultSchema, options);\n }\n /**\n * Emits a notification, which is a one-way message that does not expect a response.\n */\n async notification(notification, options) {\n if (!this._transport) {\n throw new Error('Not connected');\n }\n this.assertNotificationCapability(notification.method);\n // Queue notification if related to a task\n const relatedTaskId = options?.relatedTask?.taskId;\n if (relatedTaskId) {\n // Build the JSONRPC notification with metadata\n const jsonrpcNotification = {\n ...notification,\n jsonrpc: '2.0',\n params: {\n ...notification.params,\n _meta: {\n ...(notification.params?._meta || {}),\n [RELATED_TASK_META_KEY]: options.relatedTask\n }\n }\n };\n await this._enqueueTaskMessage(relatedTaskId, {\n type: 'notification',\n message: jsonrpcNotification,\n timestamp: Date.now()\n });\n // Don't send through transport - queued messages are delivered via tasks/result only\n // This prevents duplicate delivery for bidirectional transports\n return;\n }\n const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];\n // A notification can only be debounced if it's in the list AND it's \"simple\"\n // (i.e., has no parameters and no related request ID or related task that could be lost).\n const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask;\n if (canDebounce) {\n // If a notification of this type is already scheduled, do nothing.\n if (this._pendingDebouncedNotifications.has(notification.method)) {\n return;\n }\n // Mark this notification type as pending.\n this._pendingDebouncedNotifications.add(notification.method);\n // Schedule the actual send to happen in the next microtask.\n // This allows all synchronous calls in the current event loop tick to be coalesced.\n Promise.resolve().then(() => {\n // Un-mark the notification so the next one can be scheduled.\n this._pendingDebouncedNotifications.delete(notification.method);\n // SAFETY CHECK: If the connection was closed while this was pending, abort.\n if (!this._transport) {\n return;\n }\n let jsonrpcNotification = {\n ...notification,\n jsonrpc: '2.0'\n };\n // Augment with related task metadata if relatedTask is provided\n if (options?.relatedTask) {\n jsonrpcNotification = {\n ...jsonrpcNotification,\n params: {\n ...jsonrpcNotification.params,\n _meta: {\n ...(jsonrpcNotification.params?._meta || {}),\n [RELATED_TASK_META_KEY]: options.relatedTask\n }\n }\n };\n }\n // Send the notification, but don't await it here to avoid blocking.\n // Handle potential errors with a .catch().\n this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error));\n });\n // Return immediately.\n return;\n }\n let jsonrpcNotification = {\n ...notification,\n jsonrpc: '2.0'\n };\n // Augment with related task metadata if relatedTask is provided\n if (options?.relatedTask) {\n jsonrpcNotification = {\n ...jsonrpcNotification,\n params: {\n ...jsonrpcNotification.params,\n _meta: {\n ...(jsonrpcNotification.params?._meta || {}),\n [RELATED_TASK_META_KEY]: options.relatedTask\n }\n }\n };\n }\n await this._transport.send(jsonrpcNotification, options);\n }\n /**\n * Registers a handler to invoke when this protocol object receives a request with the given method.\n *\n * Note that this will replace any previous request handler for the same method.\n */\n setRequestHandler(requestSchema, handler) {\n const method = getMethodLiteral(requestSchema);\n this.assertRequestHandlerCapability(method);\n this._requestHandlers.set(method, (request, extra) => {\n const parsed = parseWithCompat(requestSchema, request);\n return Promise.resolve(handler(parsed, extra));\n });\n }\n /**\n * Removes the request handler for the given method.\n */\n removeRequestHandler(method) {\n this._requestHandlers.delete(method);\n }\n /**\n * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.\n */\n assertCanSetRequestHandler(method) {\n if (this._requestHandlers.has(method)) {\n throw new Error(`A request handler for ${method} already exists, which would be overridden`);\n }\n }\n /**\n * Registers a handler to invoke when this protocol object receives a notification with the given method.\n *\n * Note that this will replace any previous notification handler for the same method.\n */\n setNotificationHandler(notificationSchema, handler) {\n const method = getMethodLiteral(notificationSchema);\n this._notificationHandlers.set(method, notification => {\n const parsed = parseWithCompat(notificationSchema, notification);\n return Promise.resolve(handler(parsed));\n });\n }\n /**\n * Removes the notification handler for the given method.\n */\n removeNotificationHandler(method) {\n this._notificationHandlers.delete(method);\n }\n /**\n * Cleans up the progress handler associated with a task.\n * This should be called when a task reaches a terminal status.\n */\n _cleanupTaskProgressHandler(taskId) {\n const progressToken = this._taskProgressTokens.get(taskId);\n if (progressToken !== undefined) {\n this._progressHandlers.delete(progressToken);\n this._taskProgressTokens.delete(taskId);\n }\n }\n /**\n * Enqueues a task-related message for side-channel delivery via tasks/result.\n * @param taskId The task ID to associate the message with\n * @param message The message to enqueue\n * @param sessionId Optional session ID for binding the operation to a specific session\n * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)\n *\n * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle\n * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer\n * simply propagates the error.\n */\n async _enqueueTaskMessage(taskId, message, sessionId) {\n // Task message queues are only used when taskStore is configured\n if (!this._taskStore || !this._taskMessageQueue) {\n throw new Error('Cannot enqueue task message: taskStore and taskMessageQueue are not configured');\n }\n const maxQueueSize = this._options?.maxTaskQueueSize;\n await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);\n }\n /**\n * Clears the message queue for a task and rejects any pending request resolvers.\n * @param taskId The task ID whose queue should be cleared\n * @param sessionId Optional session ID for binding the operation to a specific session\n */\n async _clearTaskQueue(taskId, sessionId) {\n if (this._taskMessageQueue) {\n // Reject any pending request resolvers\n const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);\n for (const message of messages) {\n if (message.type === 'request' && isJSONRPCRequest(message.message)) {\n // Extract request ID from the message\n const requestId = message.message.id;\n const resolver = this._requestResolvers.get(requestId);\n if (resolver) {\n resolver(new McpError(ErrorCode.InternalError, 'Task cancelled or completed'));\n this._requestResolvers.delete(requestId);\n }\n else {\n // Log error when resolver is missing during cleanup for better observability\n this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));\n }\n }\n }\n }\n }\n /**\n * Waits for a task update (new messages or status change) with abort signal support.\n * Uses polling to check for updates at the task's configured poll interval.\n * @param taskId The task ID to wait for\n * @param signal Abort signal to cancel the wait\n * @returns Promise that resolves when an update occurs or rejects if aborted\n */\n async _waitForTaskUpdate(taskId, signal) {\n // Get the task's poll interval, falling back to default\n let interval = this._options?.defaultTaskPollInterval ?? 1000;\n try {\n const task = await this._taskStore?.getTask(taskId);\n if (task?.pollInterval) {\n interval = task.pollInterval;\n }\n }\n catch {\n // Use default interval if task lookup fails\n }\n return new Promise((resolve, reject) => {\n if (signal.aborted) {\n reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled'));\n return;\n }\n // Wait for the poll interval, then resolve so caller can check for updates\n const timeoutId = setTimeout(resolve, interval);\n // Clean up timeout and reject if aborted\n signal.addEventListener('abort', () => {\n clearTimeout(timeoutId);\n reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled'));\n }, { once: true });\n });\n }\n requestTaskStore(request, sessionId) {\n const taskStore = this._taskStore;\n if (!taskStore) {\n throw new Error('No task store configured');\n }\n return {\n createTask: async (taskParams) => {\n if (!request) {\n throw new Error('No request provided');\n }\n return await taskStore.createTask(taskParams, request.id, {\n method: request.method,\n params: request.params\n }, sessionId);\n },\n getTask: async (taskId) => {\n const task = await taskStore.getTask(taskId, sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found');\n }\n return task;\n },\n storeTaskResult: async (taskId, status, result) => {\n await taskStore.storeTaskResult(taskId, status, result, sessionId);\n // Get updated task state and send notification\n const task = await taskStore.getTask(taskId, sessionId);\n if (task) {\n const notification = TaskStatusNotificationSchema.parse({\n method: 'notifications/tasks/status',\n params: task\n });\n await this.notification(notification);\n if (isTerminal(task.status)) {\n this._cleanupTaskProgressHandler(taskId);\n // Don't clear queue here - it will be cleared after delivery via tasks/result\n }\n }\n },\n getTaskResult: taskId => {\n return taskStore.getTaskResult(taskId, sessionId);\n },\n updateTaskStatus: async (taskId, status, statusMessage) => {\n // Check if task exists\n const task = await taskStore.getTask(taskId, sessionId);\n if (!task) {\n throw new McpError(ErrorCode.InvalidParams, `Task \"${taskId}\" not found - it may have been cleaned up`);\n }\n // Don't allow transitions from terminal states\n if (isTerminal(task.status)) {\n throw new McpError(ErrorCode.InvalidParams, `Cannot update task \"${taskId}\" from terminal status \"${task.status}\" to \"${status}\". Terminal states (completed, failed, cancelled) cannot transition to other states.`);\n }\n await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);\n // Get updated task state and send notification\n const updatedTask = await taskStore.getTask(taskId, sessionId);\n if (updatedTask) {\n const notification = TaskStatusNotificationSchema.parse({\n method: 'notifications/tasks/status',\n params: updatedTask\n });\n await this.notification(notification);\n if (isTerminal(updatedTask.status)) {\n this._cleanupTaskProgressHandler(taskId);\n // Don't clear queue here - it will be cleared after delivery via tasks/result\n }\n }\n },\n listTasks: cursor => {\n return taskStore.listTasks(cursor, sessionId);\n }\n };\n }\n}\nfunction isPlainObject(value) {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\nexport function mergeCapabilities(base, additional) {\n const result = { ...base };\n for (const key in additional) {\n const k = key;\n const addValue = additional[k];\n if (addValue === undefined)\n continue;\n const baseValue = result[k];\n if (isPlainObject(baseValue) && isPlainObject(addValue)) {\n result[k] = { ...baseValue, ...addValue };\n }\n else {\n result[k] = addValue;\n }\n }\n return result;\n}\n//# sourceMappingURL=protocol.js.map","/**\n * Throwing ajv stub for browser environments.\n *\n * The MCP SDK's Server class statically imports AjvJsonSchemaValidator as a\n * default fallback. BrowserMcpServer always passes PolyfillJsonSchemaValidator,\n * so ajv is never actually used — but the static import still resolves. This\n * stub satisfies that import without pulling in the real ajv (CJS-only, breaks\n * in browsers).\n *\n * If any code path unexpectedly reaches this stub, it throws immediately so the\n * issue is surfaced rather than silently passing all validation.\n */\n\nexport class Ajv {\n compile(_schema: unknown): never {\n throw new Error(\n '[WebMCP] Ajv stub was invoked. This indicates the MCP SDK is bypassing ' +\n 'PolyfillJsonSchemaValidator. Please report this as a bug.'\n );\n }\n\n getSchema(_id: string): undefined {\n return undefined;\n }\n\n errorsText(_errors?: unknown): string {\n return '';\n }\n}\n\nexport default Ajv;\n","/**\n * No-op ajv-formats stub for browser environments.\n * See ./ajv.ts for rationale.\n */\nexport default function addFormats(_ajv: unknown): void {}\n","/**\n * AJV-based JSON Schema validator provider\n */\nimport Ajv from 'ajv';\nimport _addFormats from 'ajv-formats';\nfunction createDefaultAjvInstance() {\n const ajv = new Ajv({\n strict: false,\n validateFormats: true,\n validateSchema: false,\n allErrors: true\n });\n const addFormats = _addFormats;\n addFormats(ajv);\n return ajv;\n}\n/**\n * @example\n * ```typescript\n * // Use with default AJV instance (recommended)\n * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';\n * const validator = new AjvJsonSchemaValidator();\n *\n * // Use with custom AJV instance\n * import { Ajv } from 'ajv';\n * const ajv = new Ajv({ strict: true, allErrors: true });\n * const validator = new AjvJsonSchemaValidator(ajv);\n * ```\n */\nexport class AjvJsonSchemaValidator {\n /**\n * Create an AJV validator\n *\n * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created.\n *\n * @example\n * ```typescript\n * // Use default configuration (recommended for most cases)\n * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';\n * const validator = new AjvJsonSchemaValidator();\n *\n * // Or provide custom AJV instance for advanced configuration\n * import { Ajv } from 'ajv';\n * import addFormats from 'ajv-formats';\n *\n * const ajv = new Ajv({ validateFormats: true });\n * addFormats(ajv);\n * const validator = new AjvJsonSchemaValidator(ajv);\n * ```\n */\n constructor(ajv) {\n this._ajv = ajv ?? createDefaultAjvInstance();\n }\n /**\n * Create a validator for the given JSON Schema\n *\n * The validator is compiled once and can be reused multiple times.\n * If the schema has an $id, it will be cached by AJV automatically.\n *\n * @param schema - Standard JSON Schema object\n * @returns A validator function that validates input data\n */\n getValidator(schema) {\n // Check if schema has $id and is already compiled/cached\n const ajvValidator = '$id' in schema && typeof schema.$id === 'string'\n ? (this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema))\n : this._ajv.compile(schema);\n return (input) => {\n const valid = ajvValidator(input);\n if (valid) {\n return {\n valid: true,\n data: input,\n errorMessage: undefined\n };\n }\n else {\n return {\n valid: false,\n data: undefined,\n errorMessage: this._ajv.errorsText(ajvValidator.errors)\n };\n }\n };\n }\n}\n//# sourceMappingURL=ajv-provider.js.map","/**\n * Experimental client task features for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\nimport { CallToolResultSchema, McpError, ErrorCode } from '../../types.js';\n/**\n * Experimental task features for MCP clients.\n *\n * Access via `client.experimental.tasks`:\n * ```typescript\n * const stream = client.experimental.tasks.callToolStream({ name: 'tool', arguments: {} });\n * const task = await client.experimental.tasks.getTask(taskId);\n * ```\n *\n * @experimental\n */\nexport class ExperimentalClientTasks {\n constructor(_client) {\n this._client = _client;\n }\n /**\n * Calls a tool and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * This method provides streaming access to tool execution, allowing you to\n * observe intermediate task status updates for long-running tool calls.\n * Automatically validates structured output if the tool has an outputSchema.\n *\n * @example\n * ```typescript\n * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });\n * for await (const message of stream) {\n * switch (message.type) {\n * case 'taskCreated':\n * console.log('Tool execution started:', message.task.taskId);\n * break;\n * case 'taskStatus':\n * console.log('Tool status:', message.task.status);\n * break;\n * case 'result':\n * console.log('Tool result:', message.result);\n * break;\n * case 'error':\n * console.error('Tool error:', message.error);\n * break;\n * }\n * }\n * ```\n *\n * @param params - Tool call parameters (name and arguments)\n * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)\n * @param options - Optional request options (timeout, signal, task creation params, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n async *callToolStream(params, resultSchema = CallToolResultSchema, options) {\n // Access Client's internal methods\n const clientInternal = this._client;\n // Add task creation parameters if server supports it and not explicitly provided\n const optionsWithTask = {\n ...options,\n // We check if the tool is known to be a task during auto-configuration, but assume\n // the caller knows what they're doing if they pass this explicitly\n task: options?.task ?? (clientInternal.isToolTask(params.name) ? {} : undefined)\n };\n const stream = clientInternal.requestStream({ method: 'tools/call', params }, resultSchema, optionsWithTask);\n // Get the validator for this tool (if it has an output schema)\n const validator = clientInternal.getToolOutputValidator(params.name);\n // Iterate through the stream and validate the final result if needed\n for await (const message of stream) {\n // If this is a result message and the tool has an output schema, validate it\n if (message.type === 'result' && validator) {\n const result = message.result;\n // If tool has outputSchema, it MUST return structuredContent (unless it's an error)\n if (!result.structuredContent && !result.isError) {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)\n };\n return;\n }\n // Only validate structured content if present (not when there's an error)\n if (result.structuredContent) {\n try {\n // Validate the structured content against the schema\n const validationResult = validator(result.structuredContent);\n if (!validationResult.valid) {\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)\n };\n return;\n }\n }\n catch (error) {\n if (error instanceof McpError) {\n yield { type: 'error', error };\n return;\n }\n yield {\n type: 'error',\n error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`)\n };\n return;\n }\n }\n }\n // Yield the message (either validated result or any other message type)\n yield message;\n }\n }\n /**\n * Gets the current status of a task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n * @returns The task status\n *\n * @experimental\n */\n async getTask(taskId, options) {\n return this._client.getTask({ taskId }, options);\n }\n /**\n * Retrieves the result of a completed task.\n *\n * @param taskId - The task identifier\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options\n * @returns The task result\n *\n * @experimental\n */\n async getTaskResult(taskId, resultSchema, options) {\n // Delegate to the client's underlying Protocol method\n return this._client.getTaskResult({ taskId }, resultSchema, options);\n }\n /**\n * Lists tasks with optional pagination.\n *\n * @param cursor - Optional pagination cursor\n * @param options - Optional request options\n * @returns List of tasks with optional next cursor\n *\n * @experimental\n */\n async listTasks(cursor, options) {\n // Delegate to the client's underlying Protocol method\n return this._client.listTasks(cursor ? { cursor } : undefined, options);\n }\n /**\n * Cancels a running task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n *\n * @experimental\n */\n async cancelTask(taskId, options) {\n // Delegate to the client's underlying Protocol method\n return this._client.cancelTask({ taskId }, options);\n }\n /**\n * Sends a request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * This method provides streaming access to request processing, allowing you to\n * observe intermediate task status updates for task-augmented requests.\n *\n * @param request - The request to send\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options (timeout, signal, task creation params, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n requestStream(request, resultSchema, options) {\n return this._client.requestStream(request, resultSchema, options);\n }\n}\n//# sourceMappingURL=client.js.map","/**\n * Experimental task capability assertion helpers.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n/**\n * Asserts that task creation is supported for tools/call.\n * Used by Client.assertTaskCapability and Server.assertTaskHandlerCapability.\n *\n * @param requests - The task requests capability object\n * @param method - The method being checked\n * @param entityName - 'Server' or 'Client' for error messages\n * @throws Error if the capability is not supported\n *\n * @experimental\n */\nexport function assertToolsCallTaskCapability(requests, method, entityName) {\n if (!requests) {\n throw new Error(`${entityName} does not support task creation (required for ${method})`);\n }\n switch (method) {\n case 'tools/call':\n if (!requests.tools?.call) {\n throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);\n }\n break;\n default:\n // Method doesn't support tasks, which is fine - no error\n break;\n }\n}\n/**\n * Asserts that task creation is supported for sampling/createMessage or elicitation/create.\n * Used by Server.assertTaskCapability and Client.assertTaskHandlerCapability.\n *\n * @param requests - The task requests capability object\n * @param method - The method being checked\n * @param entityName - 'Server' or 'Client' for error messages\n * @throws Error if the capability is not supported\n *\n * @experimental\n */\nexport function assertClientRequestTaskCapability(requests, method, entityName) {\n if (!requests) {\n throw new Error(`${entityName} does not support task creation (required for ${method})`);\n }\n switch (method) {\n case 'sampling/createMessage':\n if (!requests.sampling?.createMessage) {\n throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);\n }\n break;\n case 'elicitation/create':\n if (!requests.elicitation?.create) {\n throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);\n }\n break;\n default:\n // Method doesn't support tasks, which is fine - no error\n break;\n }\n}\n//# sourceMappingURL=helpers.js.map","import { mergeCapabilities, Protocol } from '../shared/protocol.js';\nimport { CallToolResultSchema, CompleteResultSchema, EmptyResultSchema, ErrorCode, GetPromptResultSchema, InitializeResultSchema, LATEST_PROTOCOL_VERSION, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ListToolsResultSchema, McpError, ReadResourceResultSchema, SUPPORTED_PROTOCOL_VERSIONS, ElicitResultSchema, ElicitRequestSchema, CreateTaskResultSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ToolListChangedNotificationSchema, PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, ListChangedOptionsBaseSchema } from '../types.js';\nimport { AjvJsonSchemaValidator } from '../validation/ajv-provider.js';\nimport { getObjectShape, isZ4Schema, safeParse } from '../server/zod-compat.js';\nimport { ExperimentalClientTasks } from '../experimental/tasks/client.js';\nimport { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js';\n/**\n * Elicitation default application helper. Applies defaults to the data based on the schema.\n *\n * @param schema - The schema to apply defaults to.\n * @param data - The data to apply defaults to.\n */\nfunction applyElicitationDefaults(schema, data) {\n if (!schema || data === null || typeof data !== 'object')\n return;\n // Handle object properties\n if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') {\n const obj = data;\n const props = schema.properties;\n for (const key of Object.keys(props)) {\n const propSchema = props[key];\n // If missing or explicitly undefined, apply default if present\n if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) {\n obj[key] = propSchema.default;\n }\n // Recurse into existing nested objects/arrays\n if (obj[key] !== undefined) {\n applyElicitationDefaults(propSchema, obj[key]);\n }\n }\n }\n if (Array.isArray(schema.anyOf)) {\n for (const sub of schema.anyOf) {\n // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)\n if (typeof sub !== 'boolean') {\n applyElicitationDefaults(sub, data);\n }\n }\n }\n // Combine schemas\n if (Array.isArray(schema.oneOf)) {\n for (const sub of schema.oneOf) {\n // Skip boolean schemas (true/false are valid JSON Schemas but have no defaults)\n if (typeof sub !== 'boolean') {\n applyElicitationDefaults(sub, data);\n }\n }\n }\n}\n/**\n * Determines which elicitation modes are supported based on declared client capabilities.\n *\n * According to the spec:\n * - An empty elicitation capability object defaults to form mode support (backwards compatibility)\n * - URL mode is only supported if explicitly declared\n *\n * @param capabilities - The client's elicitation capabilities\n * @returns An object indicating which modes are supported\n */\nexport function getSupportedElicitationModes(capabilities) {\n if (!capabilities) {\n return { supportsFormMode: false, supportsUrlMode: false };\n }\n const hasFormCapability = capabilities.form !== undefined;\n const hasUrlCapability = capabilities.url !== undefined;\n // If neither form nor url are explicitly declared, form mode is supported (backwards compatibility)\n const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability);\n const supportsUrlMode = hasUrlCapability;\n return { supportsFormMode, supportsUrlMode };\n}\n/**\n * An MCP client on top of a pluggable transport.\n *\n * The client will automatically begin the initialization flow with the server when connect() is called.\n *\n * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:\n *\n * ```typescript\n * // Custom schemas\n * const CustomRequestSchema = RequestSchema.extend({...})\n * const CustomNotificationSchema = NotificationSchema.extend({...})\n * const CustomResultSchema = ResultSchema.extend({...})\n *\n * // Type aliases\n * type CustomRequest = z.infer<typeof CustomRequestSchema>\n * type CustomNotification = z.infer<typeof CustomNotificationSchema>\n * type CustomResult = z.infer<typeof CustomResultSchema>\n *\n * // Create typed client\n * const client = new Client<CustomRequest, CustomNotification, CustomResult>({\n * name: \"CustomClient\",\n * version: \"1.0.0\"\n * })\n * ```\n */\nexport class Client extends Protocol {\n /**\n * Initializes this client with the given name and version information.\n */\n constructor(_clientInfo, options) {\n super(options);\n this._clientInfo = _clientInfo;\n this._cachedToolOutputValidators = new Map();\n this._cachedKnownTaskTools = new Set();\n this._cachedRequiredTaskTools = new Set();\n this._listChangedDebounceTimers = new Map();\n this._capabilities = options?.capabilities ?? {};\n this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();\n // Store list changed config for setup after connection (when we know server capabilities)\n if (options?.listChanged) {\n this._pendingListChangedConfig = options.listChanged;\n }\n }\n /**\n * Set up handlers for list changed notifications based on config and server capabilities.\n * This should only be called after initialization when server capabilities are known.\n * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.\n * @internal\n */\n _setupListChangedHandlers(config) {\n if (config.tools && this._serverCapabilities?.tools?.listChanged) {\n this._setupListChangedHandler('tools', ToolListChangedNotificationSchema, config.tools, async () => {\n const result = await this.listTools();\n return result.tools;\n });\n }\n if (config.prompts && this._serverCapabilities?.prompts?.listChanged) {\n this._setupListChangedHandler('prompts', PromptListChangedNotificationSchema, config.prompts, async () => {\n const result = await this.listPrompts();\n return result.prompts;\n });\n }\n if (config.resources && this._serverCapabilities?.resources?.listChanged) {\n this._setupListChangedHandler('resources', ResourceListChangedNotificationSchema, config.resources, async () => {\n const result = await this.listResources();\n return result.resources;\n });\n }\n }\n /**\n * Access experimental features.\n *\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n get experimental() {\n if (!this._experimental) {\n this._experimental = {\n tasks: new ExperimentalClientTasks(this)\n };\n }\n return this._experimental;\n }\n /**\n * Registers new capabilities. This can only be called before connecting to a transport.\n *\n * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).\n */\n registerCapabilities(capabilities) {\n if (this.transport) {\n throw new Error('Cannot register capabilities after connecting to transport');\n }\n this._capabilities = mergeCapabilities(this._capabilities, capabilities);\n }\n /**\n * Override request handler registration to enforce client-side validation for elicitation.\n */\n setRequestHandler(requestSchema, handler) {\n const shape = getObjectShape(requestSchema);\n const methodSchema = shape?.method;\n if (!methodSchema) {\n throw new Error('Schema is missing a method literal');\n }\n // Extract literal value using type-safe property access\n let methodValue;\n if (isZ4Schema(methodSchema)) {\n const v4Schema = methodSchema;\n const v4Def = v4Schema._zod?.def;\n methodValue = v4Def?.value ?? v4Schema.value;\n }\n else {\n const v3Schema = methodSchema;\n const legacyDef = v3Schema._def;\n methodValue = legacyDef?.value ?? v3Schema.value;\n }\n if (typeof methodValue !== 'string') {\n throw new Error('Schema method literal must be a string');\n }\n const method = methodValue;\n if (method === 'elicitation/create') {\n const wrappedHandler = async (request, extra) => {\n const validatedRequest = safeParse(ElicitRequestSchema, request);\n if (!validatedRequest.success) {\n // Type guard: if success is false, error is guaranteed to exist\n const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);\n }\n const { params } = validatedRequest.data;\n params.mode = params.mode ?? 'form';\n const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);\n if (params.mode === 'form' && !supportsFormMode) {\n throw new McpError(ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests');\n }\n if (params.mode === 'url' && !supportsUrlMode) {\n throw new McpError(ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests');\n }\n const result = await Promise.resolve(handler(request, extra));\n // When task creation is requested, validate and return CreateTaskResult\n if (params.task) {\n const taskValidationResult = safeParse(CreateTaskResultSchema, result);\n if (!taskValidationResult.success) {\n const errorMessage = taskValidationResult.error instanceof Error\n ? taskValidationResult.error.message\n : String(taskValidationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);\n }\n return taskValidationResult.data;\n }\n // For non-task requests, validate against ElicitResultSchema\n const validationResult = safeParse(ElicitResultSchema, result);\n if (!validationResult.success) {\n // Type guard: if success is false, error is guaranteed to exist\n const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);\n }\n const validatedResult = validationResult.data;\n const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined;\n if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) {\n if (this._capabilities.elicitation?.form?.applyDefaults) {\n try {\n applyElicitationDefaults(requestedSchema, validatedResult.content);\n }\n catch {\n // gracefully ignore errors in default application\n }\n }\n }\n return validatedResult;\n };\n // Install the wrapped handler\n return super.setRequestHandler(requestSchema, wrappedHandler);\n }\n if (method === 'sampling/createMessage') {\n const wrappedHandler = async (request, extra) => {\n const validatedRequest = safeParse(CreateMessageRequestSchema, request);\n if (!validatedRequest.success) {\n const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);\n }\n const { params } = validatedRequest.data;\n const result = await Promise.resolve(handler(request, extra));\n // When task creation is requested, validate and return CreateTaskResult\n if (params.task) {\n const taskValidationResult = safeParse(CreateTaskResultSchema, result);\n if (!taskValidationResult.success) {\n const errorMessage = taskValidationResult.error instanceof Error\n ? taskValidationResult.error.message\n : String(taskValidationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);\n }\n return taskValidationResult.data;\n }\n // For non-task requests, validate against appropriate schema based on tools presence\n const hasTools = params.tools || params.toolChoice;\n const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;\n const validationResult = safeParse(resultSchema, result);\n if (!validationResult.success) {\n const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);\n }\n return validationResult.data;\n };\n // Install the wrapped handler\n return super.setRequestHandler(requestSchema, wrappedHandler);\n }\n // Other handlers use default behavior\n return super.setRequestHandler(requestSchema, handler);\n }\n assertCapability(capability, method) {\n if (!this._serverCapabilities?.[capability]) {\n throw new Error(`Server does not support ${capability} (required for ${method})`);\n }\n }\n async connect(transport, options) {\n await super.connect(transport);\n // When transport sessionId is already set this means we are trying to reconnect.\n // In this case we don't need to initialize again.\n if (transport.sessionId !== undefined) {\n return;\n }\n try {\n const result = await this.request({\n method: 'initialize',\n params: {\n protocolVersion: LATEST_PROTOCOL_VERSION,\n capabilities: this._capabilities,\n clientInfo: this._clientInfo\n }\n }, InitializeResultSchema, options);\n if (result === undefined) {\n throw new Error(`Server sent invalid initialize result: ${result}`);\n }\n if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {\n throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);\n }\n this._serverCapabilities = result.capabilities;\n this._serverVersion = result.serverInfo;\n // HTTP transports must set the protocol version in each header after initialization.\n if (transport.setProtocolVersion) {\n transport.setProtocolVersion(result.protocolVersion);\n }\n this._instructions = result.instructions;\n await this.notification({\n method: 'notifications/initialized'\n });\n // Set up list changed handlers now that we know server capabilities\n if (this._pendingListChangedConfig) {\n this._setupListChangedHandlers(this._pendingListChangedConfig);\n this._pendingListChangedConfig = undefined;\n }\n }\n catch (error) {\n // Disconnect if initialization fails.\n void this.close();\n throw error;\n }\n }\n /**\n * After initialization has completed, this will be populated with the server's reported capabilities.\n */\n getServerCapabilities() {\n return this._serverCapabilities;\n }\n /**\n * After initialization has completed, this will be populated with information about the server's name and version.\n */\n getServerVersion() {\n return this._serverVersion;\n }\n /**\n * After initialization has completed, this may be populated with information about the server's instructions.\n */\n getInstructions() {\n return this._instructions;\n }\n assertCapabilityForMethod(method) {\n switch (method) {\n case 'logging/setLevel':\n if (!this._serverCapabilities?.logging) {\n throw new Error(`Server does not support logging (required for ${method})`);\n }\n break;\n case 'prompts/get':\n case 'prompts/list':\n if (!this._serverCapabilities?.prompts) {\n throw new Error(`Server does not support prompts (required for ${method})`);\n }\n break;\n case 'resources/list':\n case 'resources/templates/list':\n case 'resources/read':\n case 'resources/subscribe':\n case 'resources/unsubscribe':\n if (!this._serverCapabilities?.resources) {\n throw new Error(`Server does not support resources (required for ${method})`);\n }\n if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) {\n throw new Error(`Server does not support resource subscriptions (required for ${method})`);\n }\n break;\n case 'tools/call':\n case 'tools/list':\n if (!this._serverCapabilities?.tools) {\n throw new Error(`Server does not support tools (required for ${method})`);\n }\n break;\n case 'completion/complete':\n if (!this._serverCapabilities?.completions) {\n throw new Error(`Server does not support completions (required for ${method})`);\n }\n break;\n case 'initialize':\n // No specific capability required for initialize\n break;\n case 'ping':\n // No specific capability required for ping\n break;\n }\n }\n assertNotificationCapability(method) {\n switch (method) {\n case 'notifications/roots/list_changed':\n if (!this._capabilities.roots?.listChanged) {\n throw new Error(`Client does not support roots list changed notifications (required for ${method})`);\n }\n break;\n case 'notifications/initialized':\n // No specific capability required for initialized\n break;\n case 'notifications/cancelled':\n // Cancellation notifications are always allowed\n break;\n case 'notifications/progress':\n // Progress notifications are always allowed\n break;\n }\n }\n assertRequestHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n switch (method) {\n case 'sampling/createMessage':\n if (!this._capabilities.sampling) {\n throw new Error(`Client does not support sampling capability (required for ${method})`);\n }\n break;\n case 'elicitation/create':\n if (!this._capabilities.elicitation) {\n throw new Error(`Client does not support elicitation capability (required for ${method})`);\n }\n break;\n case 'roots/list':\n if (!this._capabilities.roots) {\n throw new Error(`Client does not support roots capability (required for ${method})`);\n }\n break;\n case 'tasks/get':\n case 'tasks/list':\n case 'tasks/result':\n case 'tasks/cancel':\n if (!this._capabilities.tasks) {\n throw new Error(`Client does not support tasks capability (required for ${method})`);\n }\n break;\n case 'ping':\n // No specific capability required for ping\n break;\n }\n }\n assertTaskCapability(method) {\n assertToolsCallTaskCapability(this._serverCapabilities?.tasks?.requests, method, 'Server');\n }\n assertTaskHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n assertClientRequestTaskCapability(this._capabilities.tasks?.requests, method, 'Client');\n }\n async ping(options) {\n return this.request({ method: 'ping' }, EmptyResultSchema, options);\n }\n async complete(params, options) {\n return this.request({ method: 'completion/complete', params }, CompleteResultSchema, options);\n }\n async setLoggingLevel(level, options) {\n return this.request({ method: 'logging/setLevel', params: { level } }, EmptyResultSchema, options);\n }\n async getPrompt(params, options) {\n return this.request({ method: 'prompts/get', params }, GetPromptResultSchema, options);\n }\n async listPrompts(params, options) {\n return this.request({ method: 'prompts/list', params }, ListPromptsResultSchema, options);\n }\n async listResources(params, options) {\n return this.request({ method: 'resources/list', params }, ListResourcesResultSchema, options);\n }\n async listResourceTemplates(params, options) {\n return this.request({ method: 'resources/templates/list', params }, ListResourceTemplatesResultSchema, options);\n }\n async readResource(params, options) {\n return this.request({ method: 'resources/read', params }, ReadResourceResultSchema, options);\n }\n async subscribeResource(params, options) {\n return this.request({ method: 'resources/subscribe', params }, EmptyResultSchema, options);\n }\n async unsubscribeResource(params, options) {\n return this.request({ method: 'resources/unsubscribe', params }, EmptyResultSchema, options);\n }\n /**\n * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.\n *\n * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.\n */\n async callTool(params, resultSchema = CallToolResultSchema, options) {\n // Guard: required-task tools need experimental API\n if (this.isToolTaskRequired(params.name)) {\n throw new McpError(ErrorCode.InvalidRequest, `Tool \"${params.name}\" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);\n }\n const result = await this.request({ method: 'tools/call', params }, resultSchema, options);\n // Check if the tool has an outputSchema\n const validator = this.getToolOutputValidator(params.name);\n if (validator) {\n // If tool has outputSchema, it MUST return structuredContent (unless it's an error)\n if (!result.structuredContent && !result.isError) {\n throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);\n }\n // Only validate structured content if present (not when there's an error)\n if (result.structuredContent) {\n try {\n // Validate the structured content against the schema\n const validationResult = validator(result.structuredContent);\n if (!validationResult.valid) {\n throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);\n }\n }\n catch (error) {\n if (error instanceof McpError) {\n throw error;\n }\n throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n }\n return result;\n }\n isToolTask(toolName) {\n if (!this._serverCapabilities?.tasks?.requests?.tools?.call) {\n return false;\n }\n return this._cachedKnownTaskTools.has(toolName);\n }\n /**\n * Check if a tool requires task-based execution.\n * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.\n */\n isToolTaskRequired(toolName) {\n return this._cachedRequiredTaskTools.has(toolName);\n }\n /**\n * Cache validators for tool output schemas.\n * Called after listTools() to pre-compile validators for better performance.\n */\n cacheToolMetadata(tools) {\n this._cachedToolOutputValidators.clear();\n this._cachedKnownTaskTools.clear();\n this._cachedRequiredTaskTools.clear();\n for (const tool of tools) {\n // If the tool has an outputSchema, create and cache the validator\n if (tool.outputSchema) {\n const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);\n this._cachedToolOutputValidators.set(tool.name, toolValidator);\n }\n // If the tool supports task-based execution, cache that information\n const taskSupport = tool.execution?.taskSupport;\n if (taskSupport === 'required' || taskSupport === 'optional') {\n this._cachedKnownTaskTools.add(tool.name);\n }\n if (taskSupport === 'required') {\n this._cachedRequiredTaskTools.add(tool.name);\n }\n }\n }\n /**\n * Get cached validator for a tool\n */\n getToolOutputValidator(toolName) {\n return this._cachedToolOutputValidators.get(toolName);\n }\n async listTools(params, options) {\n const result = await this.request({ method: 'tools/list', params }, ListToolsResultSchema, options);\n // Cache the tools and their output schemas for future validation\n this.cacheToolMetadata(result.tools);\n return result;\n }\n /**\n * Set up a single list changed handler.\n * @internal\n */\n _setupListChangedHandler(listType, notificationSchema, options, fetcher) {\n // Validate options using Zod schema (validates autoRefresh and debounceMs)\n const parseResult = ListChangedOptionsBaseSchema.safeParse(options);\n if (!parseResult.success) {\n throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);\n }\n // Validate callback\n if (typeof options.onChanged !== 'function') {\n throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);\n }\n const { autoRefresh, debounceMs } = parseResult.data;\n const { onChanged } = options;\n const refresh = async () => {\n if (!autoRefresh) {\n onChanged(null, null);\n return;\n }\n try {\n const items = await fetcher();\n onChanged(null, items);\n }\n catch (e) {\n const error = e instanceof Error ? e : new Error(String(e));\n onChanged(error, null);\n }\n };\n const handler = () => {\n if (debounceMs) {\n // Clear any pending debounce timer for this list type\n const existingTimer = this._listChangedDebounceTimers.get(listType);\n if (existingTimer) {\n clearTimeout(existingTimer);\n }\n // Set up debounced refresh\n const timer = setTimeout(refresh, debounceMs);\n this._listChangedDebounceTimers.set(listType, timer);\n }\n else {\n // No debounce, refresh immediately\n refresh();\n }\n };\n // Register notification handler\n this.setNotificationHandler(notificationSchema, handler);\n }\n async sendRootsListChanged() {\n return this.notification({ method: 'notifications/roots/list_changed' });\n }\n}\n//# sourceMappingURL=index.js.map","import { JSONRPCMessageSchema } from '../types.js';\n/**\n * Buffers a continuous stdio stream into discrete JSON-RPC messages.\n */\nexport class ReadBuffer {\n append(chunk) {\n this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;\n }\n readMessage() {\n if (!this._buffer) {\n return null;\n }\n const index = this._buffer.indexOf('\\n');\n if (index === -1) {\n return null;\n }\n const line = this._buffer.toString('utf8', 0, index).replace(/\\r$/, '');\n this._buffer = this._buffer.subarray(index + 1);\n return deserializeMessage(line);\n }\n clear() {\n this._buffer = undefined;\n }\n}\nexport function deserializeMessage(line) {\n return JSONRPCMessageSchema.parse(JSON.parse(line));\n}\nexport function serializeMessage(message) {\n return JSON.stringify(message) + '\\n';\n}\n//# sourceMappingURL=stdio.js.map","/**\n * Experimental server task features for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n/**\n * Experimental task features for low-level MCP servers.\n *\n * Access via `server.experimental.tasks`:\n * ```typescript\n * const stream = server.experimental.tasks.requestStream(request, schema, options);\n * ```\n *\n * For high-level server usage with task-based tools, use `McpServer.experimental.tasks` instead.\n *\n * @experimental\n */\nexport class ExperimentalServerTasks {\n constructor(_server) {\n this._server = _server;\n }\n /**\n * Sends a request and returns an AsyncGenerator that yields response messages.\n * The generator is guaranteed to end with either a 'result' or 'error' message.\n *\n * This method provides streaming access to request processing, allowing you to\n * observe intermediate task status updates for task-augmented requests.\n *\n * @param request - The request to send\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options (timeout, signal, task creation params, etc.)\n * @returns AsyncGenerator that yields ResponseMessage objects\n *\n * @experimental\n */\n requestStream(request, resultSchema, options) {\n return this._server.requestStream(request, resultSchema, options);\n }\n /**\n * Gets the current status of a task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n * @returns The task status\n *\n * @experimental\n */\n async getTask(taskId, options) {\n return this._server.getTask({ taskId }, options);\n }\n /**\n * Retrieves the result of a completed task.\n *\n * @param taskId - The task identifier\n * @param resultSchema - Zod schema for validating the result\n * @param options - Optional request options\n * @returns The task result\n *\n * @experimental\n */\n async getTaskResult(taskId, resultSchema, options) {\n return this._server.getTaskResult({ taskId }, resultSchema, options);\n }\n /**\n * Lists tasks with optional pagination.\n *\n * @param cursor - Optional pagination cursor\n * @param options - Optional request options\n * @returns List of tasks with optional next cursor\n *\n * @experimental\n */\n async listTasks(cursor, options) {\n return this._server.listTasks(cursor ? { cursor } : undefined, options);\n }\n /**\n * Cancels a running task.\n *\n * @param taskId - The task identifier\n * @param options - Optional request options\n *\n * @experimental\n */\n async cancelTask(taskId, options) {\n return this._server.cancelTask({ taskId }, options);\n }\n}\n//# sourceMappingURL=server.js.map","import { mergeCapabilities, Protocol } from '../shared/protocol.js';\nimport { CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ElicitResultSchema, EmptyResultSchema, ErrorCode, InitializedNotificationSchema, InitializeRequestSchema, LATEST_PROTOCOL_VERSION, ListRootsResultSchema, LoggingLevelSchema, McpError, SetLevelRequestSchema, SUPPORTED_PROTOCOL_VERSIONS, CallToolRequestSchema, CallToolResultSchema, CreateTaskResultSchema } from '../types.js';\nimport { AjvJsonSchemaValidator } from '../validation/ajv-provider.js';\nimport { getObjectShape, isZ4Schema, safeParse } from './zod-compat.js';\nimport { ExperimentalServerTasks } from '../experimental/tasks/server.js';\nimport { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js';\n/**\n * An MCP server on top of a pluggable transport.\n *\n * This server will automatically respond to the initialization flow as initiated from the client.\n *\n * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters:\n *\n * ```typescript\n * // Custom schemas\n * const CustomRequestSchema = RequestSchema.extend({...})\n * const CustomNotificationSchema = NotificationSchema.extend({...})\n * const CustomResultSchema = ResultSchema.extend({...})\n *\n * // Type aliases\n * type CustomRequest = z.infer<typeof CustomRequestSchema>\n * type CustomNotification = z.infer<typeof CustomNotificationSchema>\n * type CustomResult = z.infer<typeof CustomResultSchema>\n *\n * // Create typed server\n * const server = new Server<CustomRequest, CustomNotification, CustomResult>({\n * name: \"CustomServer\",\n * version: \"1.0.0\"\n * })\n * ```\n * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases.\n */\nexport class Server extends Protocol {\n /**\n * Initializes this server with the given name and version information.\n */\n constructor(_serverInfo, options) {\n super(options);\n this._serverInfo = _serverInfo;\n // Map log levels by session id\n this._loggingLevels = new Map();\n // Map LogLevelSchema to severity index\n this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index]));\n // Is a message with the given level ignored in the log level set for the given session id?\n this.isMessageIgnored = (level, sessionId) => {\n const currentLevel = this._loggingLevels.get(sessionId);\n return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false;\n };\n this._capabilities = options?.capabilities ?? {};\n this._instructions = options?.instructions;\n this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator();\n this.setRequestHandler(InitializeRequestSchema, request => this._oninitialize(request));\n this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.());\n if (this._capabilities.logging) {\n this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => {\n const transportSessionId = extra.sessionId || extra.requestInfo?.headers['mcp-session-id'] || undefined;\n const { level } = request.params;\n const parseResult = LoggingLevelSchema.safeParse(level);\n if (parseResult.success) {\n this._loggingLevels.set(transportSessionId, parseResult.data);\n }\n return {};\n });\n }\n }\n /**\n * Access experimental features.\n *\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n get experimental() {\n if (!this._experimental) {\n this._experimental = {\n tasks: new ExperimentalServerTasks(this)\n };\n }\n return this._experimental;\n }\n /**\n * Registers new capabilities. This can only be called before connecting to a transport.\n *\n * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).\n */\n registerCapabilities(capabilities) {\n if (this.transport) {\n throw new Error('Cannot register capabilities after connecting to transport');\n }\n this._capabilities = mergeCapabilities(this._capabilities, capabilities);\n }\n /**\n * Override request handler registration to enforce server-side validation for tools/call.\n */\n setRequestHandler(requestSchema, handler) {\n const shape = getObjectShape(requestSchema);\n const methodSchema = shape?.method;\n if (!methodSchema) {\n throw new Error('Schema is missing a method literal');\n }\n // Extract literal value using type-safe property access\n let methodValue;\n if (isZ4Schema(methodSchema)) {\n const v4Schema = methodSchema;\n const v4Def = v4Schema._zod?.def;\n methodValue = v4Def?.value ?? v4Schema.value;\n }\n else {\n const v3Schema = methodSchema;\n const legacyDef = v3Schema._def;\n methodValue = legacyDef?.value ?? v3Schema.value;\n }\n if (typeof methodValue !== 'string') {\n throw new Error('Schema method literal must be a string');\n }\n const method = methodValue;\n if (method === 'tools/call') {\n const wrappedHandler = async (request, extra) => {\n const validatedRequest = safeParse(CallToolRequestSchema, request);\n if (!validatedRequest.success) {\n const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call request: ${errorMessage}`);\n }\n const { params } = validatedRequest.data;\n const result = await Promise.resolve(handler(request, extra));\n // When task creation is requested, validate and return CreateTaskResult\n if (params.task) {\n const taskValidationResult = safeParse(CreateTaskResultSchema, result);\n if (!taskValidationResult.success) {\n const errorMessage = taskValidationResult.error instanceof Error\n ? taskValidationResult.error.message\n : String(taskValidationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);\n }\n return taskValidationResult.data;\n }\n // For non-task requests, validate against CallToolResultSchema\n const validationResult = safeParse(CallToolResultSchema, result);\n if (!validationResult.success) {\n const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`);\n }\n return validationResult.data;\n };\n // Install the wrapped handler\n return super.setRequestHandler(requestSchema, wrappedHandler);\n }\n // Other handlers use default behavior\n return super.setRequestHandler(requestSchema, handler);\n }\n assertCapabilityForMethod(method) {\n switch (method) {\n case 'sampling/createMessage':\n if (!this._clientCapabilities?.sampling) {\n throw new Error(`Client does not support sampling (required for ${method})`);\n }\n break;\n case 'elicitation/create':\n if (!this._clientCapabilities?.elicitation) {\n throw new Error(`Client does not support elicitation (required for ${method})`);\n }\n break;\n case 'roots/list':\n if (!this._clientCapabilities?.roots) {\n throw new Error(`Client does not support listing roots (required for ${method})`);\n }\n break;\n case 'ping':\n // No specific capability required for ping\n break;\n }\n }\n assertNotificationCapability(method) {\n switch (method) {\n case 'notifications/message':\n if (!this._capabilities.logging) {\n throw new Error(`Server does not support logging (required for ${method})`);\n }\n break;\n case 'notifications/resources/updated':\n case 'notifications/resources/list_changed':\n if (!this._capabilities.resources) {\n throw new Error(`Server does not support notifying about resources (required for ${method})`);\n }\n break;\n case 'notifications/tools/list_changed':\n if (!this._capabilities.tools) {\n throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);\n }\n break;\n case 'notifications/prompts/list_changed':\n if (!this._capabilities.prompts) {\n throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);\n }\n break;\n case 'notifications/elicitation/complete':\n if (!this._clientCapabilities?.elicitation?.url) {\n throw new Error(`Client does not support URL elicitation (required for ${method})`);\n }\n break;\n case 'notifications/cancelled':\n // Cancellation notifications are always allowed\n break;\n case 'notifications/progress':\n // Progress notifications are always allowed\n break;\n }\n }\n assertRequestHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n switch (method) {\n case 'completion/complete':\n if (!this._capabilities.completions) {\n throw new Error(`Server does not support completions (required for ${method})`);\n }\n break;\n case 'logging/setLevel':\n if (!this._capabilities.logging) {\n throw new Error(`Server does not support logging (required for ${method})`);\n }\n break;\n case 'prompts/get':\n case 'prompts/list':\n if (!this._capabilities.prompts) {\n throw new Error(`Server does not support prompts (required for ${method})`);\n }\n break;\n case 'resources/list':\n case 'resources/templates/list':\n case 'resources/read':\n if (!this._capabilities.resources) {\n throw new Error(`Server does not support resources (required for ${method})`);\n }\n break;\n case 'tools/call':\n case 'tools/list':\n if (!this._capabilities.tools) {\n throw new Error(`Server does not support tools (required for ${method})`);\n }\n break;\n case 'tasks/get':\n case 'tasks/list':\n case 'tasks/result':\n case 'tasks/cancel':\n if (!this._capabilities.tasks) {\n throw new Error(`Server does not support tasks capability (required for ${method})`);\n }\n break;\n case 'ping':\n case 'initialize':\n // No specific capability required for these methods\n break;\n }\n }\n assertTaskCapability(method) {\n assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, 'Client');\n }\n assertTaskHandlerCapability(method) {\n // Task handlers are registered in Protocol constructor before _capabilities is initialized\n // Skip capability check for task methods during initialization\n if (!this._capabilities) {\n return;\n }\n assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, 'Server');\n }\n async _oninitialize(request) {\n const requestedVersion = request.params.protocolVersion;\n this._clientCapabilities = request.params.capabilities;\n this._clientVersion = request.params.clientInfo;\n const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION;\n return {\n protocolVersion,\n capabilities: this.getCapabilities(),\n serverInfo: this._serverInfo,\n ...(this._instructions && { instructions: this._instructions })\n };\n }\n /**\n * After initialization has completed, this will be populated with the client's reported capabilities.\n */\n getClientCapabilities() {\n return this._clientCapabilities;\n }\n /**\n * After initialization has completed, this will be populated with information about the client's name and version.\n */\n getClientVersion() {\n return this._clientVersion;\n }\n getCapabilities() {\n return this._capabilities;\n }\n async ping() {\n return this.request({ method: 'ping' }, EmptyResultSchema);\n }\n // Implementation\n async createMessage(params, options) {\n // Capability check - only required when tools/toolChoice are provided\n if (params.tools || params.toolChoice) {\n if (!this._clientCapabilities?.sampling?.tools) {\n throw new Error('Client does not support sampling tools capability.');\n }\n }\n // Message structure validation - always validate tool_use/tool_result pairs.\n // These may appear even without tools/toolChoice in the current request when\n // a previous sampling request returned tool_use and this is a follow-up with results.\n if (params.messages.length > 0) {\n const lastMessage = params.messages[params.messages.length - 1];\n const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];\n const hasToolResults = lastContent.some(c => c.type === 'tool_result');\n const previousMessage = params.messages.length > 1 ? params.messages[params.messages.length - 2] : undefined;\n const previousContent = previousMessage\n ? Array.isArray(previousMessage.content)\n ? previousMessage.content\n : [previousMessage.content]\n : [];\n const hasPreviousToolUse = previousContent.some(c => c.type === 'tool_use');\n if (hasToolResults) {\n if (lastContent.some(c => c.type !== 'tool_result')) {\n throw new Error('The last message must contain only tool_result content if any is present');\n }\n if (!hasPreviousToolUse) {\n throw new Error('tool_result blocks are not matching any tool_use from the previous message');\n }\n }\n if (hasPreviousToolUse) {\n const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => c.id));\n const toolResultIds = new Set(lastContent.filter(c => c.type === 'tool_result').map(c => c.toolUseId));\n if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) {\n throw new Error('ids of tool_result blocks and tool_use blocks from previous message do not match');\n }\n }\n }\n // Use different schemas based on whether tools are provided\n if (params.tools) {\n return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultWithToolsSchema, options);\n }\n return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultSchema, options);\n }\n /**\n * Creates an elicitation request for the given parameters.\n * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`.\n * @param params The parameters for the elicitation request.\n * @param options Optional request options.\n * @returns The result of the elicitation request.\n */\n async elicitInput(params, options) {\n const mode = (params.mode ?? 'form');\n switch (mode) {\n case 'url': {\n if (!this._clientCapabilities?.elicitation?.url) {\n throw new Error('Client does not support url elicitation.');\n }\n const urlParams = params;\n return this.request({ method: 'elicitation/create', params: urlParams }, ElicitResultSchema, options);\n }\n case 'form': {\n if (!this._clientCapabilities?.elicitation?.form) {\n throw new Error('Client does not support form elicitation.');\n }\n const formParams = params.mode === 'form' ? params : { ...params, mode: 'form' };\n const result = await this.request({ method: 'elicitation/create', params: formParams }, ElicitResultSchema, options);\n if (result.action === 'accept' && result.content && formParams.requestedSchema) {\n try {\n const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema);\n const validationResult = validator(result.content);\n if (!validationResult.valid) {\n throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`);\n }\n }\n catch (error) {\n if (error instanceof McpError) {\n throw error;\n }\n throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n return result;\n }\n }\n }\n /**\n * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete`\n * notification for the specified elicitation ID.\n *\n * @param elicitationId The ID of the elicitation to mark as complete.\n * @param options Optional notification options. Useful when the completion notification should be related to a prior request.\n * @returns A function that emits the completion notification when awaited.\n */\n createElicitationCompletionNotifier(elicitationId, options) {\n if (!this._clientCapabilities?.elicitation?.url) {\n throw new Error('Client does not support URL elicitation (required for notifications/elicitation/complete)');\n }\n return () => this.notification({\n method: 'notifications/elicitation/complete',\n params: {\n elicitationId\n }\n }, options);\n }\n async listRoots(params, options) {\n return this.request({ method: 'roots/list', params }, ListRootsResultSchema, options);\n }\n /**\n * Sends a logging message to the client, if connected.\n * Note: You only need to send the parameters object, not the entire JSON RPC message\n * @see LoggingMessageNotification\n * @param params\n * @param sessionId optional for stateless and backward compatibility\n */\n async sendLoggingMessage(params, sessionId) {\n if (this._capabilities.logging) {\n if (!this.isMessageIgnored(params.level, sessionId)) {\n return this.notification({ method: 'notifications/message', params });\n }\n }\n }\n async sendResourceUpdated(params) {\n return this.notification({\n method: 'notifications/resources/updated',\n params\n });\n }\n async sendResourceListChanged() {\n return this.notification({\n method: 'notifications/resources/list_changed'\n });\n }\n async sendToolListChanged() {\n return this.notification({ method: 'notifications/tools/list_changed' });\n }\n async sendPromptListChanged() {\n return this.notification({ method: 'notifications/prompts/list_changed' });\n }\n}\n//# sourceMappingURL=index.js.map","export const COMPLETABLE_SYMBOL = Symbol.for('mcp.completable');\n/**\n * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP.\n * Works with both Zod v3 and v4 schemas.\n */\nexport function completable(schema, complete) {\n Object.defineProperty(schema, COMPLETABLE_SYMBOL, {\n value: { complete },\n enumerable: false,\n writable: false,\n configurable: false\n });\n return schema;\n}\n/**\n * Checks if a schema is completable (has completion metadata).\n */\nexport function isCompletable(schema) {\n return !!schema && typeof schema === 'object' && COMPLETABLE_SYMBOL in schema;\n}\n/**\n * Gets the completer callback from a completable schema, if it exists.\n */\nexport function getCompleter(schema) {\n const meta = schema[COMPLETABLE_SYMBOL];\n return meta?.complete;\n}\n/**\n * Unwraps a completable schema to get the underlying schema.\n * For backward compatibility with code that called `.unwrap()`.\n */\nexport function unwrapCompletable(schema) {\n return schema;\n}\n// Legacy exports for backward compatibility\n// These types are deprecated but kept for existing code\nexport var McpZodTypeKind;\n(function (McpZodTypeKind) {\n McpZodTypeKind[\"Completable\"] = \"McpCompletable\";\n})(McpZodTypeKind || (McpZodTypeKind = {}));\n//# sourceMappingURL=completable.js.map","/**\n * Tool name validation utilities according to SEP: Specify Format for Tool Names\n *\n * Tool names SHOULD be between 1 and 128 characters in length (inclusive).\n * Tool names are case-sensitive.\n * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits\n * (0-9), underscore (_), dash (-), and dot (.).\n * Tool names SHOULD NOT contain spaces, commas, or other special characters.\n */\n/**\n * Regular expression for valid tool names according to SEP-986 specification\n */\nconst TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;\n/**\n * Validates a tool name according to the SEP specification\n * @param name - The tool name to validate\n * @returns An object containing validation result and any warnings\n */\nexport function validateToolName(name) {\n const warnings = [];\n // Check length\n if (name.length === 0) {\n return {\n isValid: false,\n warnings: ['Tool name cannot be empty']\n };\n }\n if (name.length > 128) {\n return {\n isValid: false,\n warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`]\n };\n }\n // Check for specific problematic patterns (these are warnings, not validation failures)\n if (name.includes(' ')) {\n warnings.push('Tool name contains spaces, which may cause parsing issues');\n }\n if (name.includes(',')) {\n warnings.push('Tool name contains commas, which may cause parsing issues');\n }\n // Check for potentially confusing patterns (leading/trailing dashes, dots, slashes)\n if (name.startsWith('-') || name.endsWith('-')) {\n warnings.push('Tool name starts or ends with a dash, which may cause parsing issues in some contexts');\n }\n if (name.startsWith('.') || name.endsWith('.')) {\n warnings.push('Tool name starts or ends with a dot, which may cause parsing issues in some contexts');\n }\n // Check for invalid characters\n if (!TOOL_NAME_REGEX.test(name)) {\n const invalidChars = name\n .split('')\n .filter(char => !/[A-Za-z0-9._-]/.test(char))\n .filter((char, index, arr) => arr.indexOf(char) === index); // Remove duplicates\n warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c => `\"${c}\"`).join(', ')}`, 'Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)');\n return {\n isValid: false,\n warnings\n };\n }\n return {\n isValid: true,\n warnings\n };\n}\n/**\n * Issues warnings for non-conforming tool names\n * @param name - The tool name that triggered the warnings\n * @param warnings - Array of warning messages\n */\nexport function issueToolNameWarning(name, warnings) {\n if (warnings.length > 0) {\n console.warn(`Tool name validation warning for \"${name}\":`);\n for (const warning of warnings) {\n console.warn(` - ${warning}`);\n }\n console.warn('Tool registration will proceed, but this may cause compatibility issues.');\n console.warn('Consider updating the tool name to conform to the MCP tool naming standard.');\n console.warn('See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.');\n }\n}\n/**\n * Validates a tool name and issues warnings for non-conforming names\n * @param name - The tool name to validate\n * @returns true if the name is valid, false otherwise\n */\nexport function validateAndWarnToolName(name) {\n const result = validateToolName(name);\n // Always issue warnings for any validation issues (both invalid names and warnings)\n issueToolNameWarning(name, result.warnings);\n return result.isValid;\n}\n//# sourceMappingURL=toolNameValidation.js.map","/**\n * Experimental McpServer task features for MCP SDK.\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n/**\n * Experimental task features for McpServer.\n *\n * Access via `server.experimental.tasks`:\n * ```typescript\n * server.experimental.tasks.registerToolTask('long-running', config, handler);\n * ```\n *\n * @experimental\n */\nexport class ExperimentalMcpServerTasks {\n constructor(_mcpServer) {\n this._mcpServer = _mcpServer;\n }\n registerToolTask(name, config, handler) {\n // Validate that taskSupport is not 'forbidden' for task-based tools\n const execution = { taskSupport: 'required', ...config.execution };\n if (execution.taskSupport === 'forbidden') {\n throw new Error(`Cannot register task-based tool '${name}' with taskSupport 'forbidden'. Use registerTool() instead.`);\n }\n // Access McpServer's internal _createRegisteredTool method\n const mcpServerInternal = this._mcpServer;\n return mcpServerInternal._createRegisteredTool(name, config.title, config.description, config.inputSchema, config.outputSchema, config.annotations, execution, config._meta, handler);\n }\n}\n//# sourceMappingURL=mcp-server.js.map","import { Server } from './index.js';\nimport { normalizeObjectSchema, safeParseAsync, getObjectShape, objectFromShape, getParseErrorMessage, getSchemaDescription, isSchemaOptional, getLiteralValue } from './zod-compat.js';\nimport { toJsonSchemaCompat } from './zod-json-schema-compat.js';\nimport { McpError, ErrorCode, ListResourceTemplatesRequestSchema, ReadResourceRequestSchema, ListToolsRequestSchema, CallToolRequestSchema, ListResourcesRequestSchema, ListPromptsRequestSchema, GetPromptRequestSchema, CompleteRequestSchema, assertCompleteRequestPrompt, assertCompleteRequestResourceTemplate } from '../types.js';\nimport { isCompletable, getCompleter } from './completable.js';\nimport { UriTemplate } from '../shared/uriTemplate.js';\nimport { validateAndWarnToolName } from '../shared/toolNameValidation.js';\nimport { ExperimentalMcpServerTasks } from '../experimental/tasks/mcp-server.js';\nimport { ZodOptional } from 'zod';\n/**\n * High-level MCP server that provides a simpler API for working with resources, tools, and prompts.\n * For advanced usage (like sending notifications or setting custom request handlers), use the underlying\n * Server instance available via the `server` property.\n */\nexport class McpServer {\n constructor(serverInfo, options) {\n this._registeredResources = {};\n this._registeredResourceTemplates = {};\n this._registeredTools = {};\n this._registeredPrompts = {};\n this._toolHandlersInitialized = false;\n this._completionHandlerInitialized = false;\n this._resourceHandlersInitialized = false;\n this._promptHandlersInitialized = false;\n this.server = new Server(serverInfo, options);\n }\n /**\n * Access experimental features.\n *\n * WARNING: These APIs are experimental and may change without notice.\n *\n * @experimental\n */\n get experimental() {\n if (!this._experimental) {\n this._experimental = {\n tasks: new ExperimentalMcpServerTasks(this)\n };\n }\n return this._experimental;\n }\n /**\n * Attaches to the given transport, starts it, and starts listening for messages.\n *\n * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.\n */\n async connect(transport) {\n return await this.server.connect(transport);\n }\n /**\n * Closes the connection.\n */\n async close() {\n await this.server.close();\n }\n setToolRequestHandlers() {\n if (this._toolHandlersInitialized) {\n return;\n }\n this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema));\n this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema));\n this.server.registerCapabilities({\n tools: {\n listChanged: true\n }\n });\n this.server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: Object.entries(this._registeredTools)\n .filter(([, tool]) => tool.enabled)\n .map(([name, tool]) => {\n const toolDefinition = {\n name,\n title: tool.title,\n description: tool.description,\n inputSchema: (() => {\n const obj = normalizeObjectSchema(tool.inputSchema);\n return obj\n ? toJsonSchemaCompat(obj, {\n strictUnions: true,\n pipeStrategy: 'input'\n })\n : EMPTY_OBJECT_JSON_SCHEMA;\n })(),\n annotations: tool.annotations,\n execution: tool.execution,\n _meta: tool._meta\n };\n if (tool.outputSchema) {\n const obj = normalizeObjectSchema(tool.outputSchema);\n if (obj) {\n toolDefinition.outputSchema = toJsonSchemaCompat(obj, {\n strictUnions: true,\n pipeStrategy: 'output'\n });\n }\n }\n return toolDefinition;\n })\n }));\n this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {\n try {\n const tool = this._registeredTools[request.params.name];\n if (!tool) {\n throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`);\n }\n if (!tool.enabled) {\n throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);\n }\n const isTaskRequest = !!request.params.task;\n const taskSupport = tool.execution?.taskSupport;\n const isTaskHandler = 'createTask' in tool.handler;\n // Validate task hint configuration\n if ((taskSupport === 'required' || taskSupport === 'optional') && !isTaskHandler) {\n throw new McpError(ErrorCode.InternalError, `Tool ${request.params.name} has taskSupport '${taskSupport}' but was not registered with registerToolTask`);\n }\n // Handle taskSupport 'required' without task augmentation\n if (taskSupport === 'required' && !isTaskRequest) {\n throw new McpError(ErrorCode.MethodNotFound, `Tool ${request.params.name} requires task augmentation (taskSupport: 'required')`);\n }\n // Handle taskSupport 'optional' without task augmentation - automatic polling\n if (taskSupport === 'optional' && !isTaskRequest && isTaskHandler) {\n return await this.handleAutomaticTaskPolling(tool, request, extra);\n }\n // Normal execution path\n const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);\n const result = await this.executeToolHandler(tool, args, extra);\n // Return CreateTaskResult immediately for task requests\n if (isTaskRequest) {\n return result;\n }\n // Validate output schema for non-task requests\n await this.validateToolOutput(tool, result, request.params.name);\n return result;\n }\n catch (error) {\n if (error instanceof McpError) {\n if (error.code === ErrorCode.UrlElicitationRequired) {\n throw error; // Return the error to the caller without wrapping in CallToolResult\n }\n }\n return this.createToolError(error instanceof Error ? error.message : String(error));\n }\n });\n this._toolHandlersInitialized = true;\n }\n /**\n * Creates a tool error result.\n *\n * @param errorMessage - The error message.\n * @returns The tool error result.\n */\n createToolError(errorMessage) {\n return {\n content: [\n {\n type: 'text',\n text: errorMessage\n }\n ],\n isError: true\n };\n }\n /**\n * Validates tool input arguments against the tool's input schema.\n */\n async validateToolInput(tool, args, toolName) {\n if (!tool.inputSchema) {\n return undefined;\n }\n // Try to normalize to object schema first (for raw shapes and object schemas)\n // If that fails, use the schema directly (for union/intersection/etc)\n const inputObj = normalizeObjectSchema(tool.inputSchema);\n const schemaToParse = inputObj ?? tool.inputSchema;\n const parseResult = await safeParseAsync(schemaToParse, args);\n if (!parseResult.success) {\n const error = 'error' in parseResult ? parseResult.error : 'Unknown error';\n const errorMessage = getParseErrorMessage(error);\n throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${errorMessage}`);\n }\n return parseResult.data;\n }\n /**\n * Validates tool output against the tool's output schema.\n */\n async validateToolOutput(tool, result, toolName) {\n if (!tool.outputSchema) {\n return;\n }\n // Only validate CallToolResult, not CreateTaskResult\n if (!('content' in result)) {\n return;\n }\n if (result.isError) {\n return;\n }\n if (!result.structuredContent) {\n throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`);\n }\n // if the tool has an output schema, validate structured content\n const outputObj = normalizeObjectSchema(tool.outputSchema);\n const parseResult = await safeParseAsync(outputObj, result.structuredContent);\n if (!parseResult.success) {\n const error = 'error' in parseResult ? parseResult.error : 'Unknown error';\n const errorMessage = getParseErrorMessage(error);\n throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${errorMessage}`);\n }\n }\n /**\n * Executes a tool handler (either regular or task-based).\n */\n async executeToolHandler(tool, args, extra) {\n const handler = tool.handler;\n const isTaskHandler = 'createTask' in handler;\n if (isTaskHandler) {\n if (!extra.taskStore) {\n throw new Error('No task store provided.');\n }\n const taskExtra = { ...extra, taskStore: extra.taskStore };\n if (tool.inputSchema) {\n const typedHandler = handler;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return await Promise.resolve(typedHandler.createTask(args, taskExtra));\n }\n else {\n const typedHandler = handler;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return await Promise.resolve(typedHandler.createTask(taskExtra));\n }\n }\n if (tool.inputSchema) {\n const typedHandler = handler;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return await Promise.resolve(typedHandler(args, extra));\n }\n else {\n const typedHandler = handler;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return await Promise.resolve(typedHandler(extra));\n }\n }\n /**\n * Handles automatic task polling for tools with taskSupport 'optional'.\n */\n async handleAutomaticTaskPolling(tool, request, extra) {\n if (!extra.taskStore) {\n throw new Error('No task store provided for task-capable tool.');\n }\n // Validate input and create task\n const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);\n const handler = tool.handler;\n const taskExtra = { ...extra, taskStore: extra.taskStore };\n const createTaskResult = args // undefined only if tool.inputSchema is undefined\n ? await Promise.resolve(handler.createTask(args, taskExtra))\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n await Promise.resolve(handler.createTask(taskExtra));\n // Poll until completion\n const taskId = createTaskResult.task.taskId;\n let task = createTaskResult.task;\n const pollInterval = task.pollInterval ?? 5000;\n while (task.status !== 'completed' && task.status !== 'failed' && task.status !== 'cancelled') {\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n const updatedTask = await extra.taskStore.getTask(taskId);\n if (!updatedTask) {\n throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);\n }\n task = updatedTask;\n }\n // Return the final result\n return (await extra.taskStore.getTaskResult(taskId));\n }\n setCompletionRequestHandler() {\n if (this._completionHandlerInitialized) {\n return;\n }\n this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema));\n this.server.registerCapabilities({\n completions: {}\n });\n this.server.setRequestHandler(CompleteRequestSchema, async (request) => {\n switch (request.params.ref.type) {\n case 'ref/prompt':\n assertCompleteRequestPrompt(request);\n return this.handlePromptCompletion(request, request.params.ref);\n case 'ref/resource':\n assertCompleteRequestResourceTemplate(request);\n return this.handleResourceCompletion(request, request.params.ref);\n default:\n throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);\n }\n });\n this._completionHandlerInitialized = true;\n }\n async handlePromptCompletion(request, ref) {\n const prompt = this._registeredPrompts[ref.name];\n if (!prompt) {\n throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`);\n }\n if (!prompt.enabled) {\n throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);\n }\n if (!prompt.argsSchema) {\n return EMPTY_COMPLETION_RESULT;\n }\n const promptShape = getObjectShape(prompt.argsSchema);\n const field = promptShape?.[request.params.argument.name];\n if (!isCompletable(field)) {\n return EMPTY_COMPLETION_RESULT;\n }\n const completer = getCompleter(field);\n if (!completer) {\n return EMPTY_COMPLETION_RESULT;\n }\n const suggestions = await completer(request.params.argument.value, request.params.context);\n return createCompletionResult(suggestions);\n }\n async handleResourceCompletion(request, ref) {\n const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri);\n if (!template) {\n if (this._registeredResources[ref.uri]) {\n // Attempting to autocomplete a fixed resource URI is not an error in the spec (but probably should be).\n return EMPTY_COMPLETION_RESULT;\n }\n throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);\n }\n const completer = template.resourceTemplate.completeCallback(request.params.argument.name);\n if (!completer) {\n return EMPTY_COMPLETION_RESULT;\n }\n const suggestions = await completer(request.params.argument.value, request.params.context);\n return createCompletionResult(suggestions);\n }\n setResourceRequestHandlers() {\n if (this._resourceHandlersInitialized) {\n return;\n }\n this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema));\n this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema));\n this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema));\n this.server.registerCapabilities({\n resources: {\n listChanged: true\n }\n });\n this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => {\n const resources = Object.entries(this._registeredResources)\n .filter(([_, resource]) => resource.enabled)\n .map(([uri, resource]) => ({\n uri,\n name: resource.name,\n ...resource.metadata\n }));\n const templateResources = [];\n for (const template of Object.values(this._registeredResourceTemplates)) {\n if (!template.resourceTemplate.listCallback) {\n continue;\n }\n const result = await template.resourceTemplate.listCallback(extra);\n for (const resource of result.resources) {\n templateResources.push({\n ...template.metadata,\n // the defined resource metadata should override the template metadata if present\n ...resource\n });\n }\n }\n return { resources: [...resources, ...templateResources] };\n });\n this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => {\n const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({\n name,\n uriTemplate: template.resourceTemplate.uriTemplate.toString(),\n ...template.metadata\n }));\n return { resourceTemplates };\n });\n this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {\n const uri = new URL(request.params.uri);\n // First check for exact resource match\n const resource = this._registeredResources[uri.toString()];\n if (resource) {\n if (!resource.enabled) {\n throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`);\n }\n return resource.readCallback(uri, extra);\n }\n // Then check templates\n for (const template of Object.values(this._registeredResourceTemplates)) {\n const variables = template.resourceTemplate.uriTemplate.match(uri.toString());\n if (variables) {\n return template.readCallback(uri, variables, extra);\n }\n }\n throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`);\n });\n this._resourceHandlersInitialized = true;\n }\n setPromptRequestHandlers() {\n if (this._promptHandlersInitialized) {\n return;\n }\n this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema));\n this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema));\n this.server.registerCapabilities({\n prompts: {\n listChanged: true\n }\n });\n this.server.setRequestHandler(ListPromptsRequestSchema, () => ({\n prompts: Object.entries(this._registeredPrompts)\n .filter(([, prompt]) => prompt.enabled)\n .map(([name, prompt]) => {\n return {\n name,\n title: prompt.title,\n description: prompt.description,\n arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined\n };\n })\n }));\n this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => {\n const prompt = this._registeredPrompts[request.params.name];\n if (!prompt) {\n throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);\n }\n if (!prompt.enabled) {\n throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);\n }\n if (prompt.argsSchema) {\n const argsObj = normalizeObjectSchema(prompt.argsSchema);\n const parseResult = await safeParseAsync(argsObj, request.params.arguments);\n if (!parseResult.success) {\n const error = 'error' in parseResult ? parseResult.error : 'Unknown error';\n const errorMessage = getParseErrorMessage(error);\n throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${errorMessage}`);\n }\n const args = parseResult.data;\n const cb = prompt.callback;\n return await Promise.resolve(cb(args, extra));\n }\n else {\n const cb = prompt.callback;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return await Promise.resolve(cb(extra));\n }\n });\n this._promptHandlersInitialized = true;\n }\n resource(name, uriOrTemplate, ...rest) {\n let metadata;\n if (typeof rest[0] === 'object') {\n metadata = rest.shift();\n }\n const readCallback = rest[0];\n if (typeof uriOrTemplate === 'string') {\n if (this._registeredResources[uriOrTemplate]) {\n throw new Error(`Resource ${uriOrTemplate} is already registered`);\n }\n const registeredResource = this._createRegisteredResource(name, undefined, uriOrTemplate, metadata, readCallback);\n this.setResourceRequestHandlers();\n this.sendResourceListChanged();\n return registeredResource;\n }\n else {\n if (this._registeredResourceTemplates[name]) {\n throw new Error(`Resource template ${name} is already registered`);\n }\n const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, undefined, uriOrTemplate, metadata, readCallback);\n this.setResourceRequestHandlers();\n this.sendResourceListChanged();\n return registeredResourceTemplate;\n }\n }\n registerResource(name, uriOrTemplate, config, readCallback) {\n if (typeof uriOrTemplate === 'string') {\n if (this._registeredResources[uriOrTemplate]) {\n throw new Error(`Resource ${uriOrTemplate} is already registered`);\n }\n const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback);\n this.setResourceRequestHandlers();\n this.sendResourceListChanged();\n return registeredResource;\n }\n else {\n if (this._registeredResourceTemplates[name]) {\n throw new Error(`Resource template ${name} is already registered`);\n }\n const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback);\n this.setResourceRequestHandlers();\n this.sendResourceListChanged();\n return registeredResourceTemplate;\n }\n }\n _createRegisteredResource(name, title, uri, metadata, readCallback) {\n const registeredResource = {\n name,\n title,\n metadata,\n readCallback,\n enabled: true,\n disable: () => registeredResource.update({ enabled: false }),\n enable: () => registeredResource.update({ enabled: true }),\n remove: () => registeredResource.update({ uri: null }),\n update: updates => {\n if (typeof updates.uri !== 'undefined' && updates.uri !== uri) {\n delete this._registeredResources[uri];\n if (updates.uri)\n this._registeredResources[updates.uri] = registeredResource;\n }\n if (typeof updates.name !== 'undefined')\n registeredResource.name = updates.name;\n if (typeof updates.title !== 'undefined')\n registeredResource.title = updates.title;\n if (typeof updates.metadata !== 'undefined')\n registeredResource.metadata = updates.metadata;\n if (typeof updates.callback !== 'undefined')\n registeredResource.readCallback = updates.callback;\n if (typeof updates.enabled !== 'undefined')\n registeredResource.enabled = updates.enabled;\n this.sendResourceListChanged();\n }\n };\n this._registeredResources[uri] = registeredResource;\n return registeredResource;\n }\n _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {\n const registeredResourceTemplate = {\n resourceTemplate: template,\n title,\n metadata,\n readCallback,\n enabled: true,\n disable: () => registeredResourceTemplate.update({ enabled: false }),\n enable: () => registeredResourceTemplate.update({ enabled: true }),\n remove: () => registeredResourceTemplate.update({ name: null }),\n update: updates => {\n if (typeof updates.name !== 'undefined' && updates.name !== name) {\n delete this._registeredResourceTemplates[name];\n if (updates.name)\n this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;\n }\n if (typeof updates.title !== 'undefined')\n registeredResourceTemplate.title = updates.title;\n if (typeof updates.template !== 'undefined')\n registeredResourceTemplate.resourceTemplate = updates.template;\n if (typeof updates.metadata !== 'undefined')\n registeredResourceTemplate.metadata = updates.metadata;\n if (typeof updates.callback !== 'undefined')\n registeredResourceTemplate.readCallback = updates.callback;\n if (typeof updates.enabled !== 'undefined')\n registeredResourceTemplate.enabled = updates.enabled;\n this.sendResourceListChanged();\n }\n };\n this._registeredResourceTemplates[name] = registeredResourceTemplate;\n // If the resource template has any completion callbacks, enable completions capability\n const variableNames = template.uriTemplate.variableNames;\n const hasCompleter = Array.isArray(variableNames) && variableNames.some(v => !!template.completeCallback(v));\n if (hasCompleter) {\n this.setCompletionRequestHandler();\n }\n return registeredResourceTemplate;\n }\n _createRegisteredPrompt(name, title, description, argsSchema, callback) {\n const registeredPrompt = {\n title,\n description,\n argsSchema: argsSchema === undefined ? undefined : objectFromShape(argsSchema),\n callback,\n enabled: true,\n disable: () => registeredPrompt.update({ enabled: false }),\n enable: () => registeredPrompt.update({ enabled: true }),\n remove: () => registeredPrompt.update({ name: null }),\n update: updates => {\n if (typeof updates.name !== 'undefined' && updates.name !== name) {\n delete this._registeredPrompts[name];\n if (updates.name)\n this._registeredPrompts[updates.name] = registeredPrompt;\n }\n if (typeof updates.title !== 'undefined')\n registeredPrompt.title = updates.title;\n if (typeof updates.description !== 'undefined')\n registeredPrompt.description = updates.description;\n if (typeof updates.argsSchema !== 'undefined')\n registeredPrompt.argsSchema = objectFromShape(updates.argsSchema);\n if (typeof updates.callback !== 'undefined')\n registeredPrompt.callback = updates.callback;\n if (typeof updates.enabled !== 'undefined')\n registeredPrompt.enabled = updates.enabled;\n this.sendPromptListChanged();\n }\n };\n this._registeredPrompts[name] = registeredPrompt;\n // If any argument uses a Completable schema, enable completions capability\n if (argsSchema) {\n const hasCompletable = Object.values(argsSchema).some(field => {\n const inner = field instanceof ZodOptional ? field._def?.innerType : field;\n return isCompletable(inner);\n });\n if (hasCompletable) {\n this.setCompletionRequestHandler();\n }\n }\n return registeredPrompt;\n }\n _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, execution, _meta, handler) {\n // Validate tool name according to SEP specification\n validateAndWarnToolName(name);\n const registeredTool = {\n title,\n description,\n inputSchema: getZodSchemaObject(inputSchema),\n outputSchema: getZodSchemaObject(outputSchema),\n annotations,\n execution,\n _meta,\n handler: handler,\n enabled: true,\n disable: () => registeredTool.update({ enabled: false }),\n enable: () => registeredTool.update({ enabled: true }),\n remove: () => registeredTool.update({ name: null }),\n update: updates => {\n if (typeof updates.name !== 'undefined' && updates.name !== name) {\n if (typeof updates.name === 'string') {\n validateAndWarnToolName(updates.name);\n }\n delete this._registeredTools[name];\n if (updates.name)\n this._registeredTools[updates.name] = registeredTool;\n }\n if (typeof updates.title !== 'undefined')\n registeredTool.title = updates.title;\n if (typeof updates.description !== 'undefined')\n registeredTool.description = updates.description;\n if (typeof updates.paramsSchema !== 'undefined')\n registeredTool.inputSchema = objectFromShape(updates.paramsSchema);\n if (typeof updates.outputSchema !== 'undefined')\n registeredTool.outputSchema = objectFromShape(updates.outputSchema);\n if (typeof updates.callback !== 'undefined')\n registeredTool.handler = updates.callback;\n if (typeof updates.annotations !== 'undefined')\n registeredTool.annotations = updates.annotations;\n if (typeof updates._meta !== 'undefined')\n registeredTool._meta = updates._meta;\n if (typeof updates.enabled !== 'undefined')\n registeredTool.enabled = updates.enabled;\n this.sendToolListChanged();\n }\n };\n this._registeredTools[name] = registeredTool;\n this.setToolRequestHandlers();\n this.sendToolListChanged();\n return registeredTool;\n }\n /**\n * tool() implementation. Parses arguments passed to overrides defined above.\n */\n tool(name, ...rest) {\n if (this._registeredTools[name]) {\n throw new Error(`Tool ${name} is already registered`);\n }\n let description;\n let inputSchema;\n let outputSchema;\n let annotations;\n // Tool properties are passed as separate arguments, with omissions allowed.\n // Support for this style is frozen as of protocol version 2025-03-26. Future additions\n // to tool definition should *NOT* be added.\n if (typeof rest[0] === 'string') {\n description = rest.shift();\n }\n // Handle the different overload combinations\n if (rest.length > 1) {\n // We have at least one more arg before the callback\n const firstArg = rest[0];\n if (isZodRawShapeCompat(firstArg)) {\n // We have a params schema as the first arg\n inputSchema = rest.shift();\n // Check if the next arg is potentially annotations\n if (rest.length > 1 && typeof rest[0] === 'object' && rest[0] !== null && !isZodRawShapeCompat(rest[0])) {\n // Case: tool(name, paramsSchema, annotations, cb)\n // Or: tool(name, description, paramsSchema, annotations, cb)\n annotations = rest.shift();\n }\n }\n else if (typeof firstArg === 'object' && firstArg !== null) {\n // Not a ZodRawShapeCompat, so must be annotations in this position\n // Case: tool(name, annotations, cb)\n // Or: tool(name, description, annotations, cb)\n annotations = rest.shift();\n }\n }\n const callback = rest[0];\n return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, undefined, callback);\n }\n /**\n * Registers a tool with a config object and callback.\n */\n registerTool(name, config, cb) {\n if (this._registeredTools[name]) {\n throw new Error(`Tool ${name} is already registered`);\n }\n const { title, description, inputSchema, outputSchema, annotations, _meta } = config;\n return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, { taskSupport: 'forbidden' }, _meta, cb);\n }\n prompt(name, ...rest) {\n if (this._registeredPrompts[name]) {\n throw new Error(`Prompt ${name} is already registered`);\n }\n let description;\n if (typeof rest[0] === 'string') {\n description = rest.shift();\n }\n let argsSchema;\n if (rest.length > 1) {\n argsSchema = rest.shift();\n }\n const cb = rest[0];\n const registeredPrompt = this._createRegisteredPrompt(name, undefined, description, argsSchema, cb);\n this.setPromptRequestHandlers();\n this.sendPromptListChanged();\n return registeredPrompt;\n }\n /**\n * Registers a prompt with a config object and callback.\n */\n registerPrompt(name, config, cb) {\n if (this._registeredPrompts[name]) {\n throw new Error(`Prompt ${name} is already registered`);\n }\n const { title, description, argsSchema } = config;\n const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb);\n this.setPromptRequestHandlers();\n this.sendPromptListChanged();\n return registeredPrompt;\n }\n /**\n * Checks if the server is connected to a transport.\n * @returns True if the server is connected\n */\n isConnected() {\n return this.server.transport !== undefined;\n }\n /**\n * Sends a logging message to the client, if connected.\n * Note: You only need to send the parameters object, not the entire JSON RPC message\n * @see LoggingMessageNotification\n * @param params\n * @param sessionId optional for stateless and backward compatibility\n */\n async sendLoggingMessage(params, sessionId) {\n return this.server.sendLoggingMessage(params, sessionId);\n }\n /**\n * Sends a resource list changed event to the client, if connected.\n */\n sendResourceListChanged() {\n if (this.isConnected()) {\n this.server.sendResourceListChanged();\n }\n }\n /**\n * Sends a tool list changed event to the client, if connected.\n */\n sendToolListChanged() {\n if (this.isConnected()) {\n this.server.sendToolListChanged();\n }\n }\n /**\n * Sends a prompt list changed event to the client, if connected.\n */\n sendPromptListChanged() {\n if (this.isConnected()) {\n this.server.sendPromptListChanged();\n }\n }\n}\n/**\n * A resource template combines a URI pattern with optional functionality to enumerate\n * all resources matching that pattern.\n */\nexport class ResourceTemplate {\n constructor(uriTemplate, _callbacks) {\n this._callbacks = _callbacks;\n this._uriTemplate = typeof uriTemplate === 'string' ? new UriTemplate(uriTemplate) : uriTemplate;\n }\n /**\n * Gets the URI template pattern.\n */\n get uriTemplate() {\n return this._uriTemplate;\n }\n /**\n * Gets the list callback, if one was provided.\n */\n get listCallback() {\n return this._callbacks.list;\n }\n /**\n * Gets the callback for completing a specific URI template variable, if one was provided.\n */\n completeCallback(variable) {\n return this._callbacks.complete?.[variable];\n }\n}\nconst EMPTY_OBJECT_JSON_SCHEMA = {\n type: 'object',\n properties: {}\n};\n/**\n * Checks if a value looks like a Zod schema by checking for parse/safeParse methods.\n */\nfunction isZodTypeLike(value) {\n return (value !== null &&\n typeof value === 'object' &&\n 'parse' in value &&\n typeof value.parse === 'function' &&\n 'safeParse' in value &&\n typeof value.safeParse === 'function');\n}\n/**\n * Checks if an object is a Zod schema instance (v3 or v4).\n *\n * Zod schemas have internal markers:\n * - v3: `_def` property\n * - v4: `_zod` property\n *\n * This includes transformed schemas like z.preprocess(), z.transform(), z.pipe().\n */\nfunction isZodSchemaInstance(obj) {\n return '_def' in obj || '_zod' in obj || isZodTypeLike(obj);\n}\n/**\n * Checks if an object is a \"raw shape\" - a plain object where values are Zod schemas.\n *\n * Raw shapes are used as shorthand: `{ name: z.string() }` instead of `z.object({ name: z.string() })`.\n *\n * IMPORTANT: This must NOT match actual Zod schema instances (like z.preprocess, z.pipe),\n * which have internal properties that could be mistaken for schema values.\n */\nfunction isZodRawShapeCompat(obj) {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n // If it's already a Zod schema instance, it's NOT a raw shape\n if (isZodSchemaInstance(obj)) {\n return false;\n }\n // Empty objects are valid raw shapes (tools with no parameters)\n if (Object.keys(obj).length === 0) {\n return true;\n }\n // A raw shape has at least one property that is a Zod schema\n return Object.values(obj).some(isZodTypeLike);\n}\n/**\n * Converts a provided Zod schema to a Zod object if it is a ZodRawShapeCompat,\n * otherwise returns the schema as is.\n */\nfunction getZodSchemaObject(schema) {\n if (!schema) {\n return undefined;\n }\n if (isZodRawShapeCompat(schema)) {\n return objectFromShape(schema);\n }\n return schema;\n}\nfunction promptArgumentsFromSchema(schema) {\n const shape = getObjectShape(schema);\n if (!shape)\n return [];\n return Object.entries(shape).map(([name, field]) => {\n // Get description - works for both v3 and v4\n const description = getSchemaDescription(field);\n // Check if optional - works for both v3 and v4\n const isOptional = isSchemaOptional(field);\n return {\n name,\n description,\n required: !isOptional\n };\n });\n}\nfunction getMethodValue(schema) {\n const shape = getObjectShape(schema);\n const methodSchema = shape?.method;\n if (!methodSchema) {\n throw new Error('Schema is missing a method literal');\n }\n // Extract literal value - works for both v3 and v4\n const value = getLiteralValue(methodSchema);\n if (typeof value === 'string') {\n return value;\n }\n throw new Error('Schema method literal must be a string');\n}\nfunction createCompletionResult(suggestions) {\n return {\n completion: {\n values: suggestions.slice(0, 100),\n total: suggestions.length,\n hasMore: suggestions.length > 100\n }\n };\n}\nconst EMPTY_COMPLETION_RESULT = {\n completion: {\n values: [],\n hasMore: false\n }\n};\n//# sourceMappingURL=mcp.js.map","import { isPlainObject, validateArgsWithSchema } from '@mcp-b/webmcp-polyfill';\nimport type { InputSchema } from '@mcp-b/webmcp-types';\n\ninterface JsonSchemaValidator {\n getValidator<T>(schema: unknown): (input: unknown) => JsonSchemaValidatorResult<T>;\n}\n\ntype JsonSchemaValidatorResult<T> =\n | { valid: true; data: T; errorMessage: undefined }\n | { valid: false; data: undefined; errorMessage: string };\n\nexport class PolyfillJsonSchemaValidator implements JsonSchemaValidator {\n getValidator<T>(schema: unknown): (input: unknown) => JsonSchemaValidatorResult<T> {\n return (input: unknown): JsonSchemaValidatorResult<T> => {\n if (!isPlainObject(input)) {\n return { valid: false, data: undefined, errorMessage: 'expected object arguments' };\n }\n\n const issue = validateArgsWithSchema(input, schema as InputSchema);\n if (issue) {\n return { valid: false, data: undefined, errorMessage: issue.message };\n }\n\n return { valid: true, data: input as T, errorMessage: undefined };\n };\n }\n}\n","import type {\n InputSchema,\n JsonObject,\n ModelContextClient,\n ModelContextCore,\n ModelContextExtensions,\n ModelContextOptions,\n ModelContextToolReference,\n ResourceContents,\n ToolDescriptor,\n ToolListItem,\n ToolResponse,\n} from '@mcp-b/webmcp-types';\nimport type { ServerOptions } from '@modelcontextprotocol/sdk/server/index.js';\nimport { McpServer as BaseMcpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport {\n getParseErrorMessage,\n normalizeObjectSchema,\n safeParseAsync,\n} from '@modelcontextprotocol/sdk/server/zod-compat.js';\nimport { toJsonSchemaCompat } from '@modelcontextprotocol/sdk/server/zod-json-schema-compat.js';\nimport type { RequestOptions } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport { mergeCapabilities } from '@modelcontextprotocol/sdk/shared/protocol.js';\nimport type { Transport } from '@modelcontextprotocol/sdk/shared/transport.js';\nimport type {\n CreateMessageRequest,\n CreateMessageResult,\n ElicitRequest,\n ElicitResult,\n Implementation,\n PromptMessage,\n} from '@modelcontextprotocol/sdk/types.js';\nimport {\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListToolsRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport { PolyfillJsonSchemaValidator } from './polyfill-validator.js';\n\nconst DEFAULT_INPUT_SCHEMA: InputSchema = { type: 'object', properties: {} };\nconst DEFAULT_CLIENT_REQUEST_TIMEOUT = 10_000;\n\nexport const SERVER_MARKER_PROPERTY = '__isBrowserMcpServer' as const;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction isCallToolResult(value: unknown): value is ToolResponse {\n return isPlainObject(value) && Array.isArray(value.content);\n}\n\nfunction isJsonPrimitive(value: unknown): value is string | number | boolean | null {\n return (\n value === null ||\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n );\n}\n\nfunction isJsonValue(value: unknown): boolean {\n if (isJsonPrimitive(value)) {\n return Number.isFinite(value as number) || typeof value !== 'number';\n }\n\n if (Array.isArray(value)) {\n return value.every((entry) => isJsonValue(entry));\n }\n\n if (!isPlainObject(value)) {\n return false;\n }\n\n return Object.values(value).every((entry) => isJsonValue(entry));\n}\n\nfunction toStructuredContent(value: unknown): JsonObject | undefined {\n if (!isPlainObject(value) || !isJsonValue(value)) {\n return undefined;\n }\n\n return value as JsonObject;\n}\n\nfunction serializeTextContent(value: unknown): string {\n if (typeof value === 'string') {\n return value;\n }\n\n try {\n const candidate = JSON.stringify(value);\n return candidate ?? String(value);\n } catch {\n return String(value);\n }\n}\n\nfunction normalizeToolResponse(value: unknown): ToolResponse {\n if (isCallToolResult(value)) {\n return value;\n }\n\n const structuredContent = toStructuredContent(value);\n\n return {\n content: [{ type: 'text', text: serializeTextContent(value) }],\n ...(structuredContent ? { structuredContent } : {}),\n isError: false,\n };\n}\n\nfunction withDefaultTimeout(options?: RequestOptions): RequestOptions {\n if (options?.signal) return options;\n return { ...options, signal: AbortSignal.timeout(DEFAULT_CLIENT_REQUEST_TIMEOUT) };\n}\n\ninterface ParentRegisteredTool {\n description?: string;\n inputSchema?: unknown;\n outputSchema?: unknown;\n annotations?: unknown;\n handler: (args: Record<string, unknown>, extra: unknown) => Promise<ToolResponse>;\n enabled: boolean;\n remove: () => void;\n}\n\ninterface ParentRegisteredResource {\n name: string;\n metadata?: { description?: string; mimeType?: string; title?: string };\n readCallback: (uri: URL, extra: unknown) => Promise<{ contents: ResourceContents[] }>;\n enabled: boolean;\n remove: () => void;\n}\n\ninterface ParentRegisteredPrompt {\n title?: string;\n description?: string;\n argsSchema?: unknown;\n callback: (\n args: Record<string, unknown>,\n extra: unknown\n ) => Promise<{ messages: PromptMessage[] }>;\n enabled: boolean;\n remove: () => void;\n}\n\nexport interface BrowserMcpServerOptions extends ServerOptions {\n native?: ModelContextCore;\n}\n\ntype ParentRegisterToolFn = (\n name: string,\n config: Record<string, unknown>,\n cb: (args: Record<string, unknown>, extra: unknown) => Promise<ToolResponse>\n) => void;\n\ntype ParentRegisterResourceFn = (\n name: string,\n uri: string,\n config: Record<string, unknown>,\n cb: (uri: URL, extra: unknown) => Promise<{ contents: ResourceContents[] }>\n) => { remove: () => void };\n\ntype ParentRegisterPromptFn = (\n name: string,\n config: Record<string, unknown>,\n cb: (args: Record<string, unknown>, extra: unknown) => Promise<{ messages: PromptMessage[] }>\n) => { remove: () => void };\n\ntype NativeToolsApi = ModelContextCore & Pick<ModelContextExtensions, 'listTools' | 'callTool'>;\ntype RegisteredToolHandle = { unregister: () => void };\n\n/**\n * Browser-optimized MCP Server that speaks WebMCP natively.\n *\n * This server IS navigator.modelContext — it implements the WebMCP standard API\n * (provideContext, registerTool, unregisterTool, clearContext) while retaining\n * full MCP protocol capabilities (resources, prompts, elicitation, sampling)\n * via the inherited BaseMcpServer surface.\n *\n * When `native` is provided, all tool operations are mirrored to it so that\n * navigator.modelContextTesting (polyfill testing shim) stays in sync.\n */\nexport class BrowserMcpServer extends BaseMcpServer {\n readonly [SERVER_MARKER_PROPERTY] = true as const;\n\n private native: ModelContextCore | undefined;\n private _promptSchemas = new Map<string, InputSchema>();\n private _jsonValidator: PolyfillJsonSchemaValidator;\n private _publicMethodsBound = false;\n private _provideContextDeprecationWarned = false;\n private _clearContextDeprecationWarned = false;\n\n constructor(serverInfo: Implementation, options?: BrowserMcpServerOptions) {\n const validator = new PolyfillJsonSchemaValidator();\n const enhancedOptions: ServerOptions = {\n capabilities: mergeCapabilities(options?.capabilities || {}, {\n tools: { listChanged: true },\n resources: { listChanged: true },\n prompts: { listChanged: true },\n }),\n jsonSchemaValidator: options?.jsonSchemaValidator ?? validator,\n };\n\n super(serverInfo, enhancedOptions);\n this._jsonValidator = validator;\n this.native = options?.native;\n this.bindPublicApiMethods();\n }\n\n /**\n * navigator.modelContext consumers may destructure methods (e.g. const { registerTool } = ...).\n * Bind methods once so they remain callable outside instance-method invocation syntax.\n */\n private bindPublicApiMethods(): void {\n if (this._publicMethodsBound) {\n return;\n }\n\n this.registerTool = this.registerTool.bind(this);\n this.unregisterTool = this.unregisterTool.bind(this);\n this.provideContext = this.provideContext.bind(this);\n this.clearContext = this.clearContext.bind(this);\n this.listTools = this.listTools.bind(this);\n this.callTool = this.callTool.bind(this);\n this.executeTool = this.executeTool.bind(this);\n\n this.registerResource = this.registerResource.bind(this);\n this.listResources = this.listResources.bind(this);\n this.readResource = this.readResource.bind(this);\n\n this.registerPrompt = this.registerPrompt.bind(this);\n this.listPrompts = this.listPrompts.bind(this);\n this.getPrompt = this.getPrompt.bind(this);\n\n this.createMessage = this.createMessage.bind(this);\n this.elicitInput = this.elicitInput.bind(this);\n\n this._publicMethodsBound = true;\n }\n\n private get _parentTools(): Record<string, ParentRegisteredTool> {\n return (this as unknown as { _registeredTools: Record<string, ParentRegisteredTool> })\n ._registeredTools;\n }\n\n private get _parentResources(): Record<string, ParentRegisteredResource> {\n return (this as unknown as { _registeredResources: Record<string, ParentRegisteredResource> })\n ._registeredResources;\n }\n\n private get _parentPrompts(): Record<string, ParentRegisteredPrompt> {\n return (this as unknown as { _registeredPrompts: Record<string, ParentRegisteredPrompt> })\n ._registeredPrompts;\n }\n\n /**\n * Converts a schema (Zod or plain JSON Schema) to a transport-ready JSON Schema.\n * When `requireObjectType` is true (the default, for inputSchema), empty `{}` schemas\n * are normalized to `{ type: \"object\", properties: {} }` and schemas missing a root\n * `type` get `type: \"object\"` prepended — per MCP spec requirements.\n * When false (for outputSchema), no object-type normalization is applied.\n */\n private toTransportSchema(schema: unknown, requireObjectType = true): InputSchema {\n if (!schema || typeof schema !== 'object') {\n if (requireObjectType) {\n console.warn(\n `[BrowserMcpServer] toTransportSchema received non-object schema (${typeof schema}), using default`\n );\n return DEFAULT_INPUT_SCHEMA;\n }\n return {} as InputSchema;\n }\n\n const normalized = normalizeObjectSchema(schema as Parameters<typeof normalizeObjectSchema>[0]);\n const jsonSchema = normalized\n ? (toJsonSchemaCompat(normalized, {\n strictUnions: true,\n pipeStrategy: 'input',\n }) as unknown as Record<string, unknown>)\n : (schema as Record<string, unknown>);\n\n if (Object.keys(jsonSchema).length === 0) {\n if (requireObjectType) {\n return DEFAULT_INPUT_SCHEMA;\n }\n return jsonSchema as InputSchema;\n }\n\n if (requireObjectType && jsonSchema.type === undefined) {\n return { type: 'object', ...jsonSchema } as InputSchema;\n }\n\n return jsonSchema as InputSchema;\n }\n\n private isZodSchema(schema: unknown): boolean {\n if (!schema || typeof schema !== 'object') return false;\n const s = schema as Record<string, unknown>;\n return '_zod' in s || '_def' in s;\n }\n\n private getNativeToolsApi(): NativeToolsApi | undefined {\n if (!this.native) {\n return undefined;\n }\n\n const candidate = this.native as ModelContextCore &\n Partial<Pick<ModelContextExtensions, 'listTools' | 'callTool'>>;\n if (typeof candidate.listTools !== 'function' || typeof candidate.callTool !== 'function') {\n return undefined;\n }\n\n return candidate as NativeToolsApi;\n }\n\n private registerToolInServer(tool: ToolDescriptor): RegisteredToolHandle {\n const inputSchema = this.toTransportSchema(tool.inputSchema);\n\n // Cast needed: parent expects Zod-compatible schemas, we pass JSON Schema objects.\n (super.registerTool as unknown as ParentRegisterToolFn)(\n tool.name,\n {\n description: tool.description,\n inputSchema,\n ...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),\n ...(tool.annotations ? { annotations: tool.annotations } : {}),\n },\n async (args: Record<string, unknown>) => {\n const client: ModelContextClient = {\n requestUserInteraction: async (cb: () => Promise<unknown>) => cb(),\n };\n return normalizeToolResponse(await tool.execute(args, client));\n }\n );\n return {\n unregister: () => this.unregisterTool(tool.name),\n };\n }\n\n backfillTools(\n tools: readonly ToolListItem[],\n execute: (name: string, args: Record<string, unknown>) => Promise<ToolResponse>\n ): number {\n let synced = 0;\n\n for (const sourceTool of tools) {\n if (!sourceTool?.name || this._parentTools[sourceTool.name]) {\n continue;\n }\n\n const toolDescriptor: ToolDescriptor = {\n name: sourceTool.name,\n description: sourceTool.description ?? '',\n inputSchema: sourceTool.inputSchema ?? DEFAULT_INPUT_SCHEMA,\n execute: async (args: Record<string, unknown>) => execute(sourceTool.name, args),\n };\n\n if (sourceTool.outputSchema) {\n toolDescriptor.outputSchema = sourceTool.outputSchema;\n }\n if (sourceTool.annotations) {\n toolDescriptor.annotations = sourceTool.annotations;\n }\n\n this.registerToolInServer(toolDescriptor);\n synced++;\n }\n\n return synced;\n }\n\n // --- WebMCP standard API (primary surface) ---\n\n // @ts-expect-error -- WebMCP API: (ToolDescriptor) vs MCP SDK: (name, config, cb)\n override registerTool(tool: ToolDescriptor): RegisteredToolHandle {\n // Mirror to native first — the polyfill validates the descriptor\n if (this.native) {\n (this.native.registerTool as (tool: ToolDescriptor) => void)(tool);\n }\n\n try {\n return this.registerToolInServer(tool);\n } catch (error) {\n // Rollback native registration on server failure\n if (this.native) {\n try {\n this.native.unregisterTool(tool.name);\n } catch (rollbackError) {\n console.error(\n '[BrowserMcpServer] Rollback of native tool registration failed:',\n rollbackError\n );\n }\n }\n throw error;\n }\n }\n\n /**\n * Backfill tools that were already registered on the native/polyfill context\n * before this BrowserMcpServer wrapper was installed.\n */\n syncNativeTools(): number {\n const nativeToolsApi = this.getNativeToolsApi();\n if (!nativeToolsApi) {\n return 0;\n }\n\n const nativeCallTool = nativeToolsApi.callTool.bind(nativeToolsApi);\n return this.backfillTools(\n nativeToolsApi.listTools(),\n async (name: string, args: Record<string, unknown>) =>\n nativeCallTool({\n name,\n arguments: args,\n })\n );\n }\n\n unregisterTool(nameOrTool: string | ModelContextToolReference): void {\n const name = this.resolveToolNameForUnregister(nameOrTool);\n this._parentTools[name]?.remove();\n\n if (this.native) {\n this.native.unregisterTool(name);\n }\n }\n\n private clearRegisteredTools(): void {\n for (const name of Object.keys(this._parentTools)) {\n this.unregisterTool(name);\n }\n }\n\n // @ts-expect-error -- WebMCP API: (descriptor) vs MCP SDK: (name, uri, config, readCallback)\n override registerResource(descriptor: {\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n read: (uri: URL, params?: Record<string, string>) => Promise<{ contents: ResourceContents[] }>;\n }): { unregister: () => void } {\n const registered = (super.registerResource as unknown as ParentRegisterResourceFn)(\n descriptor.name,\n descriptor.uri,\n {\n ...(descriptor.description !== undefined && { description: descriptor.description }),\n ...(descriptor.mimeType !== undefined && { mimeType: descriptor.mimeType }),\n },\n async (uri: URL) => ({\n contents: (await descriptor.read(uri)).contents,\n })\n );\n\n return {\n unregister: () => registered.remove(),\n };\n }\n\n // @ts-expect-error -- WebMCP API: (descriptor) vs MCP SDK: (name, config, cb)\n override registerPrompt(descriptor: {\n name: string;\n description?: string;\n argsSchema?: InputSchema;\n get: (args: Record<string, unknown>) => Promise<{ messages: PromptMessage[] }>;\n }): { unregister: () => void } {\n // Store argsSchema locally — the parent SDK's _createRegisteredPrompt corrupts\n // plain JSON Schema objects via objectFromShape() which expects Zod schemas.\n if (descriptor.argsSchema) {\n this._promptSchemas.set(descriptor.name, descriptor.argsSchema);\n }\n\n const registered = (super.registerPrompt as unknown as ParentRegisterPromptFn)(\n descriptor.name,\n {\n ...(descriptor.description !== undefined && { description: descriptor.description }),\n // Do NOT pass argsSchema to parent — it gets corrupted by Zod's objectFromShape\n },\n async (args: Record<string, unknown>) => ({\n messages: (await descriptor.get(args)).messages,\n })\n );\n\n return {\n unregister: () => {\n this._promptSchemas.delete(descriptor.name);\n registered.remove();\n },\n };\n }\n\n provideContext(options?: ModelContextOptions): void {\n this.warnProvideContextDeprecationOnce();\n this.clearRegisteredTools();\n\n for (const tool of options?.tools ?? []) {\n this.registerTool(tool);\n }\n }\n\n clearContext(): void {\n this.warnClearContextDeprecationOnce();\n this.clearRegisteredTools();\n // Note: _promptSchemas is NOT cleared here. clearContext() is a WebMCP standard\n // method that only handles tools. Prompt schemas are cleaned up individually\n // via the unregister() callback returned by registerPrompt().\n }\n\n private resolveToolNameForUnregister(nameOrTool: string | ModelContextToolReference): string {\n if (typeof nameOrTool === 'string') {\n return nameOrTool;\n }\n\n if (isPlainObject(nameOrTool) && typeof nameOrTool.name === 'string') {\n return nameOrTool.name;\n }\n\n throw new TypeError(\n \"Failed to execute 'unregisterTool' on 'ModelContext': parameter 1 must be a string or an object with a string name.\"\n );\n }\n\n private warnProvideContextDeprecationOnce(): void {\n if (this._provideContextDeprecationWarned) {\n return;\n }\n\n this._provideContextDeprecationWarned = true;\n console.warn(\n '[BrowserMcpServer] navigator.modelContext.provideContext() is deprecated and will be removed in the next major version. Register tools individually with registerTool() instead.'\n );\n }\n\n private warnClearContextDeprecationOnce(): void {\n if (this._clearContextDeprecationWarned) {\n return;\n }\n\n this._clearContextDeprecationWarned = true;\n console.warn(\n '[BrowserMcpServer] navigator.modelContext.clearContext() is deprecated and will be removed in the next major version. Unregister individual tools instead.'\n );\n }\n\n // --- Extension methods ---\n\n listResources(): Array<{\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n }> {\n return Object.entries(this._parentResources)\n .filter(([, resource]) => resource.enabled)\n .map(([uri, resource]) => ({\n uri,\n name: resource.name,\n ...resource.metadata,\n }));\n }\n\n async readResource(uri: string): Promise<{ contents: ResourceContents[] }> {\n const resource = this._parentResources[uri];\n if (!resource) {\n throw new Error(`Resource not found: ${uri}`);\n }\n\n return resource.readCallback(new URL(uri), {});\n }\n\n listPrompts(): Array<{\n name: string;\n description?: string;\n arguments?: Array<{ name: string; description?: string; required?: boolean }>;\n }> {\n return Object.entries(this._parentPrompts)\n .filter(([, prompt]) => prompt.enabled)\n .map(([name, prompt]) => {\n const schema = this._promptSchemas.get(name);\n return {\n name,\n ...(prompt.description !== undefined && { description: prompt.description }),\n ...(schema?.properties\n ? {\n arguments: Object.entries(schema.properties).map(([argName, prop]) => ({\n name: argName,\n ...(typeof prop === 'object' && prop !== null && 'description' in prop\n ? { description: (prop as { description: string }).description }\n : {}),\n ...(schema.required?.includes(argName) ? { required: true } : {}),\n })),\n }\n : {}),\n };\n });\n }\n\n async getPrompt(\n name: string,\n args: Record<string, unknown> = {}\n ): Promise<{ messages: PromptMessage[] }> {\n const prompt = this._parentPrompts[name];\n if (!prompt) {\n throw new Error(`Prompt not found: ${name}`);\n }\n\n const schema = this._promptSchemas.get(name);\n if (schema) {\n const validator = this._jsonValidator.getValidator(schema);\n const result = validator(args);\n if (!result.valid) {\n throw new Error(`Invalid arguments for prompt ${name}: ${result.errorMessage}`);\n }\n }\n\n return prompt.callback(args, {});\n }\n\n listTools(): ToolListItem[] {\n return Object.entries(this._parentTools)\n .filter(([, tool]) => tool.enabled)\n .map(([name, tool]) => {\n const item: ToolListItem = {\n name,\n description: tool.description ?? '',\n inputSchema: this.toTransportSchema(tool.inputSchema ?? DEFAULT_INPUT_SCHEMA),\n };\n if (tool.outputSchema) item.outputSchema = this.toTransportSchema(tool.outputSchema, false);\n if (tool.annotations)\n item.annotations = tool.annotations as NonNullable<ToolListItem['annotations']>;\n return item;\n });\n }\n\n /**\n * Override SDK's validateToolInput to handle both Zod schemas and plain JSON Schema.\n * Zod schemas use the SDK's safeParseAsync; plain JSON Schema uses PolyfillJsonSchemaValidator.\n */\n override async validateToolInput(\n tool: { inputSchema?: unknown },\n args: Record<string, unknown> | undefined,\n toolName: string\n ): Promise<Record<string, unknown> | undefined> {\n if (!tool.inputSchema) return undefined;\n\n // Zod schemas → use SDK's safeParseAsync\n if (this.isZodSchema(tool.inputSchema)) {\n const result = await safeParseAsync(\n tool.inputSchema as Parameters<typeof safeParseAsync>[0],\n args ?? {}\n );\n if (!result.success) {\n throw new Error(\n `Invalid arguments for tool ${toolName}: ${getParseErrorMessage(result.error)}`\n );\n }\n return result.data as Record<string, unknown>;\n }\n\n // Plain JSON Schema → use PolyfillJsonSchemaValidator\n const validator = this._jsonValidator.getValidator(tool.inputSchema);\n const result = validator(args ?? {});\n if (!result.valid) {\n throw new Error(`Invalid arguments for tool ${toolName}: ${result.errorMessage}`);\n }\n return result.data as Record<string, unknown>;\n }\n\n /**\n * Override SDK's validateToolOutput to handle both Zod schemas and plain JSON Schema.\n */\n override async validateToolOutput(\n tool: { outputSchema?: unknown },\n result: unknown,\n toolName: string\n ): Promise<void> {\n if (!tool.outputSchema) return;\n\n const r = result as Record<string, unknown>;\n if (!('content' in r) || r.isError || !r.structuredContent) return;\n\n // Zod schemas → use SDK's safeParseAsync\n if (this.isZodSchema(tool.outputSchema)) {\n const parseResult = await safeParseAsync(\n tool.outputSchema as Parameters<typeof safeParseAsync>[0],\n r.structuredContent\n );\n if (!parseResult.success) {\n throw new Error(\n `Output validation error: Invalid structured content for tool ${toolName}: ${getParseErrorMessage(parseResult.error)}`\n );\n }\n return;\n }\n\n // Plain JSON Schema → use PolyfillJsonSchemaValidator\n const validator = this._jsonValidator.getValidator(tool.outputSchema);\n const validationResult = validator(r.structuredContent);\n if (!validationResult.valid) {\n throw new Error(\n `Output validation error: Invalid structured content for tool ${toolName}: ${validationResult.errorMessage}`\n );\n }\n }\n\n async callTool(params: {\n name: string;\n arguments?: Record<string, unknown>;\n }): Promise<ToolResponse> {\n const tool = this._parentTools[params.name];\n if (!tool) {\n throw new Error(`Tool not found: ${params.name}`);\n }\n\n return tool.handler(params.arguments ?? {}, {});\n }\n\n async executeTool(name: string, args: Record<string, unknown> = {}): Promise<ToolResponse> {\n return this.callTool({ name, arguments: args });\n }\n\n /**\n * Override connect to initialize request handlers BEFORE the transport connection.\n * This prevents \"Cannot register capabilities after connecting to transport\" errors\n * when tools are registered dynamically after connection.\n *\n * After the parent sets up its Zod-based handlers, we replace the ones that break\n * with plain JSON Schema objects (ListTools, ListPrompts, GetPrompt).\n */\n override async connect(transport: Transport): Promise<void> {\n // Let parent set up its handlers (including CallTool which uses our validateToolInput override)\n (this as unknown as { setToolRequestHandlers: () => void }).setToolRequestHandlers();\n (this as unknown as { setResourceRequestHandlers: () => void }).setResourceRequestHandlers();\n (this as unknown as { setPromptRequestHandlers: () => void }).setPromptRequestHandlers();\n\n // Replace ListTools handler — parent tries toJsonSchemaCompat (Zod → JSON Schema) on\n // inputSchema, but ours are already JSON Schema, so it falls back to empty {}.\n this.server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: this.listTools(),\n }));\n\n // Replace ListPrompts handler — parent calls promptArgumentsFromSchema which expects\n // Zod shapes. We use _promptSchemas which has the real JSON Schema.\n this.server.setRequestHandler(ListPromptsRequestSchema, () => ({\n prompts: this.listPrompts(),\n }));\n\n // Replace GetPrompt handler — parent calls safeParseAsync on argsSchema.\n // We validate with PolyfillJsonSchemaValidator instead.\n this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {\n const prompt = this._parentPrompts[request.params.name];\n if (!prompt) {\n throw new Error(`Prompt ${request.params.name} not found`);\n }\n if (!prompt.enabled) {\n throw new Error(`Prompt ${request.params.name} disabled`);\n }\n\n const schema = this._promptSchemas.get(request.params.name);\n if (schema) {\n const validator = this._jsonValidator.getValidator(schema);\n const result = validator(request.params.arguments ?? {});\n if (!result.valid) {\n throw new Error(\n `Invalid arguments for prompt ${request.params.name}: ${result.errorMessage}`\n );\n }\n return prompt.callback(request.params.arguments as Record<string, unknown>, {});\n }\n\n return prompt.callback({}, {});\n });\n\n return super.connect(transport);\n }\n\n // --- Sampling & Elicitation (delegated to Server) ---\n\n async createMessage(\n params: CreateMessageRequest['params'],\n options?: RequestOptions\n ): Promise<CreateMessageResult> {\n return this.server.createMessage(params, withDefaultTimeout(options));\n }\n\n async elicitInput(\n params: ElicitRequest['params'],\n options?: RequestOptions\n ): Promise<ElicitResult> {\n return this.server.elicitInput(params, withDefaultTimeout(options));\n }\n}\n\n// --- Exported descriptor types for consumers ---\n\nexport interface ResourceDescriptor {\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n read: (uri: URL, params?: Record<string, string>) => Promise<{ contents: ResourceContents[] }>;\n}\n\nexport interface PromptDescriptor {\n name: string;\n description?: string;\n argsSchema?: InputSchema;\n get: (args: Record<string, unknown>) => Promise<{ messages: PromptMessage[] }>;\n}\n","/**\n * No-op JSON Schema validator for browser environments.\n *\n * This validator bypasses the MCP SDK's internal ajv-based validation which causes\n * \"Error compiling schema\" errors in browser extensions due to ajv's use of\n * eval/Function constructor.\n *\n * Validation is handled externally by Zod in @mcp-b/global, making the SDK's\n * internal validation redundant. This no-op validator allows the SDK to function\n * without the ajv dependency issues.\n */\n\n/**\n * Interface for JSON Schema validators.\n * This matches the MCP SDK's jsonSchemaValidator interface.\n */\ninterface JsonSchemaValidator {\n getValidator<T>(schema: unknown): (input: unknown) => JsonSchemaValidatorResult<T>;\n}\n\n/**\n * Result type for JSON Schema validation\n */\ntype JsonSchemaValidatorResult<T> =\n | { valid: true; data: T; errorMessage: undefined }\n | { valid: false; data: undefined; errorMessage: string };\n\n/**\n * A no-op JSON Schema validator that always returns valid.\n *\n * Use this in browser environments where:\n * - ajv causes \"Error compiling schema\" errors\n * - Validation is already handled elsewhere (e.g., by Zod)\n * - You need to avoid eval/Function constructor restrictions\n *\n * @example\n * ```typescript\n * import { BrowserMcpServer } from '@mcp-b/webmcp-ts-sdk';\n * import { NoOpJsonSchemaValidator } from '@mcp-b/webmcp-ts-sdk/no-op-validator';\n *\n * const server = new BrowserMcpServer(\n * { name: 'my-server', version: '1.0.0' },\n * { jsonSchemaValidator: new NoOpJsonSchemaValidator() }\n * );\n * ```\n */\nexport class NoOpJsonSchemaValidator implements JsonSchemaValidator {\n /**\n * Returns a validator function that always passes.\n * The input data is passed through unchanged.\n *\n * @param _schema - The JSON Schema (ignored)\n * @returns A validator function that always returns valid\n */\n getValidator<T>(_schema: unknown): (input: unknown) => JsonSchemaValidatorResult<T> {\n return (input: unknown): JsonSchemaValidatorResult<T> => ({\n valid: true,\n data: input as T,\n errorMessage: undefined,\n });\n }\n}\n"],"x_google_ignoreList":[0,1,2,3,4,7,8,9,10,11,12,13,14,15,16,17],"mappings":";;;;;;;;AAOA,SAAgB,WAAW,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