@modelcontextprotocol/server 2.0.0-beta.1 → 2.0.0-beta.2

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.
Files changed (41) hide show
  1. package/dist/ajvProvider-D2kRT_qB.d.cts +1030 -0
  2. package/dist/ajvProvider-D2kRT_qB.d.cts.map +1 -0
  3. package/dist/ajvProvider-DhTNkgm1.cjs +7059 -0
  4. package/dist/ajvProvider-DhTNkgm1.cjs.map +1 -0
  5. package/dist/cfWorkerProvider-Djgwc46-.cjs +976 -0
  6. package/dist/cfWorkerProvider-Djgwc46-.cjs.map +1 -0
  7. package/dist/cfWorkerProvider-RncldJmy.d.cts +59 -0
  8. package/dist/cfWorkerProvider-RncldJmy.d.cts.map +1 -0
  9. package/dist/chunk-Bnu9O96Y.cjs +60 -0
  10. package/dist/createMcpHandler-Du3hjXvf.d.mts.map +1 -1
  11. package/dist/createMcpHandler-DyxapqGO.d.cts +11190 -0
  12. package/dist/createMcpHandler-DyxapqGO.d.cts.map +1 -0
  13. package/dist/index.cjs +1657 -0
  14. package/dist/index.cjs.map +1 -0
  15. package/dist/index.d.cts +1745 -0
  16. package/dist/index.d.cts.map +1 -0
  17. package/dist/index.mjs +3 -2
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/{mcp-JttQJlI9.mjs → mcp-C2tFGfLG.mjs} +18 -5
  20. package/dist/mcp-C2tFGfLG.mjs.map +1 -0
  21. package/dist/mcp-DVEehpM2.cjs +10545 -0
  22. package/dist/mcp-DVEehpM2.cjs.map +1 -0
  23. package/dist/shimsNode.cjs +12 -0
  24. package/dist/shimsNode.d.cts +3 -0
  25. package/dist/shimsWorkerd.cjs +23 -0
  26. package/dist/shimsWorkerd.cjs.map +1 -0
  27. package/dist/shimsWorkerd.d.cts +11 -0
  28. package/dist/shimsWorkerd.d.cts.map +1 -0
  29. package/dist/stdio.cjs +563 -0
  30. package/dist/stdio.cjs.map +1 -0
  31. package/dist/stdio.d.cts +107 -0
  32. package/dist/stdio.d.cts.map +1 -0
  33. package/dist/stdio.mjs +1 -1
  34. package/dist/types-Pc2fJzyM.d.cts +1099 -0
  35. package/dist/types-Pc2fJzyM.d.cts.map +1 -0
  36. package/dist/validators/ajv.cjs +10 -0
  37. package/dist/validators/ajv.d.cts +2 -0
  38. package/dist/validators/cfWorker.cjs +3 -0
  39. package/dist/validators/cfWorker.d.cts +2 -0
  40. package/package.json +68 -19
  41. package/dist/mcp-JttQJlI9.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"mcp-JttQJlI9.mjs","names":["COMPLETABLE_SYMBOL: unique symbol","code: OAuthErrorCode | string","errorUri?: string","response: OAuthErrorResponse","code: SdkErrorCode","data?: unknown","REQUIRED_CLIENT_CAPABILITIES_BY_METHOD: Readonly<Record<string, ClientCapabilities>>","isPlainObject","missing: Record<string, unknown>","missingMembers: Record<string, unknown>","REF_REWRITE_DATA_POSITION_KEYS: ReadonlySet<string>","REF_REWRITE_NAME_MAP_KEYS: ReadonlySet<string>","out: Record<string, unknown>","JSONValueSchema: z.ZodType<JSONValue, JSONValue>","JSONValueSchema","JSONObjectSchema: z.ZodType<JSONObject, JSONObject>","ProgressTokenSchema","CursorSchema","TaskMetadataSchema","RelatedTaskMetadataSchema","RequestMetaSchema","BaseRequestParamsSchema","TaskAugmentedRequestParamsSchema","RequestSchema","NotificationsParamsSchema","NotificationSchema","ResultSchema","RequestIdSchema","EmptyResultSchema","CancelledNotificationParamsSchema","CancelledNotificationSchema","IconSchema","IconsSchema","BaseMetadataSchema","ImplementationSchema","FormElicitationCapabilitySchema","JSONObjectSchema","ElicitationCapabilitySchema","ClientTasksCapabilitySchema","ServerTasksCapabilitySchema","ClientCapabilitiesSchema","InitializeRequestParamsSchema","InitializeRequestSchema","ServerCapabilitiesSchema","InitializeResultSchema","InitializedNotificationSchema","PingRequestSchema","ProgressSchema","ProgressNotificationParamsSchema","ProgressNotificationSchema","PaginatedRequestParamsSchema","PaginatedRequestSchema","PaginatedResultSchema","ResourceContentsSchema","TextResourceContentsSchema","Base64Schema","BlobResourceContentsSchema","RoleSchema","AnnotationsSchema","ResourceSchema","ResourceTemplateSchema","ListResourcesRequestSchema","ListResourcesResultSchema","ListResourceTemplatesRequestSchema","ListResourceTemplatesResultSchema","ResourceRequestParamsSchema","ReadResourceRequestParamsSchema","ReadResourceRequestSchema","ReadResourceResultSchema","ResourceListChangedNotificationSchema","SubscribeRequestParamsSchema","SubscribeRequestSchema","UnsubscribeRequestParamsSchema","UnsubscribeRequestSchema","ResourceUpdatedNotificationParamsSchema","ResourceUpdatedNotificationSchema","PromptArgumentSchema","PromptSchema","ListPromptsRequestSchema","ListPromptsResultSchema","GetPromptRequestParamsSchema","GetPromptRequestSchema","TextContentSchema","ImageContentSchema","AudioContentSchema","ToolUseContentSchema","EmbeddedResourceSchema","ResourceLinkSchema","ContentBlockSchema","PromptMessageSchema","GetPromptResultSchema","PromptListChangedNotificationSchema","ToolAnnotationsSchema","ToolExecutionSchema","ToolSchema","ListToolsRequestSchema","ListToolsResultSchema","CallToolResultSchema","CallToolRequestParamsSchema","CallToolRequestSchema","ToolListChangedNotificationSchema","LoggingLevelSchema","SetLevelRequestParamsSchema","SetLevelRequestSchema","LoggingMessageNotificationParamsSchema","LoggingMessageNotificationSchema","ModelHintSchema","ModelPreferencesSchema","ToolChoiceSchema","ToolResultContentSchema","SamplingContentSchema","SamplingMessageContentBlockSchema","SamplingMessageSchema","CreateMessageRequestParamsSchema","CreateMessageRequestSchema","CreateMessageResultSchema","CreateMessageResultWithToolsSchema","BooleanSchemaSchema","StringSchemaSchema","NumberSchemaSchema","UntitledSingleSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","LegacyTitledEnumSchemaSchema","SingleSelectEnumSchemaSchema","UntitledMultiSelectEnumSchemaSchema","TitledMultiSelectEnumSchemaSchema","MultiSelectEnumSchemaSchema","EnumSchemaSchema","PrimitiveSchemaDefinitionSchema","ElicitRequestFormParamsSchema","ElicitRequestURLParamsSchema","ElicitRequestParamsSchema","ElicitRequestSchema","ElicitationCompleteNotificationParamsSchema","ElicitationCompleteNotificationSchema","ElicitResultSchema","ResourceTemplateReferenceSchema","PromptReferenceSchema","CompleteRequestParamsSchema","CompleteRequestSchema","CompleteResultSchema","RootSchema","ListRootsRequestSchema","ListRootsResultSchema","RootsListChangedNotificationSchema","TaskCreationParamsSchema","TaskStatusSchema","TaskSchema","CreateTaskResultSchema","TaskStatusNotificationParamsSchema","TaskStatusNotificationSchema","GetTaskRequestSchema","GetTaskResultSchema","GetTaskPayloadRequestSchema","GetTaskPayloadResultSchema","ListTasksRequestSchema","ListTasksResultSchema","CancelTaskRequestSchema","CancelTaskResultSchema","ClientRequestSchema","ClientNotificationSchema","ClientResultSchema","ServerRequestSchema","ServerNotificationSchema","ServerResultSchema","resultSchemas: { readonly [M in Rev2025TypedRequestMethod]: z.ZodType<ResultTypeMap[M]> }","EmptyResultSchema","InitializeResultSchema","CompleteResultSchema","GetPromptResultSchema","ListPromptsResultSchema","ListResourcesResultSchema","ListResourceTemplatesResultSchema","ReadResourceResultSchema","CallToolResultSchema","ListToolsResultSchema","CreateMessageResultWithToolsSchema","ElicitResultSchema","ListRootsResultSchema","requestSchemas: { readonly [M in Rev2025RequestMethod]: z.ZodType<Extract<WireRequest, { method: M }>> }","PingRequestSchema","InitializeRequestSchema","CompleteRequestSchema","SetLevelRequestSchema","GetPromptRequestSchema","ListPromptsRequestSchema","ListResourcesRequestSchema","ListResourceTemplatesRequestSchema","ReadResourceRequestSchema","SubscribeRequestSchema","UnsubscribeRequestSchema","CallToolRequestSchema","ListToolsRequestSchema","GetTaskRequestSchema","GetTaskPayloadRequestSchema","ListTasksRequestSchema","CancelTaskRequestSchema","CreateMessageRequestSchema","ElicitRequestSchema","ListRootsRequestSchema","notificationSchemas: { readonly [M in Rev2025NotificationMethod]: z.ZodType<Extract<WireNotification, { method: M }>> }","CancelledNotificationSchema","ProgressNotificationSchema","InitializedNotificationSchema","RootsListChangedNotificationSchema","TaskStatusNotificationSchema","LoggingMessageNotificationSchema","ResourceUpdatedNotificationSchema","ResourceListChangedNotificationSchema","ToolListChangedNotificationSchema","PromptListChangedNotificationSchema","ElicitationCompleteNotificationSchema","rev2025RequestMethods: readonly string[]","rev2025NotificationMethods: readonly string[]","isPlainObject","triState","NOT_IN_ERA: ValidateOutcome<never>","rev2025Codec: WireCodec","NOT_IN_ERA","CreateMessageResultWithToolsSchema","CreateMessageResultSchema","RESULT_CACHE_HINT_FALLBACK: unique symbol","merged: CacheHint","code: number","data?: unknown","EXTENDED_RESULT_TYPE_METHODS: readonly string[]","JSONValueSchema: z.ZodType<JSONValue, JSONValue>","JSONValueSchema","JSONObjectSchema: z.ZodType<JSONObject, JSONObject>","ProgressTokenSchema","CursorSchema","RequestIdSchema","RoleSchema","LoggingLevelSchema","Base64Schema","TaskMetadataSchema","RelatedTaskMetadataSchema","RequestMetaSchema","BaseRequestParamsSchema","TaskAugmentedRequestParamsSchema","NotificationsParamsSchema","NotificationSchema","IconSchema","IconsSchema","BaseMetadataSchema","ImplementationSchema","FormElicitationCapabilitySchema","JSONObjectSchema","ElicitationCapabilitySchema","ClientTasksCapabilitySchema","ServerTasksCapabilitySchema","ClientCapabilitiesSchema","ServerCapabilitiesSchema","ProgressSchema","ProgressNotificationParamsSchema","ProgressNotificationSchema","LoggingMessageNotificationParamsSchema","LoggingMessageNotificationSchema","ResourceContentsSchema","TextResourceContentsSchema","BlobResourceContentsSchema","AnnotationsSchema","ResourceSchema","ResourceTemplateSchema","ResourceListChangedNotificationSchema","ResourceUpdatedNotificationParamsSchema","ResourceUpdatedNotificationSchema","PromptArgumentSchema","PromptSchema","PromptListChangedNotificationSchema","TextContentSchema","ImageContentSchema","AudioContentSchema","ToolUseContentSchema","EmbeddedResourceSchema","ResourceLinkSchema","ContentBlockSchema","PromptMessageSchema","ToolAnnotationsSchema","ToolListChangedNotificationSchema","ModelHintSchema","ModelPreferencesSchema","ToolChoiceSchema","BooleanSchemaSchema","StringSchemaSchema","NumberSchemaSchema","UntitledSingleSelectEnumSchemaSchema","TitledSingleSelectEnumSchemaSchema","LegacyTitledEnumSchemaSchema","SingleSelectEnumSchemaSchema","UntitledMultiSelectEnumSchemaSchema","TitledMultiSelectEnumSchemaSchema","MultiSelectEnumSchemaSchema","EnumSchemaSchema","PrimitiveSchemaDefinitionSchema","ElicitRequestFormParamsSchema","ResourceTemplateReferenceSchema","PromptReferenceSchema","RootSchema","ToolSchema","ToolResultContentSchema","SamplingMessageContentBlockSchema","SamplingMessageSchema","ResultSchema","PaginatedResultSchema","CallToolResultSchema","ListToolsResultSchema","ListPromptsResultSchema","GetPromptResultSchema","ListResourcesResultSchema","ListResourceTemplatesResultSchema","ReadResourceResultSchema","CompleteResultSchema","DiscoverResultSchema","CreateMessageRequestParamsSchema","CreateMessageRequestSchema","ListRootsRequestSchema","CreateMessageResultSchema","ListRootsResultSchema","ElicitResultSchema","ElicitRequestURLParamsSchema","ElicitRequestParamsSchema","ElicitRequestSchema","CallToolRequestSchema","ListToolsRequestSchema","ListPromptsRequestSchema","GetPromptRequestSchema","ListResourcesRequestSchema","ListResourceTemplatesRequestSchema","ReadResourceRequestSchema","CompleteRequestSchema","DiscoverRequestSchema","SubscriptionFilterSchema","SubscriptionsListenRequestSchema","SubscriptionsListenResultMetaSchema","SubscriptionsListenResultSchema","dispatchRequestSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType<{ method: M }> }","dispatchResultSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType }","SubscriptionsAcknowledgedNotificationSchema","CancelledNotificationParamsSchema","CancelledNotificationSchema","notificationSchemas2026: { readonly [M in Rev2026NotificationMethod]: z.ZodType<{ method: M }> }","JSONRPCResultResponseSchema","inputRequestSchemas2026: Record<InputRequestMethod2026, z.ZodType>","ElicitRequestParamsSchema","CreateMessageRequestParamsSchema","inputResponseSchemas2026: Record<InputRequestMethod2026, z.ZodType>","ElicitResultSchema","CreateMessageResultSchema","ListRootsResultSchema","rev2026RequestMethods: readonly string[]","rev2026NotificationMethods: readonly string[]","isPlainObject","NOT_IN_ERA: ValidateOutcome<never>","REQUIRED_ENVELOPE_KEYS: readonly string[]","next: Record<string, unknown>","rev2026Codec: WireCodec & {\n /**\n * @deprecated Off-interface in-band registry probe retained for the\n * existing inputRequiredFunnel pin. Use {@link WireCodec.validateInputRequest}\n * — its `not-in-era` outcome is the membership signal.\n */\n inputRequestSchema(method: string): unknown;\n}","issues: EnvelopeIssue[]","WIRE_RESULT_SCHEMAS: Record<string, z.ZodType>","CallToolResultSchema","ListToolsResultSchema","GetPromptResultSchema","ListPromptsResultSchema","ListResourcesResultSchema","ListResourceTemplatesResultSchema","ReadResourceResultSchema","CompleteResultSchema","DiscoverResultSchema","ALL_CODECS: readonly WireCodec[]","isPlainObject","JSONValueSchema: z.ZodType<JSONValue, JSONValue>","JSONObjectSchema: z.ZodType<JSONObject, JSONObject>","JSONArraySchema: z.ZodType<JSONArray, JSONArray>","PERMITTED_X_MCP_HEADER_TYPES: ReadonlySet<string>","declarations: XMcpHeaderDeclaration[]","fault","branches: unknown[]","OBJECT_VALUED_SUBSCHEMA_KEYWORDS: ReadonlySet<string>","node: unknown","INBOUND_VALIDATION_LADDER: readonly InboundValidationRungDescriptor[]","LADDER_ERROR_HTTP_STATUS: Readonly<Record<number, number>>","MCP_NAME_HEADER_SOURCE: Readonly<Record<string, 'name' | 'uri'>>","isPlainObject","inputRequired: InputRequiredBuilder","_specTypeSchemas: Record<string, StandardSchemaV1>","_isSpecType: Record<string, (value: unknown) => boolean>","schemas","specTypeSchemas: SchemaRecord","isSpecType: GuardRecord","result: Record<string, unknown>","RESERVED_ENVELOPE_META_KEYS: readonly string[]","isPlainObject","lifted: LiftedWireMaterial","nextParams: Record<string, unknown>","envelope: Record<string, unknown>","nextMeta: Record<string, unknown>","writeNegotiatedProtocolVersion: <ContextT extends BaseContext>(instance: Protocol<ContextT>, version: string | undefined) => void","_options?: ProtocolOptions","errorResponse: JSONRPCErrorResponse","baseCtx: BaseContext","encoded: Result","response: JSONRPCResponse","onAbort: (() => void) | undefined","cleanupMessageId: number | undefined","jsonrpcRequest: JSONRPCRequest","decoded: ReturnType<WireCodec['decodeResult']>","flow: NonCompleteResultFlow<T>","stored: (request: JSONRPCRequest, ctx: ContextT) => Promise<Result>","result: T","accepted: Record<string, unknown>","droppedKeys: string[]","warnings: string[]","parts: Array<string | { name: string; operator: string; names: string[]; exploded: boolean }>","name","value","patterns: Array<{ pattern: string; name: string }>","pattern: string","names: Array<{ name: string; exploded: boolean }>","result: Variables","onerror?: (error: Error) => void","honored: SubscriptionFilter","controller!: ReadableStreamDefaultController<Uint8Array>","unsubscribe: (() => void) | undefined","keepAliveTimer: ReturnType<typeof setInterval> | undefined","abortCleanup: (() => void) | undefined","CHANGE_NOTIFICATION_METHODS: ReadonlySet<string>","_maxSubscriptions: number","uriParam: unknown","out: NotificationBody[]","out: {\n jsonrpc: '2.0';\n id: RequestId;\n result: { resultType: 'complete'; _meta: { [SUBSCRIPTION_ID_META_KEY]: RequestId } };\n }[]","_host: LegacyInputRequiredShimHost","responses: Record<string, unknown> | undefined","coerced: [string, CoercedEmbeddedInputRequest][]","legOptions: RequestOptions","ctxNext: ServerContext","INPUT_REQUIRED_CAPABLE_METHODS: ReadonlySet<string>","writeClientIdentity: (server: Server, identity: PerRequestClientIdentity) => void","installDiscoverHandler: (server: Server, servedModernVersions: readonly string[]) => void","_serverInfo: Implementation","transportSessionId: string | undefined","threshold: LoggingLevel | undefined","rawRequestState: unknown","result: Result","formParams: ElicitRequestFormParams","toolDefinition: Tool","templateResources: Resource[]","metadata: ResourceMetadata","registeredResource: RegisteredResource","registeredResourceTemplate: RegisteredResourceTemplate","registeredPrompt: RegisteredPrompt","registeredTool: RegisteredTool","_callbacks: {\n /**\n * A callback to list all resources matching this template. This is required to be specified, even if `undefined`, to avoid accidentally forgetting resource listing.\n */\n list: ListResourcesCallback | undefined;\n\n /**\n * An optional callback to autocomplete variables within the URI template. Useful for clients and users to discover possible values.\n */\n complete?: {\n [variable: string]: CompleteResourceTemplateCallback;\n };\n }","callback","EMPTY_COMPLETION_RESULT: CompleteResult"],"sources":["../src/server/completable.ts","../../core-internal/src/auth/errors.ts","../../core-internal/src/errors/sdkErrors.ts","../../core-internal/src/shared/auth.ts","../../core-internal/src/shared/authUtils.ts","../../core-internal/src/shared/clientCapabilityRequirements.ts","../../core-internal/src/types/constants.ts","../../core-internal/src/shared/protocolEras.ts","../../core-internal/src/wire/textFallback.ts","../../core-internal/src/wire/rev2025-11-25/legacyWrap.ts","../../core-internal/src/wire/rev2025-11-25/schemas.ts","../../core-internal/src/wire/rev2025-11-25/registry.ts","../../core-internal/src/wire/rev2025-11-25/codec.ts","../../core-internal/src/shared/resultCacheHints.ts","../../core-internal/src/types/enums.ts","../../core-internal/src/types/errors.ts","../../core-internal/src/wire/rev2026-07-28/encodeContract.ts","../../core-internal/src/wire/rev2026-07-28/schemas.ts","../../core-internal/src/wire/rev2026-07-28/inputRequired.ts","../../core-internal/src/wire/rev2026-07-28/registry.ts","../../core-internal/src/wire/rev2026-07-28/codec.ts","../../core-internal/src/wire/codec.ts","../../core-internal/src/shared/envelope.ts","../../core-internal/src/types/schemas.ts","../../core-internal/src/types/guards.ts","../../core-internal/src/shared/mcpParamHeaders.ts","../../core-internal/src/shared/inboundClassification.ts","../../core-internal/src/shared/inputRequired.ts","../../core-internal/src/shared/inputRequiredDriver.ts","../../core-internal/src/types/specTypeSchema.ts","../../core-internal/src/util/standardSchema.ts","../../core-internal/src/wire/bootstrap.ts","../../core-internal/src/shared/protocol.ts","../../core-internal/src/shared/inputRequiredEngine.ts","../../core-internal/src/shared/metadataUtils.ts","../../core-internal/src/shared/stdio.ts","../../core-internal/src/shared/toolNameValidation.ts","../../core-internal/src/shared/transport.ts","../../core-internal/src/shared/uriTemplate.ts","../../core-internal/src/util/inMemory.ts","../../core-internal/src/util/schema.ts","../../core-internal/src/util/zodCompat.ts","../../core-internal/src/validators/fromJsonSchema.ts","../src/server/serverEventBus.ts","../src/server/listenRouter.ts","../src/server/legacyInputRequiredShim.ts","../src/server/server.ts","../src/server/mcp.ts"],"sourcesContent":["import type { StandardSchemaV1 } from '@modelcontextprotocol/core-internal';\n\nexport const COMPLETABLE_SYMBOL: unique symbol = Symbol.for('mcp.completable');\n\nexport type CompleteCallback<T extends StandardSchemaV1 = StandardSchemaV1> = (\n value: StandardSchemaV1.InferInput<T>,\n context?: {\n arguments?: Record<string, string>;\n }\n) => StandardSchemaV1.InferInput<T>[] | Promise<StandardSchemaV1.InferInput<T>[]>;\n\nexport type CompletableMeta<T extends StandardSchemaV1 = StandardSchemaV1> = {\n complete: CompleteCallback<T>;\n};\n\nexport type CompletableSchema<T extends StandardSchemaV1> = T & {\n [COMPLETABLE_SYMBOL]: CompletableMeta<T>;\n};\n\n/**\n * Wraps a schema to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP.\n *\n * @example\n * ```ts source=\"./completable.examples.ts#completable_basicUsage\"\n * server.registerPrompt(\n * 'review-code',\n * {\n * title: 'Code Review',\n * argsSchema: z.object({\n * language: completable(z.string().describe('Programming language'), value =>\n * ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => lang.startsWith(value))\n * )\n * })\n * },\n * ({ language }) => ({\n * messages: [\n * {\n * role: 'user' as const,\n * content: {\n * type: 'text' as const,\n * text: `Review this ${language} code.`\n * }\n * }\n * ]\n * })\n * );\n * ```\n *\n * @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions\n */\nexport function completable<T extends StandardSchemaV1>(schema: T, complete: CompleteCallback<T>): CompletableSchema<T> {\n Object.defineProperty(schema as object, COMPLETABLE_SYMBOL, {\n value: { complete } as CompletableMeta<T>,\n enumerable: false,\n writable: false,\n configurable: false\n });\n return schema as CompletableSchema<T>;\n}\n\n/**\n * Checks if a schema is completable (has completion metadata).\n */\nexport function isCompletable(schema: unknown): schema is CompletableSchema<StandardSchemaV1> {\n return !!schema && typeof schema === 'object' && COMPLETABLE_SYMBOL in (schema as object);\n}\n\n/**\n * Gets the completer callback from a completable schema, if it exists.\n */\nexport function getCompleter<T extends StandardSchemaV1>(schema: T): CompleteCallback<T> | undefined {\n const meta = (schema as unknown as { [COMPLETABLE_SYMBOL]?: CompletableMeta<T> })[COMPLETABLE_SYMBOL];\n return meta?.complete as CompleteCallback<T> | undefined;\n}\n","import type { OAuthErrorResponse } from '../shared/auth';\n\n/**\n * OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749}\n * and extensions.\n */\nexport enum OAuthErrorCode {\n /**\n * The request is missing a required parameter, includes an invalid parameter value,\n * includes a parameter more than once, or is otherwise malformed.\n */\n InvalidRequest = 'invalid_request',\n\n /**\n * Client authentication failed (e.g., unknown client, no client authentication included,\n * or unsupported authentication method).\n */\n InvalidClient = 'invalid_client',\n\n /**\n * The provided authorization grant or refresh token is invalid, expired, revoked,\n * does not match the redirection URI used in the authorization request, or was issued to another client.\n */\n InvalidGrant = 'invalid_grant',\n\n /**\n * The authenticated client is not authorized to use this authorization grant type.\n */\n UnauthorizedClient = 'unauthorized_client',\n\n /**\n * The authorization grant type is not supported by the authorization server.\n */\n UnsupportedGrantType = 'unsupported_grant_type',\n\n /**\n * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner.\n */\n InvalidScope = 'invalid_scope',\n\n /**\n * The resource owner or authorization server denied the request.\n */\n AccessDenied = 'access_denied',\n\n /**\n * The authorization server encountered an unexpected condition that prevented it from fulfilling the request.\n */\n ServerError = 'server_error',\n\n /**\n * The authorization server is currently unable to handle the request due to temporary overloading or maintenance.\n */\n TemporarilyUnavailable = 'temporarily_unavailable',\n\n /**\n * The authorization server does not support obtaining an authorization code using this method.\n */\n UnsupportedResponseType = 'unsupported_response_type',\n\n /**\n * The authorization server does not support the requested token type.\n */\n UnsupportedTokenType = 'unsupported_token_type',\n\n /**\n * The access token provided is expired, revoked, malformed, or invalid for other reasons.\n */\n InvalidToken = 'invalid_token',\n\n /**\n * The HTTP method used is not allowed for this endpoint. (Custom, non-standard error)\n */\n MethodNotAllowed = 'method_not_allowed',\n\n /**\n * Rate limit exceeded. (Custom, non-standard error based on RFC 6585)\n */\n TooManyRequests = 'too_many_requests',\n\n /**\n * The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591)\n */\n InvalidClientMetadata = 'invalid_client_metadata',\n\n /**\n * The value of one or more redirection URIs is invalid. (Dynamic client registration - RFC 7591 §3.2.2)\n */\n InvalidRedirectUri = 'invalid_redirect_uri',\n\n /**\n * The request requires higher privileges than provided by the access token.\n */\n InsufficientScope = 'insufficient_scope',\n\n /**\n * The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707)\n */\n InvalidTarget = 'invalid_target'\n}\n\n/**\n * OAuth error class for all OAuth-related errors.\n */\nexport class OAuthError extends Error {\n constructor(\n public readonly code: OAuthErrorCode | string,\n message: string,\n public readonly errorUri?: string\n ) {\n super(message);\n this.name = 'OAuthError';\n }\n\n /**\n * Converts the error to a standard OAuth error response object.\n */\n toResponseObject(): OAuthErrorResponse {\n const response: OAuthErrorResponse = {\n error: this.code,\n error_description: this.message\n };\n\n if (this.errorUri) {\n response.error_uri = this.errorUri;\n }\n\n return response;\n }\n\n /**\n * Creates an {@linkcode OAuthError} from an OAuth error response.\n */\n static fromResponse(response: OAuthErrorResponse): OAuthError {\n return new OAuthError(response.error as OAuthErrorCode, response.error_description ?? response.error, response.error_uri);\n }\n}\n","/**\n * Error codes for SDK errors (local errors that never cross the wire).\n * Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses\n * descriptive string values for better developer experience.\n *\n * These errors are thrown locally by the SDK and are never serialized as\n * JSON-RPC error responses.\n */\nexport enum SdkErrorCode {\n // State errors\n /** Transport is not connected */\n NotConnected = 'NOT_CONNECTED',\n /** Transport is already connected */\n AlreadyConnected = 'ALREADY_CONNECTED',\n /** Protocol is not initialized */\n NotInitialized = 'NOT_INITIALIZED',\n\n // Capability errors\n /** Required capability is not supported by the remote side */\n CapabilityNotSupported = 'CAPABILITY_NOT_SUPPORTED',\n\n // Transport errors\n /** Request timed out waiting for response */\n RequestTimeout = 'REQUEST_TIMEOUT',\n /** Connection was closed */\n ConnectionClosed = 'CONNECTION_CLOSED',\n /** Failed to send message */\n SendFailed = 'SEND_FAILED',\n /** Response result failed local schema validation */\n InvalidResult = 'INVALID_RESULT',\n /**\n * The response carried a `resultType` discriminator (protocol revision\n * 2026-07-28) naming a result kind this client cannot consume yet, e.g.\n * `input_required`. The kind is carried in `data.resultType`.\n */\n UnsupportedResultType = 'UNSUPPORTED_RESULT_TYPE',\n /**\n * The multi-round-trip auto-fulfilment driver exhausted its round cap\n * (`inputRequired.maxRounds`) without the server returning a complete\n * result. `data.rounds` carries the cap that was hit and\n * `data.lastResult` carries the last `input_required` payload received\n * (`{ inputRequests, requestState? }`), so callers can inspect or resume\n * the flow manually.\n */\n InputRequiredRoundsExceeded = 'INPUT_REQUIRED_ROUNDS_EXCEEDED',\n /**\n * The auto-aggregating no-`cursor` `listTools()` / `listPrompts()` /\n * `listResources()` / `listResourceTemplates()` walk hit the\n * `ClientOptions.listMaxPages` cap without the server's pagination\n * converging. `data.method` carries the list verb and\n * `data.listMaxPages` the cap that was hit; raise the cap or fall back to\n * explicit per-page `{ cursor }` calls.\n */\n ListPaginationExceeded = 'LIST_PAGINATION_EXCEEDED',\n /**\n * The spec method being sent does not exist on the negotiated protocol\n * version's wire era (e.g. `tasks/get` toward a 2026-07-28 peer, or\n * `server/discover` toward a 2025-era peer). Raised locally, before\n * anything reaches the transport. The method and era are carried in\n * `data.method` / `data.era`.\n */\n MethodNotSupportedByProtocolVersion = 'METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION',\n /**\n * Protocol-era negotiation at connect time failed without producing either a\n * usable modern (2026-07-28+) era or a definitive legacy fallback signal —\n * e.g. the negotiation mode forbids falling back (`pin`), or the probe hit a\n * network failure (a typed connect error, never an era verdict).\n *\n * Negotiation-phase only: this code is never used once an era is established.\n */\n EraNegotiationFailed = 'ERA_NEGOTIATION_FAILED',\n\n // Transport errors\n ClientHttpNotImplemented = 'CLIENT_HTTP_NOT_IMPLEMENTED',\n ClientHttpAuthentication = 'CLIENT_HTTP_AUTHENTICATION',\n ClientHttpForbidden = 'CLIENT_HTTP_FORBIDDEN',\n ClientHttpUnexpectedContent = 'CLIENT_HTTP_UNEXPECTED_CONTENT',\n ClientHttpFailedToOpenStream = 'CLIENT_HTTP_FAILED_TO_OPEN_STREAM',\n ClientHttpFailedToTerminateSession = 'CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION'\n}\n\n/**\n * SDK errors are local errors that never cross the wire.\n * They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors\n * that are serialized and sent as error responses.\n *\n * @example\n * ```ts source=\"./sdkErrors.examples.ts#SdkError_basicUsage\"\n * try {\n * // Throwing an SDK error\n * throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected');\n * } catch (error) {\n * // Checking error type by code\n * if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) {\n * // Handle timeout\n * }\n * }\n * ```\n */\nexport class SdkError extends Error {\n constructor(\n public readonly code: SdkErrorCode,\n message: string,\n public readonly data?: unknown\n ) {\n super(message);\n this.name = 'SdkError';\n }\n}\n\n/**\n * Typed shape for HTTP error data carried by {@linkcode SdkHttpError}.\n */\nexport interface SdkHttpErrorData {\n status: number;\n statusText?: string;\n [key: string]: unknown;\n}\n\n/**\n * An {@linkcode SdkError} subclass for HTTP transport failures.\n *\n * Thrown by the streamable HTTP transport when the server responds with a\n * non-OK status code. Narrows {@linkcode SdkError.data | data} to\n * {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status\n * without unsafe casting.\n *\n * @example\n * ```ts source=\"./sdkErrors.examples.ts#SdkHttpError_basicUsage\"\n * if (error instanceof SdkHttpError) {\n * console.log(error.status); // number\n * console.log(error.statusText); // string | undefined\n * }\n * ```\n */\nexport class SdkHttpError extends SdkError {\n declare readonly data: SdkHttpErrorData;\n\n constructor(code: SdkErrorCode, message: string, data: SdkHttpErrorData) {\n super(code, message, data);\n this.name = 'SdkHttpError';\n }\n\n get status(): number {\n return this.data.status;\n }\n\n get statusText(): string | undefined {\n return this.data.statusText;\n }\n}\n","import * as z from 'zod/v4';\n\n/**\n * Reusable URL validation that disallows `javascript:` scheme\n */\nexport const SafeUrlSchema = z\n .url()\n .superRefine((val, ctx) => {\n if (!URL.canParse(val)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'URL must be parseable',\n fatal: true\n });\n\n return z.NEVER;\n }\n })\n .refine(\n url => {\n const u = new URL(url);\n return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:';\n },\n { message: 'URL cannot use javascript:, data:, or vbscript: scheme' }\n );\n\n/**\n * RFC 9728 OAuth Protected Resource Metadata\n */\nexport const OAuthProtectedResourceMetadataSchema = z.looseObject({\n resource: z.string().url(),\n authorization_servers: z.array(SafeUrlSchema).optional(),\n jwks_uri: z.string().url().optional(),\n scopes_supported: z.array(z.string()).optional(),\n bearer_methods_supported: z.array(z.string()).optional(),\n resource_signing_alg_values_supported: z.array(z.string()).optional(),\n resource_name: z.string().optional(),\n resource_documentation: z.string().optional(),\n resource_policy_uri: z.string().url().optional(),\n resource_tos_uri: z.string().url().optional(),\n tls_client_certificate_bound_access_tokens: z.boolean().optional(),\n authorization_details_types_supported: z.array(z.string()).optional(),\n dpop_signing_alg_values_supported: z.array(z.string()).optional(),\n dpop_bound_access_tokens_required: z.boolean().optional()\n});\n\n/**\n * RFC 8414 OAuth 2.0 Authorization Server Metadata\n */\nexport const OAuthMetadataSchema = z.looseObject({\n issuer: z.string(),\n authorization_endpoint: SafeUrlSchema,\n token_endpoint: SafeUrlSchema,\n registration_endpoint: SafeUrlSchema.optional(),\n scopes_supported: z.array(z.string()).optional(),\n response_types_supported: z.array(z.string()),\n response_modes_supported: z.array(z.string()).optional(),\n grant_types_supported: z.array(z.string()).optional(),\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n service_documentation: SafeUrlSchema.optional(),\n revocation_endpoint: SafeUrlSchema.optional(),\n revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n introspection_endpoint: z.string().optional(),\n introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n code_challenge_methods_supported: z.array(z.string()).optional(),\n client_id_metadata_document_supported: z.boolean().optional(),\n // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod .catch(), not a Promise chain\n authorization_response_iss_parameter_supported: z.boolean().optional().catch(undefined)\n});\n\n/**\n * OpenID Connect Discovery 1.0 Provider Metadata\n *\n * @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata\n */\nexport const OpenIdProviderMetadataSchema = z.looseObject({\n issuer: z.string(),\n authorization_endpoint: SafeUrlSchema,\n token_endpoint: SafeUrlSchema,\n userinfo_endpoint: SafeUrlSchema.optional(),\n jwks_uri: SafeUrlSchema,\n registration_endpoint: SafeUrlSchema.optional(),\n scopes_supported: z.array(z.string()).optional(),\n response_types_supported: z.array(z.string()),\n response_modes_supported: z.array(z.string()).optional(),\n grant_types_supported: z.array(z.string()).optional(),\n acr_values_supported: z.array(z.string()).optional(),\n subject_types_supported: z.array(z.string()),\n id_token_signing_alg_values_supported: z.array(z.string()),\n id_token_encryption_alg_values_supported: z.array(z.string()).optional(),\n id_token_encryption_enc_values_supported: z.array(z.string()).optional(),\n userinfo_signing_alg_values_supported: z.array(z.string()).optional(),\n userinfo_encryption_alg_values_supported: z.array(z.string()).optional(),\n userinfo_encryption_enc_values_supported: z.array(z.string()).optional(),\n request_object_signing_alg_values_supported: z.array(z.string()).optional(),\n request_object_encryption_alg_values_supported: z.array(z.string()).optional(),\n request_object_encryption_enc_values_supported: z.array(z.string()).optional(),\n token_endpoint_auth_methods_supported: z.array(z.string()).optional(),\n token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(),\n display_values_supported: z.array(z.string()).optional(),\n claim_types_supported: z.array(z.string()).optional(),\n claims_supported: z.array(z.string()).optional(),\n service_documentation: z.string().optional(),\n claims_locales_supported: z.array(z.string()).optional(),\n ui_locales_supported: z.array(z.string()).optional(),\n claims_parameter_supported: z.boolean().optional(),\n request_parameter_supported: z.boolean().optional(),\n request_uri_parameter_supported: z.boolean().optional(),\n require_request_uri_registration: z.boolean().optional(),\n op_policy_uri: SafeUrlSchema.optional(),\n op_tos_uri: SafeUrlSchema.optional(),\n client_id_metadata_document_supported: z.boolean().optional(),\n // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod .catch(), not a Promise chain\n authorization_response_iss_parameter_supported: z.boolean().optional().catch(undefined)\n});\n\n/**\n * OpenID Connect Discovery metadata that may include OAuth 2.0 fields\n * This schema represents the real-world scenario where OIDC providers\n * return a mix of OpenID Connect and OAuth 2.0 metadata fields\n */\nexport const OpenIdProviderDiscoveryMetadataSchema = z.object({\n ...OpenIdProviderMetadataSchema.shape,\n ...OAuthMetadataSchema.pick({\n code_challenge_methods_supported: true\n }).shape\n});\n\n/**\n * OAuth 2.1 token response\n */\nexport const OAuthTokensSchema = z\n .object({\n access_token: z.string(),\n id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect\n token_type: z.string(),\n expires_in: z.coerce.number().optional(),\n scope: z.string().optional(),\n refresh_token: z.string().optional()\n })\n .strip();\n\n/**\n * RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens.\n *\n * `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when\n * the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive,\n * so strict checking rejects conformant IdPs.\n */\nexport const IdJagTokenExchangeResponseSchema = z\n .object({\n issued_token_type: z.literal('urn:ietf:params:oauth:token-type:id-jag'),\n access_token: z.string(),\n token_type: z.string().optional(),\n expires_in: z.number().optional(),\n scope: z.string().optional()\n })\n .strip();\n\nexport type IdJagTokenExchangeResponse = z.infer<typeof IdJagTokenExchangeResponseSchema>;\n\n/**\n * OAuth 2.1 error response\n */\nexport const OAuthErrorResponseSchema = z.object({\n error: z.string(),\n error_description: z.string().optional(),\n error_uri: z.string().optional()\n});\n\n/**\n * Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri`\n */\n// eslint-disable-next-line unicorn/no-useless-undefined\nexport const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined));\n\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata\n */\nexport const OAuthClientMetadataSchema = z\n .object({\n redirect_uris: z.array(SafeUrlSchema),\n token_endpoint_auth_method: z.string().optional(),\n grant_types: z.array(z.string()).optional(),\n response_types: z.array(z.string()).optional(),\n /**\n * OIDC Dynamic Client Registration `application_type`. MCP clients MUST set\n * this to `'native'` or `'web'` when registering (SEP-837); the SDK defaults\n * it from `redirect_uris` when omitted. Typed as `string` (not an enum) so\n * that parsing an authorization server's registration response — which under\n * RFC 7591 may echo extension values — never rejects the document on this\n * field alone.\n */\n application_type: z.string().optional(),\n client_name: z.string().optional(),\n client_uri: SafeUrlSchema.optional(),\n logo_uri: OptionalSafeUrlSchema,\n scope: z.string().optional(),\n contacts: z.array(z.string()).optional(),\n tos_uri: OptionalSafeUrlSchema,\n policy_uri: z.string().optional(),\n jwks_uri: SafeUrlSchema.optional(),\n jwks: z.any().optional(),\n software_id: z.string().optional(),\n software_version: z.string().optional(),\n software_statement: z.string().optional()\n })\n .strip();\n\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration client information\n */\nexport const OAuthClientInformationSchema = z\n .object({\n client_id: z.string(),\n client_secret: z.string().optional(),\n client_id_issued_at: z.number().optional(),\n client_secret_expires_at: z.number().optional()\n })\n .strip();\n\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata)\n */\nexport const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);\n\n/**\n * RFC 7591 OAuth 2.0 Dynamic Client Registration error response\n */\nexport const OAuthClientRegistrationErrorSchema = z\n .object({\n error: z.string(),\n error_description: z.string().optional()\n })\n .strip();\n\n/**\n * RFC 7009 OAuth 2.0 Token Revocation request\n */\nexport const OAuthTokenRevocationRequestSchema = z\n .object({\n token: z.string(),\n token_type_hint: z.string().optional()\n })\n .strip();\n\nexport type OAuthMetadata = z.infer<typeof OAuthMetadataSchema>;\nexport type OpenIdProviderMetadata = z.infer<typeof OpenIdProviderMetadataSchema>;\nexport type OpenIdProviderDiscoveryMetadata = z.infer<typeof OpenIdProviderDiscoveryMetadataSchema>;\n\nexport type OAuthTokens = z.infer<typeof OAuthTokensSchema>;\nexport type OAuthErrorResponse = z.infer<typeof OAuthErrorResponseSchema>;\nexport type OAuthClientMetadata = z.infer<typeof OAuthClientMetadataSchema>;\nexport type OAuthClientInformation = z.infer<typeof OAuthClientInformationSchema>;\nexport type OAuthClientInformationFull = z.infer<typeof OAuthClientInformationFullSchema>;\nexport type OAuthClientInformationMixed = OAuthClientInformation | OAuthClientInformationFull;\n\n/**\n * {@linkcode OAuthTokens} as persisted by an `OAuthClientProvider`. Adds an\n * SDK-stamped authorization-server `issuer` identifier so stored tokens are\n * bound to the AS that issued them. The `issuer` field is **not** part of the\n * RFC 6749 wire response and is intentionally absent from the wire-response\n * schema; the client SDK writes it before calling `saveTokens`.\n */\nexport type StoredOAuthTokens = OAuthTokens & { issuer?: string };\n\n/**\n * {@linkcode OAuthClientInformationMixed} as persisted by an\n * `OAuthClientProvider`. Adds an SDK-stamped authorization-server `issuer`\n * identifier so stored client credentials are bound to the AS that issued them.\n * The `issuer` field is **not** part of the RFC 7591 wire response and is\n * intentionally absent from the wire-response schema; the client SDK writes it\n * before calling `saveClientInformation`.\n */\nexport type StoredOAuthClientInformation = OAuthClientInformationMixed & { issuer?: string };\n\nexport type OAuthClientRegistrationError = z.infer<typeof OAuthClientRegistrationErrorSchema>;\nexport type OAuthTokenRevocationRequest = z.infer<typeof OAuthTokenRevocationRequestSchema>;\nexport type OAuthProtectedResourceMetadata = z.infer<typeof OAuthProtectedResourceMetadataSchema>;\n\n// Unified type for authorization server metadata\nexport type AuthorizationServerMetadata = OAuthMetadata | OpenIdProviderDiscoveryMetadata;\n","/**\n * Utilities for handling OAuth resource URIs.\n */\n\n/**\n * Converts a server URL to a resource URL by removing the fragment.\n * {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2}\n * states that resource URIs \"MUST NOT include a fragment component\".\n * Keeps everything else unchanged (scheme, domain, port, path, query).\n */\nexport function resourceUrlFromServerUrl(url: URL | string): URL {\n const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href);\n resourceURL.hash = ''; // Remove fragment\n return resourceURL;\n}\n\n/**\n * Checks if a requested resource URL matches a configured resource URL.\n * A requested resource matches if it has the same scheme, domain, port,\n * and its path starts with the configured resource's path.\n *\n * @param options - The options object\n * @param options.requestedResource - The resource URL being requested\n * @param options.configuredResource - The resource URL that has been configured\n * @returns true if the requested resource matches the configured resource, false otherwise\n */\nexport function checkResourceAllowed({\n requestedResource,\n configuredResource\n}: {\n requestedResource: URL | string;\n configuredResource: URL | string;\n}): boolean {\n const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href);\n const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href);\n\n // Compare the origin (scheme, domain, and port)\n if (requested.origin !== configured.origin) {\n return false;\n }\n\n // Handle cases like requested=/foo and configured=/foo/\n if (requested.pathname.length < configured.pathname.length) {\n return false;\n }\n\n // Check if the requested path starts with the configured path\n // Ensure both paths end with / for proper comparison\n // This ensures that if we have paths like \"/api\" and \"/api/users\",\n // we properly detect that \"/api/users\" is a subpath of \"/api\"\n // By adding a trailing slash if missing, we avoid false positives\n // where paths like \"/api123\" would incorrectly match \"/api\"\n const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/';\n const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/';\n\n return requestedPath.startsWith(configuredPath);\n}\n","/**\n * Client-capability requirements for inbound requests (protocol revision\n * 2026-07-28).\n *\n * The 2026-07-28 revision carries the client's declared capabilities on every\n * request (`io.modelcontextprotocol/clientCapabilities`), and a server MUST\n * NOT rely on capabilities the client did not declare: when processing a\n * request requires an undeclared capability, the server answers\n * `MissingRequiredClientCapabilityError` (`-32021`) with\n * `data.requiredCapabilities` listing what is missing — HTTP status `400` on\n * HTTP transports.\n *\n * This module is the shared, pure half of that rule. It is written for three\n * call sites:\n *\n * 1. the pre-dispatch feature gate at the HTTP entry (a request to a method\n * whose processing structurally requires a client capability is refused\n * before dispatch),\n * 2. the outbound input-request leg of multi round-trip requests (a server\n * must not embed an input request the client cannot satisfy) — lands with\n * the input-request engine,\n * 3. the legacy-session pre-check before bridging input requests onto a\n * 2025-era session — lands with that bridge.\n *\n * All three share {@linkcode missingClientCapabilities}; the per-method\n * requirement table below feeds call site 1 only.\n */\nimport type { ClientCapabilities } from '../types/types';\n\n/**\n * Inbound request methods whose processing structurally requires a client\n * capability, keyed by method, valued by the capabilities required.\n *\n * Currently empty: none of the request methods served on the 2026-07-28\n * registry unconditionally requires a client capability. Entries appear here\n * when such methods exist — for example requests whose handling embeds\n * elicitation or sampling input requests (the input-request engine), or\n * opt-in subscription delivery. Handler-conditional requirements (a specific\n * tool that needs sampling) are not expressible as a static method table and\n * are enforced at the point the requirement arises instead.\n */\nexport const REQUIRED_CLIENT_CAPABILITIES_BY_METHOD: Readonly<Record<string, ClientCapabilities>> = {};\n\n/**\n * The client capabilities a request method structurally requires, or\n * `undefined` when the method has no static requirement.\n */\nexport function requiredClientCapabilitiesForRequest(method: string): ClientCapabilities | undefined {\n return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD, method) ? REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method] : undefined;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/**\n * Whether a required nested member counts as declared even though it is not\n * spelled out: a bare `elicitation: {}` declaration (no mode sub-capability at\n * all) is read as form support — the pre-mode (2025) meaning of a bare\n * declaration — so an `elicitation.form` requirement treats it as satisfied.\n * Declaring any mode explicitly (for example `elicitation: { url: {} }`)\n * removes the implication.\n */\nfunction isImpliedCapabilityMember(capability: string, member: string, declaredValue: Record<string, unknown>): boolean {\n return capability === 'elicitation' && member === 'form' && declaredValue['form'] === undefined && declaredValue['url'] === undefined;\n}\n\n/**\n * The client capabilities an embedded multi-round-trip input request requires\n * (call site 2 — the outbound input-request leg): a server MUST NOT send an\n * `inputRequests` kind the request's declared client capabilities do not\n * cover. Returns `undefined` for entries whose method is not one of the\n * embedded input-request kinds (those are a server bug handled separately,\n * not a capability question).\n *\n * The requirement is mode-aware where the capability is: URL-mode elicitation\n * requires `elicitation.url`; form-mode (or mode-omitted) elicitation requires\n * `elicitation.form` (modes are sub-capabilities, and a server MUST NOT send a\n * mode the client did not declare); sampling with `tools`/`toolChoice`\n * requires `sampling.tools`. A bare `elicitation: {}` declaration satisfies\n * the form requirement — see {@linkcode missingClientCapabilities}.\n */\nexport function requiredClientCapabilitiesForInputRequest(entry: {\n method: string;\n params?: Record<string, unknown>;\n}): ClientCapabilities | undefined {\n switch (entry.method) {\n case 'elicitation/create': {\n if (entry.params?.['mode'] === 'url') {\n return { elicitation: { url: {} } };\n }\n return { elicitation: { form: {} } };\n }\n case 'sampling/createMessage': {\n const params = entry.params;\n if (params !== undefined && (params['tools'] !== undefined || params['toolChoice'] !== undefined)) {\n return { sampling: { tools: {} } };\n }\n return { sampling: {} };\n }\n case 'roots/list': {\n return { roots: {} };\n }\n default: {\n return undefined;\n }\n }\n}\n\n/**\n * Computes the subset of `required` client capabilities the client did not\n * declare. Returns `undefined` when every required capability is declared;\n * otherwise returns an object in the `ClientCapabilities` shape containing\n * exactly the missing capabilities (suitable for\n * `data.requiredCapabilities` on the `-32021` error).\n *\n * A capability counts as declared when its top-level key is present on the\n * declared capabilities; when the requirement names nested members (for\n * example `elicitation: { url: {} }`), each named member must also be present\n * under the declared capability. One lenient reading applies: a bare\n * `elicitation: {}` declaration (no mode sub-capability at all) counts as\n * declaring `elicitation.form` — the pre-mode (2025) meaning of a bare\n * declaration. An absent or empty `declared` value means\n * nothing is declared — every required capability is missing (the structural\n * clean-refusal posture for sessions with no per-request capability view).\n */\nexport function missingClientCapabilities(\n required: ClientCapabilities,\n declared: ClientCapabilities | undefined\n): ClientCapabilities | undefined {\n const missing: Record<string, unknown> = {};\n\n for (const [capability, requirement] of Object.entries(required)) {\n if (requirement === undefined) {\n continue;\n }\n const declaredValue = declared === undefined ? undefined : (declared as Record<string, unknown>)[capability];\n if (declaredValue === undefined) {\n missing[capability] = requirement;\n continue;\n }\n if (isPlainObject(requirement) && isPlainObject(declaredValue)) {\n const missingMembers: Record<string, unknown> = {};\n for (const [member, memberRequirement] of Object.entries(requirement)) {\n if (\n memberRequirement !== undefined &&\n declaredValue[member] === undefined &&\n !isImpliedCapabilityMember(capability, member, declaredValue)\n ) {\n missingMembers[member] = memberRequirement;\n }\n }\n if (Object.keys(missingMembers).length > 0) {\n missing[capability] = missingMembers;\n }\n }\n }\n\n return Object.keys(missing).length > 0 ? (missing as ClientCapabilities) : undefined;\n}\n","export 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'];\n\n/**\n * `_meta` key associating a message with a 2025-11-25 task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task';\n\n/* Reserved `_meta` keys for the per-request envelope (protocol revision 2026-07-28) */\n\n/**\n * `_meta` key carrying the MCP protocol version governing a request.\n *\n * For the HTTP transport, the value must match the `MCP-Protocol-Version` header.\n */\nexport const PROTOCOL_VERSION_META_KEY = 'io.modelcontextprotocol/protocolVersion';\n\n/**\n * `_meta` key identifying the client software making a request.\n */\nexport const CLIENT_INFO_META_KEY = 'io.modelcontextprotocol/clientInfo';\n\n/**\n * `_meta` key carrying the client's capabilities for a request.\n *\n * Capabilities are declared per request rather than once at initialization;\n * servers must not infer capabilities from prior requests.\n */\nexport const CLIENT_CAPABILITIES_META_KEY = 'io.modelcontextprotocol/clientCapabilities';\n\n/**\n * `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request\n * that opened the stream a notification was delivered on.\n *\n * Stamped by the server on every notification delivered via a\n * `subscriptions/listen` stream (including the leading\n * `notifications/subscriptions/acknowledged`); on stdio, where all messages\n * share one channel, clients use it to correlate notifications with their\n * originating subscription. The value is the listen request's JSON-RPC ID\n * verbatim.\n */\nexport const SUBSCRIPTION_ID_META_KEY = 'io.modelcontextprotocol/subscriptionId';\n\n/**\n * `_meta` key carrying the desired log level for a request.\n *\n * When absent, the server must not send `notifications/message` notifications\n * for the request.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months.\n */\nexport const LOG_LEVEL_META_KEY = 'io.modelcontextprotocol/logLevel';\n\n/*\n * Reserved `_meta` keys for distributed trace context propagation (SEP-414).\n *\n * These unprefixed keys are reserved by the MCP specification as an explicit\n * exception to the `_meta` key prefix rule. The SDK does not interpret them;\n * they pass through `_meta` untouched for OpenTelemetry-style propagation.\n */\n\n/**\n * `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414).\n *\n * When present, the value MUST follow the W3C `traceparent` header format,\n * e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`.\n *\n * @see https://www.w3.org/TR/trace-context/#traceparent-header\n */\nexport const TRACEPARENT_META_KEY = 'traceparent';\n\n/**\n * `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414).\n *\n * When present, the value MUST follow the W3C `tracestate` header format,\n * e.g. `vendor1=value1,vendor2=value2`.\n *\n * @see https://www.w3.org/TR/trace-context/#tracestate-header\n */\nexport const TRACESTATE_META_KEY = 'tracestate';\n\n/**\n * `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414).\n *\n * When present, the value MUST follow the W3C Baggage header format,\n * e.g. `userId=alice,serverRegion=us-east-1`.\n *\n * @see https://www.w3.org/TR/baggage/\n */\nexport const BAGGAGE_META_KEY = 'baggage';\n\n/* JSON-RPC types */\nexport const JSONRPC_VERSION = '2.0';\n\n/* Standard JSON-RPC error code constants */\nexport const PARSE_ERROR = -32_700;\nexport const INVALID_REQUEST = -32_600;\nexport const METHOD_NOT_FOUND = -32_601;\nexport const INVALID_PARAMS = -32_602;\nexport const INTERNAL_ERROR = -32_603;\n","/**\n * Protocol-era helpers (pure module). The MCP wire protocol splits into two eras:\n * legacy (the 2025-11-25 family and earlier; the version is negotiated via the\n * `initialize` handshake) and modern (2026-07-28 and later; no `initialize` —\n * servers advertise versions via `server/discover` and every request carries a\n * `_meta` envelope).\n *\n * An operation that belongs to one era must only ever consult that era's subset\n * of a supported-versions list: `initialize` never accepts or counter-offers a\n * modern revision, and the `server/discover` advertisement only ever contains\n * modern revisions.\n */\n\n/**\n * The protocol era of a connection: `'legacy'` for the 2025-11-25 family and\n * earlier (negotiated via `initialize`), `'modern'` for 2026-07-28 and later\n * (negotiated via `server/discover`; every request carries a `_meta` envelope).\n */\nexport type ProtocolEra = 'legacy' | 'modern';\n\n/**\n * The first protocol revision of the modern (2026-07-28) era. Revision identifiers\n * are ISO dates, so lexicographic comparison orders them chronologically.\n */\nexport const FIRST_MODERN_PROTOCOL_VERSION = '2026-07-28';\n\n/**\n * Modern-era protocol revisions this SDK can negotiate via `server/discover`.\n * Deliberately separate from {@linkcode SUPPORTED_PROTOCOL_VERSIONS} (the legacy\n * `initialize` list), so adding a revision here can never leak a modern version\n * string into a 2025-era handshake. Internal — not part of the public API surface.\n */\nexport const SUPPORTED_MODERN_PROTOCOL_VERSIONS = [FIRST_MODERN_PROTOCOL_VERSION];\n\n/** Whether the given protocol revision belongs to the modern (2026-07-28+) era. */\nexport function isModernProtocolVersion(version: string): boolean {\n return version >= FIRST_MODERN_PROTOCOL_VERSION;\n}\n\n/** The legacy-era (pre-2026-07-28) subset of a supported-versions list, in the list's own preference order. */\nexport function legacyProtocolVersions(versions: readonly string[]): string[] {\n return versions.filter(version => !isModernProtocolVersion(version));\n}\n\n/** The modern-era (2026-07-28+) subset of a supported-versions list, in the list's own preference order. */\nexport function modernProtocolVersions(versions: readonly string[]): string[] {\n return versions.filter(version => isModernProtocolVersion(version));\n}\n","import type { CallToolResult } from '../types/types';\n\n/**\n * SEP-2106 §4.3 TextContent auto-append, era-agnostic, called from BOTH\n * codecs' {@link WireCodec.projectCallToolResult}: when `structuredContent`\n * is a non-object value (array/primitive/`null`) and the handler authored no\n * `type:'text'` block, append `{type:'text', text: JSON.stringify(value)}`.\n * Object-shaped (or absent) `structuredContent` returns the same reference.\n *\n * Leaf module: imported by both era codec modules, so it must NOT import from\n * `./codec.js` (which value-imports the rev codecs at top level — that would\n * make a runtime cycle and a TDZ hazard for entries that evaluate a rev codec\n * module first).\n */\nexport function appendTextFallbackForNonObject(result: CallToolResult): CallToolResult {\n const sc = result.structuredContent;\n if (sc === undefined) return result;\n const isNonObjectValue = typeof sc !== 'object' || sc === null || Array.isArray(sc);\n if (!isNonObjectValue) return result;\n const hasTextContent = result.content?.some(c => c.type === 'text') ?? false;\n if (hasTextContent) return result;\n return { ...result, content: [...(result.content ?? []), { type: 'text' as const, text: JSON.stringify(sc) }] };\n}\n","/**\n * SEP-2106 legacy `outputSchema` wrap helpers (2025-era projection only).\n *\n * The neutral / 2026-07-28 model lets a tool's `outputSchema` carry any JSON\n * Schema root. The 2025-11-25 wire shape requires `type:'object'` at the root,\n * so when an era-blind handler advertises a non-object root, the 2025 codec's\n * `encodeResult('tools/list', …)` projects it down to\n * `{type:'object', properties:{result:<natural>}, required:['result']}`, and\n * `projectCallToolResult` wraps the matching `structuredContent` as\n * `{result:<value>}`. The 2026 codec's projections are the identity.\n *\n * These helpers are wire-layer property — they exist so the projection can\n * live behind {@link WireCodec.encodeResult} / {@link WireCodec.projectCallToolResult}\n * and never be re-derived in shared/ or server-side code.\n */\n\n/**\n * Whether a JSON Schema's root is non-object: either an explicit non-object\n * `type`, or a typeless root such as `{anyOf:[…]}`. Object-shaped typeless\n * roots that the schema-conversion layer can prove are objects are stamped\n * `type:'object'` upstream, so they reach this predicate as object roots.\n */\nexport function isNonObjectJsonSchemaRoot(json: Readonly<Record<string, unknown>>): boolean {\n return json['type'] !== 'object';\n}\n\n/**\n * Keyword-position keys whose values are instance data (not subschemas). A\n * `{$ref:…}` appearing inside one is a literal value, not a JSON Pointer to\n * rewrite. Only consulted when the current object is in keyword position —\n * a PROPERTY named `default`/`const` (under `properties`/`$defs`/…) is a name\n * position whose value IS a subschema and is recursed into.\n */\nconst REF_REWRITE_DATA_POSITION_KEYS: ReadonlySet<string> = new Set(['const', 'enum', 'default', 'examples']);\n\n/**\n * Keyword-position keys whose value is a name→subschema map. Entries inside\n * such a map are in NAME position: their keys are author-chosen property\n * names (which may collide with JSON Schema keywords), their values are\n * subschemas to recurse into.\n */\nconst REF_REWRITE_NAME_MAP_KEYS: ReadonlySet<string> = new Set([\n 'properties',\n 'patternProperties',\n '$defs',\n 'definitions',\n 'dependentSchemas'\n]);\n\n/**\n * Wrap a non-object output schema in the 2025-era envelope:\n * `{type:'object', properties:{result:<natural>}, required:['result']}`.\n *\n * Same-document `$ref` / `$dynamicRef` JSON Pointers inside the natural schema\n * (e.g. `#/properties/foo` produced by zod for de-duplicated/recursive types)\n * are rewritten to account for the new `#/properties/result` root: bare `#` →\n * `#/properties/result`, `#/…` → `#/properties/result/…`. Cross-document refs\n * (anything not starting with `#`) are left untouched.\n *\n * The rewrite is position-aware: data-valued keywords\n * (`const`/`enum`/`default`/`examples`) in keyword position are NOT descended\n * into; the same names appearing as property names under\n * `properties`/`patternProperties`/`$defs`/`definitions`/`dependentSchemas`\n * ARE descended into (they're subschemas). The rewrite is also `$id`-scoped:\n * if the natural root carries `$id` no pointer is rewritten (same-document\n * refs inside resolve against the embedded `$id` base, not the wrapper root),\n * and any subtree that establishes its own `$id` is left untouched for the\n * same reason.\n */\nexport function wrapOutputSchemaForLegacy(natural: Readonly<Record<string, unknown>>): Record<string, unknown> {\n // A root `$schema` is hoisted to the wrapper root: it's a document-level\n // dialect declaration and the SEP-1613 dialect checks (both built-in\n // providers) only inspect the root, so leaving it under `properties.result`\n // would make a non-2020-12 schema pass the dialect check on the 2025\n // projection while the same tool is rejected on the 2026 era.\n const $schema = typeof natural['$schema'] === 'string' ? natural['$schema'] : undefined;\n // `$id` at the natural root: every same-document `#/…` ref inside resolves\n // against that base URI, not against the wrapper root — skip the rewrite.\n if (natural['$id'] !== undefined) {\n return { ...($schema !== undefined && { $schema }), type: 'object', properties: { result: natural }, required: ['result'] };\n }\n const rewriteRefs = (node: unknown, parentIsNameMap: boolean): unknown => {\n if (Array.isArray(node)) return node.map(item => rewriteRefs(item, false));\n if (node === null || typeof node !== 'object') return node;\n // A nested `$id` establishes its own resolution base for the subtree —\n // same-document refs inside are no longer relative to the wrapper root.\n // Only applies in keyword position (a property NAMED `$id` is just a name).\n if (!parentIsNameMap && (node as Record<string, unknown>)['$id'] !== undefined) return node;\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(node)) {\n if (parentIsNameMap) {\n // Name position: `k` is an author-chosen property/def name, `v` is a\n // subschema in keyword position. Never treat `k` as a keyword here.\n out[k] = rewriteRefs(v, false);\n } else if ((k === '$ref' || k === '$dynamicRef') && typeof v === 'string') {\n out[k] = v === '#' ? '#/properties/result' : v.startsWith('#/') ? `#/properties/result${v.slice(1)}` : v;\n } else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) {\n out[k] = v;\n } else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) {\n out[k] = rewriteRefs(v, true);\n } else {\n out[k] = rewriteRefs(v, false);\n }\n }\n return out;\n };\n return {\n ...($schema !== undefined && { $schema }),\n type: 'object',\n properties: { result: rewriteRefs(natural, false) },\n required: ['result']\n };\n}\n","/**\n * Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from\n * the public/neutral types/schemas.ts. The neutral layer is the public-API\n * superset and is free to evolve (e.g., SEP-2106 widening); this file is the\n * 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN.\n *\n * This is the era's complete frozen wire-parse contract — both the 2025-only\n * delta (the deprecated task family, the era role unions) AND frozen copies of\n * every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock,\n * prompts/resources/completion/elicitation, …). The 2026-era codec\n * (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way.\n *\n * The 2025-only delta (the task message surface, restored types-only by #2248\n * for interop with task-capable 2025 peers) is parsed ONLY through this era's\n * registry; the deprecated Task* schemas also live (marked `@deprecated`) in\n * the neutral schema layer so the public types stay nameable without a\n * cross-layer import — nameability is constant, runtime availability is\n * version-keyed — but appear in no API signature. Q1 increment 2 — deletions\n * are physical: the\n * 2026-era REGISTRY has no Task* methods (its frozen building-block copies do\n * carry the deprecated Task* sub-schemas by composition — soft contamination,\n * tracked for anchor-exactness adjudication).\n *\n * The only cross-layer dependency is `import type { JSONObject, JSONValue }`\n * from the neutral types barrel — pure structural type aliases with no parse\n * behavior. No runtime schema is shared with the neutral layer.\n */\nimport * as z from 'zod/v4';\n\nimport type { JSONObject, JSONValue } from '../../types/types';\n\n/* ───────────────────────────────────────────────────────────────────────────\n * Building blocks\n * ─────────────────────────────────────────────────────────────────────────── */\n\nexport const JSONValueSchema: z.ZodType<JSONValue, JSONValue> = z.lazy(() =>\n z.union([z.string(), z.number(), z.boolean(), z.null(), z.record(z.string(), JSONValueSchema), z.array(JSONValueSchema)])\n);\nexport const JSONObjectSchema: z.ZodType<JSONObject, JSONObject> = z.record(z.string(), JSONValueSchema);\n\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/**\n * An opaque token used to represent a cursor for pagination.\n */\nexport const CursorSchema = z.string();\n\n/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\nexport const TaskMetadataSchema = z.object({\n ttl: z.number().optional()\n});\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 *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const RelatedTaskMetadataSchema = z.object({\n taskId: z.string()\n});\n\nexport const 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 'io.modelcontextprotocol/related-task': RelatedTaskMetadataSchema.optional()\n});\n\n/**\n * Common params for any request.\n */\nexport const 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/**\n * Common params for any task-augmented request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\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\nexport const RequestSchema = z.object({\n method: z.string(),\n params: BaseRequestParamsSchema.loose().optional()\n});\n\nexport const 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});\n\nexport const NotificationSchema = z.object({\n method: z.string(),\n params: NotificationsParamsSchema.loose().optional()\n});\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/**\n * A uniquely identifying ID for a request in JSON-RPC.\n */\nexport const RequestIdSchema = z.union([z.string(), z.number().int()]);\n\n/* Empty result */\n/**\n * A response that indicates success but carries no data.\n */\nexport const EmptyResultSchema = ResultSchema.strict();\n\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 {@linkcode InitializeRequest | initialize} request.\n */\nexport const CancelledNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/cancelled'),\n params: CancelledNotificationParamsSchema\n});\n\n/* Base Metadata */\n/**\n * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | 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/**\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/**\n * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | 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\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 /**\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});\n\nconst FormElicitationCapabilitySchema = z.intersection(\n z.object({\n applyDefaults: z.boolean().optional()\n }),\n JSONObjectSchema\n);\n\nconst ElicitationCapabilitySchema = z.preprocess(\n value => {\n if (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value as Record<string, unknown>).length === 0) {\n return { form: {} };\n }\n return value;\n },\n z.intersection(\n z.object({\n form: FormElicitationCapabilitySchema.optional(),\n url: JSONObjectSchema.optional()\n }),\n JSONObjectSchema.optional()\n )\n);\n\n/**\n * Task capabilities for clients, indicating which request types support task creation.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const ClientTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the client supports listing tasks.\n */\n list: JSONObjectSchema.optional(),\n /**\n * Present if the client supports cancelling tasks.\n */\n cancel: JSONObjectSchema.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: JSONObjectSchema.optional()\n })\n .optional(),\n /**\n * Task support for elicitation requests.\n */\n elicitation: z\n .looseObject({\n create: JSONObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n\n/**\n * Task capabilities for servers, indicating which request types support task creation.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const ServerTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the server supports listing tasks.\n */\n list: JSONObjectSchema.optional(),\n /**\n * Present if the server supports cancelling tasks.\n */\n cancel: JSONObjectSchema.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: JSONObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\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(), JSONObjectSchema).optional(),\n /**\n * Present if the client supports sampling from an LLM.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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: JSONObjectSchema.optional(),\n /**\n * Present if the client supports tool use via `tools` and `toolChoice` parameters.\n */\n tools: JSONObjectSchema.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 * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\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 * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; parsed for interoperability only — servers built on this SDK never advertise it.\n */\n tasks: ClientTasksCapabilitySchema.optional(),\n /**\n * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), JSONObjectSchema).optional()\n});\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});\n\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(), JSONObjectSchema).optional(),\n /**\n * Present if the server supports sending log messages to the client.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\n logging: JSONObjectSchema.optional(),\n /**\n * Present if the server supports sending completions to the client.\n */\n completions: JSONObjectSchema.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 /**\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 * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; parsed for interoperability only — servers built on this SDK never advertise it.\n */\n tasks: ServerTasksCapabilitySchema.optional(),\n /**\n * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), JSONObjectSchema).optional()\n});\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/**\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});\n\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\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});\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});\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\n/* Pagination */\nexport const PaginatedRequestSchema = RequestSchema.extend({\n params: PaginatedRequestParamsSchema.optional()\n});\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/* 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});\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/**\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(\n 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 } catch {\n return false;\n }\n },\n { message: 'Invalid Base64 string' }\n);\n\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/**\n * The sender or recipient of messages and data in a conversation.\n */\nexport const RoleSchema = z.enum(['user', 'assistant']);\n\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 /**\n * Importance hint for the resource, from 0 (least) to 1 (most).\n */\n priority: z.number().min(0).max(1).optional(),\n\n /**\n * ISO 8601 timestamp for the most recent modification.\n */\n lastModified: z.iso.datetime({ offset: true }).optional()\n});\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 /**\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 /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n\n /**\n * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n *\n * This can be used by Hosts to display file sizes and estimate context window usage.\n */\n size: z.optional(z.number()),\n\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n\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/**\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 /**\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 /**\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 /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n\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/**\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/**\n * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client.\n */\nexport const ListResourcesResultSchema = PaginatedResultSchema.extend({\n resources: z.array(ResourceSchema)\n});\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/**\n * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client.\n */\nexport const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({\n resourceTemplates: z.array(ResourceTemplateSchema)\n});\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/**\n * Parameters for a {@linkcode ReadResourceRequest | resources/read} request.\n */\nexport const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;\n\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/**\n * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client.\n */\nexport const ReadResourceResultSchema = ResultSchema.extend({\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n});\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});\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});\n\nexport const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request.\n */\nexport const UnsubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/unsubscribe'),\n params: UnsubscribeRequestParamsSchema\n});\n\n/**\n * Parameters for a {@linkcode ResourceUpdatedNotification | 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/**\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 {@linkcode SubscribeRequest | resources/subscribe} request.\n */\nexport const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/updated'),\n params: ResourceUpdatedNotificationParamsSchema\n});\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/**\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/**\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/**\n * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client.\n */\nexport const ListPromptsResultSchema = PaginatedResultSchema.extend({\n prompts: z.array(PromptSchema)\n});\n\n/**\n * Parameters for a {@linkcode GetPromptRequest | 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/**\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 /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n\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/**\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 /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n\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/**\n * Audio content 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 /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n\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/**\n * A tool call request from an assistant (LLM).\n * Represents the assistant's request to use a tool.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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/**\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/**\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 {@linkcode ListResourcesRequest | resources/list} requests.\n */\nexport const ResourceLinkSchema = ResourceSchema.extend({\n type: z.literal('resource_link')\n});\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/**\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/**\n * The server's response to a {@linkcode GetPromptRequest | 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/**\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\n/* Tools */\n/**\n * Additional properties describing a `Tool` to clients.\n *\n * NOTE: all properties in {@linkcode 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 /**\n * If `true`, the tool does not modify its environment.\n *\n * Default: `false`\n */\n readOnlyHint: z.boolean().optional(),\n\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 /**\n * If `true`, calling the tool repeatedly with the same arguments\n * will have no additional effect on its environment.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: `false`\n */\n idempotentHint: z.boolean().optional(),\n\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/**\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/**\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(), JSONValueSchema).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(), JSONValueSchema).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 /**\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/**\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/**\n * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client.\n */\nexport const ListToolsResultSchema = PaginatedResultSchema.extend({\n tools: z.array(ToolSchema)\n});\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 * Required on the wire per the specification (it may be an empty array).\n */\n content: z.array(ContentBlockSchema),\n\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 /**\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/**\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/**\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/**\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/* Logging */\n/**\n * The severity of a log message.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\nexport const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n\n/**\n * Parameters for a `logging/setLevel` request.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\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 *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\nexport const SetLevelRequestSchema = RequestSchema.extend({\n method: z.literal('logging/setLevel'),\n params: SetLevelRequestParamsSchema\n});\n\n/**\n * Parameters for a `notifications/message` notification.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\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 *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\nexport const LoggingMessageNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/message'),\n params: LoggingMessageNotificationParamsSchema\n});\n\n/* Sampling */\n/**\n * Hints to use for model selection.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const ModelHintSchema = z.object({\n /**\n * A hint for a model name.\n */\n name: z.string().optional()\n});\n\n/**\n * The server's preferences for model selection, requested of the client during sampling.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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/**\n * Controls tool usage behavior in sampling requests.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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/**\n * The result of a tool execution, provided by the user (server).\n * Represents the outcome of invoking a tool requested via `ToolUseContent`.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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),\n structuredContent: z.object({}).loose().optional(),\n isError: z.boolean().optional(),\n\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/**\n * Basic content types for sampling responses (without tool use).\n * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);\n\n/**\n * Content block types allowed in sampling messages.\n * This includes text, image, audio, tool use requests, and tool results.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n ToolResultContentSchema\n]);\n\n/**\n * Describes a message issued to or received from an LLM API.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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/**\n * Parameters for a `sampling/createMessage` request.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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\"`. The values `\"thisServer\"` and `\"allServers\"` are deprecated (SEP-2596): servers SHOULD\n * omit this field or use `\"none\"`, and SHOULD only use the deprecated values if the client declares\n * `ClientCapabilities`.`sampling.context`.\n *\n * @deprecated The `\"thisServer\"` and `\"allServers\"` values are deprecated as of protocol version 2025-11-25\n * (SEP-2596) and will be removed no later than the Sampling feature itself (SEP-2577). Omit this field or use `\"none\"`.\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: JSONObjectSchema.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 *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const CreateMessageRequestSchema = RequestSchema.extend({\n method: z.literal('sampling/createMessage'),\n params: CreateMessageRequestParamsSchema\n});\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 *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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/**\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 *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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\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/**\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/**\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/**\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/**\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(\n z.object({\n const: z.string(),\n title: z.string()\n })\n ),\n default: z.string().optional()\n});\n\n/**\n * Use {@linkcode 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\n// Combined single selection enumeration\nexport const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n\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/**\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(\n z.object({\n const: z.string(),\n title: z.string()\n })\n )\n }),\n default: z.array(z.string()).optional()\n});\n\n/**\n * Combined schema for multiple-selection enumeration\n */\nexport const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n\n/**\n * Primitive schema definition for enum fields.\n */\nexport const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n\n/**\n * Union of all primitive schema definitions.\n */\nexport const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n\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\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown())\n});\n\n/**\n * Parameters for an {@linkcode ElicitRequest | 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/**\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/**\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/**\n * Parameters for a {@linkcode ElicitationCompleteNotification | 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/**\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/**\n * The client's response to an {@linkcode ElicitRequest | 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 declined 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(\n val => (val === null ? undefined : val),\n z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional()\n )\n});\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/**\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/**\n * Parameters for a {@linkcode CompleteRequest | 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});\n\n/**\n * The server's response to a {@linkcode CompleteRequest | 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\n/* Roots */\n/**\n * Represents a root directory or file that the server can operate on.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\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 /**\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/**\n * Sent from the server to request a list of root URIs from the client.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\n */\nexport const ListRootsRequestSchema = RequestSchema.extend({\n method: z.literal('roots/list'),\n params: BaseRequestParamsSchema.optional()\n});\n\n/**\n * The client's response to a `roots/list` request from the server.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\n */\nexport const ListRootsResultSchema = ResultSchema.extend({\n roots: z.array(RootSchema)\n});\n\n/**\n * A notification from the client to the server, informing it that the list of roots has changed.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\n */\nexport const RootsListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/roots/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n\n/* ───────────────────────────────────────────────────────────────────────────\n * Tasks (2025-11-25 wire vocabulary; restored types-only by #2248 for interop\n * with task-capable 2025 peers — parsed ONLY through this era's registry).\n * ─────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Task creation parameters, used to ask that the server create a task to represent a request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const TaskCreationParamsSchema = z.looseObject({\n /**\n * Requested duration in milliseconds to retain task from creation.\n */\n ttl: z.number().optional(),\n\n /**\n * Time in milliseconds to wait between task status requests.\n */\n pollInterval: z.number().optional()\n});\n\n/**\n * The status of a task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']);\n\n/**\n * A pollable state object associated with a request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\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/**\n * Result returned when a task is created, containing the task data wrapped in a `task` field.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const CreateTaskResultSchema = ResultSchema.extend({\n task: TaskSchema\n});\n\n/**\n * Parameters for task status notification.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);\n\n/**\n * A notification sent when a task's status changes.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const TaskStatusNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tasks/status'),\n params: TaskStatusNotificationParamsSchema\n});\n\n/**\n * A request to get the state of a specific task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const GetTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/get'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n\n/**\n * The response to a {@linkcode GetTaskRequest | tasks/get} request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const GetTaskResultSchema = ResultSchema.merge(TaskSchema);\n\n/**\n * A request to get the result of a specific task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const GetTaskPayloadRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/result'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\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 {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure.\n *\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const GetTaskPayloadResultSchema = ResultSchema.loose();\n\n/**\n * A request to list tasks.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const ListTasksRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tasks/list')\n});\n\n/**\n * The response to a {@linkcode ListTasksRequest | tasks/list} request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const ListTasksResultSchema = PaginatedResultSchema.extend({\n tasks: z.array(TaskSchema)\n});\n\n/**\n * A request to cancel a specific task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const CancelTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/cancel'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n\n/**\n * The response to a {@linkcode CancelTaskRequest | tasks/cancel} request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);\n\n/* ───────────────────────────────────────────────────────────────────────────\n * The 2025-era wire role unions: the era-faithful aggregates (what a\n * 2025-11-25 peer may legally put on the wire, per role) and the source the\n * era registry is built from. Member order preserves the pre-split unions\n * (task members last for requests/results; notification members are\n * method-discriminated, so ordering is not observable).\n * ─────────────────────────────────────────────────────────────────────────── */\n\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]);\n\nexport const ClientNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n InitializedNotificationSchema,\n RootsListChangedNotificationSchema,\n TaskStatusNotificationSchema\n]);\n\nexport const ClientResultSchema = z.union([\n EmptyResultSchema,\n CreateMessageResultSchema,\n CreateMessageResultWithToolsSchema,\n ElicitResultSchema,\n ListRootsResultSchema,\n GetTaskResultSchema,\n ListTasksResultSchema,\n CreateTaskResultSchema\n]);\n\nexport const ServerRequestSchema = z.union([\n PingRequestSchema,\n CreateMessageRequestSchema,\n ElicitRequestSchema,\n ListRootsRequestSchema,\n GetTaskRequestSchema,\n GetTaskPayloadRequestSchema,\n ListTasksRequestSchema,\n CancelTaskRequestSchema\n]);\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]);\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]);\n","/**\n * The 2025-era method registries — re-homed verbatim from\n * `types/schemas.ts` (Q1 increment-2 step 1: mechanical relocation behind the\n * codec interface; the registry CONTENT is byte-identical to the pre-split\n * maps and is pinned by reference in `test/types/registryPins.test.ts`).\n *\n * This era serves all five legacy protocol versions (2024-10-07 …\n * 2025-11-25), exactly as the single schema set did before the split. It is\n * BEHAVIOR-FROZEN behind the Q10-L2 byte-identity suite: the request and\n * notification maps carry the full deliberate 2025-11-25 wire vocabulary,\n * including the task family (the #2248 wire-interop restore). The RESULT map\n * is the runtime/typed ALIGNED map (PR #2293 review): keyed by this era's\n * subset of the typed `RequestMethod` set so it cannot drift from the typed\n * `ResultTypeMap` — no\n * task-result union members and no `tasks/*` entries; a task-capable 2025\n * peer's `CreateTaskResult` answer fails the plain per-method schema as a\n * typed invalid-result error, and callers needing task interop pass an\n * explicit result schema (see `test/shared/typedMapAlignment.test.ts`).\n *\n * 2026-only vocabulary (`server/discover`, `subscriptions/listen`, the MRTR\n * shells, `resultType`, the `_meta` envelope) has NO entry and NO code path\n * here — the inverse-leak guarantee is physical absence, not discipline.\n */\nimport type * as z from 'zod/v4';\n\nimport type { NotificationMethod, NotificationTypeMap, RequestMethod, RequestTypeMap, ResultTypeMap } from '../../types/types';\nimport type { ClientNotificationSchema, ClientRequestSchema, ServerNotificationSchema, ServerRequestSchema } from './schemas';\nimport {\n CallToolRequestSchema,\n CallToolResultSchema,\n CancelledNotificationSchema,\n CancelTaskRequestSchema,\n CompleteRequestSchema,\n CompleteResultSchema,\n CreateMessageRequestSchema,\n CreateMessageResultWithToolsSchema,\n ElicitationCompleteNotificationSchema,\n ElicitRequestSchema,\n ElicitResultSchema,\n EmptyResultSchema,\n GetPromptRequestSchema,\n GetPromptResultSchema,\n GetTaskPayloadRequestSchema,\n GetTaskRequestSchema,\n InitializedNotificationSchema,\n InitializeRequestSchema,\n InitializeResultSchema,\n ListPromptsRequestSchema,\n ListPromptsResultSchema,\n ListResourcesRequestSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesRequestSchema,\n ListResourceTemplatesResultSchema,\n ListRootsRequestSchema,\n ListRootsResultSchema,\n ListTasksRequestSchema,\n ListToolsRequestSchema,\n ListToolsResultSchema,\n LoggingMessageNotificationSchema,\n PingRequestSchema,\n ProgressNotificationSchema,\n PromptListChangedNotificationSchema,\n ReadResourceRequestSchema,\n ReadResourceResultSchema,\n ResourceListChangedNotificationSchema,\n ResourceUpdatedNotificationSchema,\n RootsListChangedNotificationSchema,\n SetLevelRequestSchema,\n SubscribeRequestSchema,\n TaskStatusNotificationSchema,\n ToolListChangedNotificationSchema,\n UnsubscribeRequestSchema\n} from './schemas';\n\n/* The era's wire vocabulary, derived from the wire role unions in\n * `./schemas.ts` (the same unions the registries used to be built from at\n * runtime). Keying the maps by these derived unions makes drift a compile\n * error in BOTH directions: a union member without a map entry, a map entry\n * the unions do not know, and an entry pointing at a different method's\n * schema all fail to typecheck. */\ntype WireRequest = z.output<typeof ClientRequestSchema> | z.output<typeof ServerRequestSchema>;\ntype WireNotification = z.output<typeof ClientNotificationSchema> | z.output<typeof ServerNotificationSchema>;\n\n/** Every request method in the 2025-era wire vocabulary (the typed `RequestMethod` surface plus the task family). */\nexport type Rev2025RequestMethod = WireRequest['method'];\n/** Every notification method in the 2025-era wire vocabulary. */\nexport type Rev2025NotificationMethod = WireNotification['method'];\n\n/**\n * The typed-method surface this era serves: the typed `RequestMethod` set\n * minus methods whose wire vocabulary does not exist on this era (e.g.\n * `server/discover`, which the typed maps carry but only the 2026-era\n * registry serves). Deriving the subset from the era's own wire role unions\n * keeps the both-direction drift guard: a typed 2025-era method without a map\n * entry, or a map entry the era's wire vocabulary does not know, is a compile\n * error.\n */\ntype Rev2025TypedRequestMethod = Extract<RequestMethod, Rev2025RequestMethod>;\n\n/* Runtime schema lookup — result schemas by method */\n// Keyed by the era's typed-method subset and valued by\n// `z.ZodType<ResultTypeMap[M]>` so the runtime map and the typed\n// `ResultTypeMap` cannot drift: a missing entry, an extra key, or an entry\n// that does not parse to the typed map's result type is a compile error. No\n// entry may be looser than the typed map (no task-result union members) and\n// no key may fall outside it (no `tasks/*` entries — the task methods are\n// 2025-11-25 wire vocabulary with no SDK runtime; callers needing task\n// interop pass an explicit schema).\nconst resultSchemas: { readonly [M in Rev2025TypedRequestMethod]: z.ZodType<ResultTypeMap[M]> } = {\n ping: EmptyResultSchema,\n initialize: InitializeResultSchema,\n 'completion/complete': CompleteResultSchema,\n 'logging/setLevel': EmptyResultSchema,\n 'prompts/get': GetPromptResultSchema,\n 'prompts/list': ListPromptsResultSchema,\n 'resources/list': ListResourcesResultSchema,\n 'resources/templates/list': ListResourceTemplatesResultSchema,\n 'resources/read': ReadResourceResultSchema,\n 'resources/subscribe': EmptyResultSchema,\n 'resources/unsubscribe': EmptyResultSchema,\n 'tools/call': CallToolResultSchema,\n 'tools/list': ListToolsResultSchema,\n 'sampling/createMessage': CreateMessageResultWithToolsSchema,\n 'elicitation/create': ElicitResultSchema,\n 'roots/list': ListRootsResultSchema\n};\n\n/* Runtime schema lookup — request and notification schemas by method.\n *\n * The entries are the SAME schema objects the wire role unions are built\n * from (reference identity is pinned by `test/types/registryPins.test.ts`),\n * and the key order preserves the pre-split union iteration order so the\n * exported method lists are byte-identical to the builder they replace. */\nconst requestSchemas: { readonly [M in Rev2025RequestMethod]: z.ZodType<Extract<WireRequest, { method: M }>> } = {\n ping: PingRequestSchema,\n initialize: InitializeRequestSchema,\n 'completion/complete': CompleteRequestSchema,\n 'logging/setLevel': SetLevelRequestSchema,\n 'prompts/get': GetPromptRequestSchema,\n 'prompts/list': ListPromptsRequestSchema,\n 'resources/list': ListResourcesRequestSchema,\n 'resources/templates/list': ListResourceTemplatesRequestSchema,\n 'resources/read': ReadResourceRequestSchema,\n 'resources/subscribe': SubscribeRequestSchema,\n 'resources/unsubscribe': UnsubscribeRequestSchema,\n 'tools/call': CallToolRequestSchema,\n 'tools/list': ListToolsRequestSchema,\n 'tasks/get': GetTaskRequestSchema,\n 'tasks/result': GetTaskPayloadRequestSchema,\n 'tasks/list': ListTasksRequestSchema,\n 'tasks/cancel': CancelTaskRequestSchema,\n 'sampling/createMessage': CreateMessageRequestSchema,\n 'elicitation/create': ElicitRequestSchema,\n 'roots/list': ListRootsRequestSchema\n};\n\nconst notificationSchemas: { readonly [M in Rev2025NotificationMethod]: z.ZodType<Extract<WireNotification, { method: M }>> } = {\n 'notifications/cancelled': CancelledNotificationSchema,\n 'notifications/progress': ProgressNotificationSchema,\n 'notifications/initialized': InitializedNotificationSchema,\n 'notifications/roots/list_changed': RootsListChangedNotificationSchema,\n 'notifications/tasks/status': TaskStatusNotificationSchema,\n 'notifications/message': LoggingMessageNotificationSchema,\n 'notifications/resources/updated': ResourceUpdatedNotificationSchema,\n 'notifications/resources/list_changed': ResourceListChangedNotificationSchema,\n 'notifications/tools/list_changed': ToolListChangedNotificationSchema,\n 'notifications/prompts/list_changed': PromptListChangedNotificationSchema,\n 'notifications/elicitation/complete': ElicitationCompleteNotificationSchema\n};\n\n/** The 2025-era request-method set (registry membership = the deletion story). */\nexport function hasRequestMethod2025(method: string): method is Rev2025RequestMethod {\n return Object.prototype.hasOwnProperty.call(requestSchemas, method);\n}\n\n/** The 2025-era notification-method set. */\nexport function hasNotificationMethod2025(method: string): method is Rev2025NotificationMethod {\n return Object.prototype.hasOwnProperty.call(notificationSchemas, method);\n}\n\n/** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */\nfunction hasResultMethod(method: string): method is Rev2025TypedRequestMethod {\n return Object.prototype.hasOwnProperty.call(resultSchemas, method);\n}\n\n/**\n * Gets the Zod schema for validating results of a given request method.\n * Returns `undefined` for non-spec methods and 2026-only methods.\n * The typed overload is backed by the map's own typing (`z.ZodType<ResultTypeMap[M]>`\n * per entry), so callers with a statically known 2025-era method can use the\n * parsed value without a type assertion.\n */\nexport function getResultSchema<M extends Rev2025TypedRequestMethod>(method: M): z.ZodType<ResultTypeMap[M]>;\nexport function getResultSchema(method: string): z.ZodType | undefined;\nexport function getResultSchema(method: string): z.ZodType | undefined {\n return hasResultMethod(method) ? resultSchemas[method] : undefined;\n}\n\n/**\n * Gets the Zod schema for a given request method.\n * Returns `undefined` for non-spec methods and 2026-only methods.\n * The typed overload returns a ZodType that parses to `RequestTypeMap[M]`,\n * allowing callers to use `schema.parse()` without additional type assertions.\n */\nexport function getRequestSchema<M extends Rev2025TypedRequestMethod>(method: M): z.ZodType<RequestTypeMap[M]>;\nexport function getRequestSchema(method: string): z.ZodType | undefined;\nexport function getRequestSchema(method: string): z.ZodType | undefined {\n return hasRequestMethod2025(method) ? requestSchemas[method] : undefined;\n}\n\n/**\n * Gets the Zod schema for a given notification method.\n * Returns `undefined` for non-spec methods.\n * @see getRequestSchema for the typed-overload contract.\n */\nexport function getNotificationSchema<M extends NotificationMethod>(method: M): z.ZodType<NotificationTypeMap[M]>;\nexport function getNotificationSchema(method: string): z.ZodType | undefined;\nexport function getNotificationSchema(method: string): z.ZodType | undefined {\n return hasNotificationMethod2025(method) ? notificationSchemas[method] : undefined;\n}\n\n/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */\nexport const rev2025RequestMethods: readonly string[] = Object.keys(requestSchemas);\nexport const rev2025NotificationMethods: readonly string[] = Object.keys(notificationSchemas);\n","/**\n * The 2025-era wire codec: decode/encode ≈ identity.\n *\n * This codec serves every legacy protocol version (2024-10-07 … 2025-11-25).\n * It is BEHAVIOR-FROZEN behind the Q10-L2 byte-identity suite — its schemas\n * are today's schemas, its registry is today's method map, and its encode\n * path is the identity.\n *\n * Never-stamp guarantee: this module NEVER WRITES 2026 vocabulary\n * (`resultType`, `ttlMs`, `cacheScope`, the `_meta` envelope keys) — there is\n * no code path that can. `encodeResult` is the identity for every result\n * EXCEPT the SEP-2106 `tools/list` projection: when a tool's neutral\n * `outputSchema` has a non-object root, the 2025 wire shape requires\n * `type:'object'` there, so the codec PROJECTS the public superset down by\n * wrapping the advertised schema as `{type:'object',\n * properties:{result:<natural>}, required:['result']}`. That projection\n * narrows neutral→2025-wire; it never adds 2026 vocabulary.\n *\n * One deliberate exception to \"no 2026 code path\" (Q1-SD3 ii, amending the\n * V-2 'no code path at all' design claim): `decodeResult` STRIPS a foreign\n * `resultType` key from inbound results before validation (strip-on-lift).\n * `resultType` is not 2025 vocabulary — a 2025 peer that sends it is\n * misbehaving — and the ruled posture is tolerate-and-drop so the foreign key\n * can neither surface to consumers (the neutral types have no slot for it)\n * nor leak through the retained loose-object passthrough. This is the ONLY\n * 2026-vocabulary code path in the 2025 codec, it exists on the decode side\n * only, and it deletes — never reads, maps, or emits — the foreign value.\n */\nimport type * as z from 'zod/v4';\n\nimport type { CallToolResult, Result } from '../../types/types';\nimport type { DecodedResult, EnvelopeIssue, LiftedWireMaterial, OutboundEnvelopeMaterial, ValidateOutcome, WireCodec } from '../codec';\nimport { appendTextFallbackForNonObject } from '../textFallback';\nimport { isNonObjectJsonSchemaRoot, wrapOutputSchemaForLegacy } from './legacyWrap';\nimport { getNotificationSchema, getRequestSchema, getResultSchema, hasNotificationMethod2025, hasRequestMethod2025 } from './registry';\nimport { CreateMessageResultSchema, CreateMessageResultWithToolsSchema } from './schemas';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */\nfunction triState<T>(schema: z.ZodType<T> | undefined, raw: unknown): ValidateOutcome<T> {\n if (schema === undefined) return { ok: false, reason: 'not-in-era' };\n const parsed = schema.safeParse(raw);\n return parsed.success ? { ok: true, value: parsed.data } : { ok: false, reason: 'invalid', message: String(parsed.error) };\n}\n\nconst NOT_IN_ERA: ValidateOutcome<never> = { ok: false, reason: 'not-in-era' };\n\n/** Whether a `tools/list` entry advertises a non-object `outputSchema` root that needs the SEP-2106 legacy wrap. */\nfunction toolNeedsLegacyWrap(t: unknown): t is { outputSchema: Record<string, unknown> } {\n return isPlainObject(t) && isPlainObject(t['outputSchema']) && isNonObjectJsonSchemaRoot(t['outputSchema']);\n}\n\n/** The wire→neutral trust boundary: a decoded 2025-era wire result is adopted as the neutral `Result` here (the module's single deliberate assertion). */\nfunction toNeutralResult(value: unknown): Result {\n return value as Result;\n}\n\nexport const rev2025Codec: WireCodec = {\n era: '2025-11-25',\n\n hasRequestMethod: hasRequestMethod2025,\n hasNotificationMethod: hasNotificationMethod2025,\n\n // ── Function-only validation surface ──\n validateRequest: (method: string, raw: unknown) => triState(getRequestSchema(method), raw),\n validateResult: (method: string, raw: unknown) => triState(getResultSchema(method), raw),\n validateNotification: (method: string, raw: unknown) => triState(getNotificationSchema(method), raw),\n // No in-band input-request vocabulary on this era: elicitation, sampling\n // and roots are real wire request methods here (see the registry).\n hasInputRequestMethod: (): boolean => false,\n validateInputRequest: (): ValidateOutcome<never> => NOT_IN_ERA,\n validateInputResponse: (): ValidateOutcome<never> => NOT_IN_ERA,\n\n // Arrow literals can't carry overload signatures; the cast is sound (the\n // boolean dispatches to exactly the schema each overload names).\n samplingResultVariant: ((hasTools: boolean, raw: unknown) =>\n triState(hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema, raw)) as WireCodec['samplingResultVariant'],\n\n // The 2025 era carries no per-request `_meta` envelope — legacy wire\n // bytes stay identical (the never-stamp guarantee, outbound-request half).\n outboundEnvelope: (_material: OutboundEnvelopeMaterial): undefined => undefined,\n validateEnvelopeMeta: (_meta: Readonly<Record<string, unknown>>): EnvelopeIssue[] => [],\n\n projectCallToolResult(result: CallToolResult, advertisedOutputSchema): CallToolResult {\n // Era-agnostic SEP-2106 §4.3 TextContent auto-append first (value-shape-based).\n const withText = appendTextFallbackForNonObject(result);\n const sc = withText.structuredContent;\n if (sc === undefined) return withText;\n // SEP-2106 result-side projection. Wrap as `{result:<sc>}` when EITHER:\n // - the value is non-object (array/primitive/`null`) — REGARDLESS of\n // advertised schema, because the 2025 wire shape requires\n // `structuredContent` to be an object (a schema-less tool returning\n // `[1,2,3]` would otherwise ship wire-illegal bytes), or\n // - the advertised `outputSchema` has a non-object root — so the\n // result satisfies the wrapped schema this codec's\n // `encodeResult('tools/list', …)` advertised for the same tool.\n const valueIsNonObject = typeof sc !== 'object' || sc === null || Array.isArray(sc);\n const schemaWrapped = advertisedOutputSchema !== undefined && isNonObjectJsonSchemaRoot(advertisedOutputSchema);\n if (!valueIsNonObject && !schemaWrapped) return withText;\n return { ...withText, structuredContent: { result: sc } };\n },\n\n decodeResult(_method: string, raw: unknown): DecodedResult {\n // Strip-on-lift (Q1-SD3 ii): a foreign `resultType` on the 2025 leg is\n // dropped before validation, whatever its value. There is no\n // discrimination on this era — `resultType` carries no meaning here.\n if (isPlainObject(raw) && 'resultType' in raw) {\n const stripped = { ...raw };\n delete stripped['resultType'];\n return { kind: 'complete', result: toNeutralResult(stripped) };\n }\n return { kind: 'complete', result: toNeutralResult(raw) };\n },\n\n // The never-stamp guarantee: never writes 2026 vocabulary. Identity for\n // every result EXCEPT the SEP-2106 `tools/list` projection (see header).\n // Copy-on-write: a listing with no non-object outputSchema roots returns\n // the same reference (the byte-identity suite pins this).\n encodeResult(method: string, result: Result): Result {\n if (method !== 'tools/list') return result;\n const tools = (result as { tools?: unknown }).tools;\n if (!Array.isArray(tools) || !tools.some(t => toolNeedsLegacyWrap(t))) return result;\n return {\n ...result,\n tools: tools.map(t => (toolNeedsLegacyWrap(t) ? { ...t, outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) } : t))\n } as Result;\n },\n\n // The −32002 resource-not-found domain code maps to −32602 on the wire on\n // this era too (matching what the deployed v1.x SDK already emits — this\n // is not a behavior change for v1.x peers). There is deliberately no era\n // branch that preserves −32002.\n encodeErrorCode: (code: number): number => (code === -32_002 ? -32_602 : code),\n\n // The 2025 era never requires a per-request envelope.\n checkInboundEnvelope: (_material: LiftedWireMaterial): string | undefined => undefined\n};\n","/**\n * Cache-hint plumbing for cacheable results (protocol revision 2026-07-28).\n *\n * The 2026-07-28 revision requires `ttlMs`/`cacheScope` on the cacheable\n * result types (SEP-2549 `CacheableResult`). The values are resolved at the\n * era-aware encode seam (the 2026 wire codec's `encodeResult`), most specific\n * author first:\n *\n * 1. fields the handler returned on the result itself (when valid),\n * 2. a configured cache hint attached by the server layer\n * (per-registration hint, then the server-level per-operation hint,\n * combined per field — see {@linkcode attachCacheHintFallback}),\n * 3. the conservative defaults `{ ttlMs: 0, cacheScope: 'private' }`.\n *\n * The configured hint travels from the (era-blind) server configuration to the\n * (era-aware) encode seam on a symbol-keyed property of the result object —\n * {@linkcode RESULT_CACHE_HINT_FALLBACK}. Symbol-keyed properties are never\n * serialized to JSON, so attaching a hint can never change what a 2025-era\n * response looks like on the wire: only the 2026-era codec reads (and removes)\n * it while filling the required fields. The 2025-era codec has no cache code\n * path at all.\n */\n\n/** The cache scopes defined for cacheable results (SEP-2549). */\nexport type CacheScope = 'public' | 'private';\n\n/**\n * A cache hint for a cacheable result (protocol revision 2026-07-28): the\n * values to emit for `ttlMs` / `cacheScope` when the handler does not provide\n * them itself. Absent fields fall back to the conservative defaults\n * (`ttlMs: 0`, `cacheScope: 'private'`).\n */\nexport interface CacheHint {\n /** Cache lifetime in milliseconds. Must be a non-negative safe integer. */\n ttlMs?: number;\n /** Whether the result may be cached by shared caches (`public`) or only by the requesting client (`private`). */\n cacheScope?: CacheScope;\n}\n\n/**\n * The operations whose results are cacheable on the 2026-07-28 revision (the\n * `CacheableResult` extenders). This list is closed: no other operation's\n * result ever receives cache fields from the SDK.\n */\nexport const CACHEABLE_RESULT_METHODS = [\n 'tools/list',\n 'prompts/list',\n 'resources/list',\n 'resources/templates/list',\n 'resources/read',\n 'server/discover'\n] as const;\n\n/** A method whose result is cacheable on the 2026-07-28 revision. */\nexport type CacheableResultMethod = (typeof CACHEABLE_RESULT_METHODS)[number];\n\n/** Whether the given method's result is cacheable on the 2026-07-28 revision. */\nexport function isCacheableResultMethod(method: string): method is CacheableResultMethod {\n return (CACHEABLE_RESULT_METHODS as readonly string[]).includes(method);\n}\n\n/**\n * The symbol-keyed carrier for a configured cache hint on a result object.\n * Symbol properties are invisible to JSON serialization, so the carrier can be\n * attached era-blind: only the 2026-era encode seam consumes it.\n */\nexport const RESULT_CACHE_HINT_FALLBACK: unique symbol = Symbol('modelcontextprotocol.resultCacheHintFallback');\n\n/** A result object that may carry a configured cache-hint fallback. */\ninterface CacheHintCarrier {\n [RESULT_CACHE_HINT_FALLBACK]?: CacheHint;\n}\n\n/**\n * Attaches a configured cache hint to a result as the encode-time fallback.\n * Returns the result unchanged when there is nothing to attach. When a more\n * specific hint is already attached, the two hints are combined per field\n * (most-specific-author-wins for each of `ttlMs` and `cacheScope`): the\n * per-registration hint attached by the feature layer keeps every field it\n * sets, and the server-level per-operation hint only fills the fields the\n * more specific hint leaves unset.\n */\nexport function attachCacheHintFallback<T extends object>(result: T, hint: CacheHint | undefined): T {\n if (hint === undefined) {\n return result;\n }\n const attached = (result as CacheHintCarrier)[RESULT_CACHE_HINT_FALLBACK];\n if (attached === undefined) {\n return { ...result, [RESULT_CACHE_HINT_FALLBACK]: hint };\n }\n const merged: CacheHint = {};\n const ttlMs = attached.ttlMs ?? hint.ttlMs;\n if (ttlMs !== undefined) {\n merged.ttlMs = ttlMs;\n }\n const cacheScope = attached.cacheScope ?? hint.cacheScope;\n if (cacheScope !== undefined) {\n merged.cacheScope = cacheScope;\n }\n return { ...result, [RESULT_CACHE_HINT_FALLBACK]: merged };\n}\n\n/** Reads the configured cache-hint fallback attached to a result, if any. */\nexport function cacheHintFallbackOf(result: object): CacheHint | undefined {\n return (result as CacheHintCarrier)[RESULT_CACHE_HINT_FALLBACK];\n}\n\n/**\n * Whether a value is a valid `ttlMs`: a non-negative safe integer. Safe\n * integers are required because the wire schemas validate `ttlMs` as an\n * integer within `Number.MIN_SAFE_INTEGER`/`Number.MAX_SAFE_INTEGER`; a value\n * outside that range is treated as invalid here so it falls through to the\n * next author instead of being emitted and rejected downstream.\n */\nexport function isValidCacheTtlMs(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\n}\n\n/** Whether a value is a valid `cacheScope`. */\nexport function isValidCacheScope(value: unknown): value is CacheScope {\n return value === 'public' || value === 'private';\n}\n\n/**\n * Validates a configured cache hint at configuration time. Throws a\n * `RangeError` naming the offending field, so misconfiguration fails at\n * startup/registration rather than silently degrading at encode time.\n */\nexport function assertValidCacheHint(hint: CacheHint, context: string): void {\n if (hint.ttlMs !== undefined && !isValidCacheTtlMs(hint.ttlMs)) {\n throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`);\n }\n if (hint.cacheScope !== undefined && !isValidCacheScope(hint.cacheScope)) {\n throw new RangeError(\n `Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`\n );\n }\n}\n","/**\n * Error codes for protocol errors that cross the wire as JSON-RPC error responses.\n * These follow the JSON-RPC specification and MCP-specific extensions.\n */\nexport enum ProtocolErrorCode {\n // Standard JSON-RPC error codes\n ParseError = -32_700,\n InvalidRequest = -32_600,\n MethodNotFound = -32_601,\n InvalidParams = -32_602,\n InternalError = -32_603,\n\n // MCP-specific error codes\n /**\n * Resource not found.\n *\n * Receive-tolerated only: the SDK never EMITS `-32002` — `resources/read`\n * misses answer `-32602` (Invalid Params) on every protocol revision per\n * the 2026-07-28 spec MUST, and a handler-thrown `-32002` is mapped to\n * `-32602` at the era encode seam. The member stays importable so clients\n * can recognise `-32002` from peers built on earlier SDK releases (the\n * spec's \"clients SHOULD also accept `-32002`\" backwards-compatibility\n * clause). Throw `ResourceNotFoundError` instead.\n */\n ResourceNotFound = -32_002,\n /**\n * Processing the request requires a capability the client did not declare\n * in the request's `clientCapabilities` (protocol revision 2026-07-28).\n */\n MissingRequiredClientCapability = -32_021,\n /**\n * The request's protocol version is unknown to the server or unsupported\n * by it (protocol revision 2026-07-28).\n */\n UnsupportedProtocolVersion = -32_022,\n UrlElicitationRequired = -32_042\n}\n","import { ProtocolErrorCode } from './enums';\nimport type {\n ClientCapabilities,\n ElicitRequestURLParams,\n MissingRequiredClientCapabilityErrorData,\n UnsupportedProtocolVersionErrorData\n} from './types';\n\n/**\n * Protocol errors are JSON-RPC errors that cross the wire as error responses.\n * They use numeric error codes from the {@linkcode ProtocolErrorCode} enum.\n */\nexport class ProtocolError extends Error {\n constructor(\n public readonly code: number,\n message: string,\n public readonly data?: unknown\n ) {\n super(message);\n this.name = 'ProtocolError';\n }\n\n /**\n * Factory method to create the appropriate error type based on the error code and data\n */\n static fromError(code: number, message: string, data?: unknown): ProtocolError {\n // Check for specific error types\n if (code === ProtocolErrorCode.UrlElicitationRequired && data) {\n const errorData = data as { elicitations?: unknown[] };\n if (errorData.elicitations) {\n return new UrlElicitationRequiredError(errorData.elicitations as ElicitRequestURLParams[], message);\n }\n }\n\n if (code === ProtocolErrorCode.UnsupportedProtocolVersion && data) {\n const errorData = data as Partial<UnsupportedProtocolVersionErrorData>;\n if (Array.isArray(errorData.supported) && typeof errorData.requested === 'string') {\n return new UnsupportedProtocolVersionError({ supported: errorData.supported, requested: errorData.requested }, message);\n }\n }\n\n // Resource not found is recognised on BOTH the spec-mandated −32602 and\n // the legacy −32002 (the spec's \"clients SHOULD also accept −32002\"\n // backwards-compatibility clause). On −32602 the data-shape parse is\n // narrowed to \"exactly `{ uri: string }` and nothing else\": a server's\n // own Invalid Params that happens to carry `data.uri` alongside other\n // keys (e.g. `{ uri, reason: 'uri must be https' }`) stays a generic\n // ProtocolError. On −32002 the code itself is the discriminator, so any\n // `data.uri` string suffices.\n if (code === ProtocolErrorCode.InvalidParams || code === ProtocolErrorCode.ResourceNotFound) {\n const errorData = data as Record<string, unknown> | undefined;\n if (\n typeof errorData?.uri === 'string' &&\n (code === ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)\n ) {\n return new ResourceNotFoundError(errorData.uri, message);\n }\n }\n\n if (code === ProtocolErrorCode.MissingRequiredClientCapability && data) {\n const errorData = data as Partial<MissingRequiredClientCapabilityErrorData>;\n if (\n errorData.requiredCapabilities !== null &&\n typeof errorData.requiredCapabilities === 'object' &&\n !Array.isArray(errorData.requiredCapabilities)\n ) {\n return new MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message);\n }\n }\n\n // Default to generic ProtocolError\n return new ProtocolError(code, message, data);\n }\n}\n\n/**\n * Error type for a `resources/read` miss: the requested resource does not\n * exist. The wire code is `-32602` (Invalid Params) on every protocol\n * revision — the spec MUST for revision 2026-07-28, and the value the v1.x\n * SDK has always emitted on earlier revisions. The error data echoes the\n * requested URI.\n *\n * Recognise this error by checking `error.data` is exactly `{ uri: string }`\n * (a `-32602` whose data carries `uri` and nothing else is resource-not-found;\n * any other `-32602` is an ordinary Invalid Params). For backwards compatibility, clients should also\n * accept `-32002` as resource not found — earlier SDK builds emitted that\n * code, and {@linkcode ProtocolError.fromError} reconstructs this class for\n * either code **when `error.data` carries `uri`** (a bare `-32002` without\n * `data.uri` stays a generic {@linkcode ProtocolError}). Do not rely on\n * `instanceof` — it does not work across separately bundled copies of the\n * SDK.\n */\nexport class ResourceNotFoundError extends ProtocolError {\n constructor(uri: string, message: string = `Resource not found: ${uri}`) {\n super(ProtocolErrorCode.InvalidParams, message, { uri });\n }\n\n /** The URI that was requested and not found. */\n get uri(): string {\n return (this.data as { uri: string }).uri;\n }\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 ProtocolError {\n constructor(elicitations: ElicitRequestURLParams[], message: string = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) {\n super(ProtocolErrorCode.UrlElicitationRequired, message, {\n elicitations: elicitations\n });\n }\n\n get elicitations(): ElicitRequestURLParams[] {\n return (this.data as { elicitations: ElicitRequestURLParams[] })?.elicitations ?? [];\n }\n}\n\n/**\n * Error type for the `-32022` UnsupportedProtocolVersion protocol error (protocol\n * revision 2026-07-28): the request's protocol version is unknown to the server or\n * unsupported by it.\n *\n * The error data lists the protocol versions the receiver supports (`supported`),\n * so the sender can choose a mutually supported version and retry, and echoes the\n * version that was requested (`requested`).\n */\nexport class UnsupportedProtocolVersionError extends ProtocolError {\n constructor(data: UnsupportedProtocolVersionErrorData, message: string = `Unsupported protocol version: ${data.requested}`) {\n super(ProtocolErrorCode.UnsupportedProtocolVersion, message, data);\n }\n\n /**\n * Protocol versions the receiver supports.\n */\n get supported(): string[] {\n return (this.data as UnsupportedProtocolVersionErrorData).supported;\n }\n\n /**\n * The protocol version that was requested.\n */\n get requested(): string {\n return (this.data as UnsupportedProtocolVersionErrorData).requested;\n }\n}\n\n/**\n * Error type for the `-32021` MissingRequiredClientCapability protocol error\n * (protocol revision 2026-07-28): processing the request requires a capability\n * the client did not declare in the request's `clientCapabilities`.\n *\n * The error data lists the missing capabilities (`requiredCapabilities`) in\n * the `ClientCapabilities` shape, so the client can see exactly what it would\n * have to declare for the request to be served. On HTTP, the response status\n * is `400 Bad Request`.\n *\n * Recognize this error by its code and `data.requiredCapabilities` rather than\n * by class identity (`instanceof` does not work across separately bundled\n * copies of the SDK).\n */\nexport class MissingRequiredClientCapabilityError extends ProtocolError {\n constructor(\n data: MissingRequiredClientCapabilityErrorData,\n message: string = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(', ')}`\n ) {\n super(ProtocolErrorCode.MissingRequiredClientCapability, message, data);\n }\n\n /**\n * The capabilities the server requires from the client to process the\n * request (only the missing capabilities are listed).\n */\n get requiredCapabilities(): ClientCapabilities {\n return (this.data as MissingRequiredClientCapabilityErrorData).requiredCapabilities;\n }\n}\n","/**\n * The outbound result encode contract for the 2026-07-28 wire codec, as pure,\n * individually-testable steps. `encodeResult` applies them in order:\n *\n * 1. {@linkcode stampResultType} — the `resultType` discriminator. The SDK\n * stamps `'complete'`; a handler-provided value passes through only for\n * methods whose spec result vocabulary goes beyond `'complete'` (the\n * multi round-trip request methods, whose results may be\n * `input_required`). A non-`'complete'` value returned by a handler for\n * any other method is a server bug and fails loudly (internal error)\n * rather than being mis-typed on the wire.\n * 2. {@linkcode fillCacheFields} — the required `ttlMs`/`cacheScope` fields\n * on cacheable results (SEP-2549), filled only when the post-stamp\n * `resultType` is `'complete'` and the method is one of the cacheable\n * operations. Resolution is most-specific-author-first: valid\n * handler-returned values, then the configured cache hint attached by the\n * server layer, then the conservative defaults\n * `{ ttlMs: 0, cacheScope: 'private' }`. Invalid handler-returned values\n * never reach the wire — they fall through to the next author.\n *\n * Ordering matters and is pinned by tests: the stamp runs before the fill, so\n * an `input_required` result is never given cache fields.\n */\nimport type { CacheHint } from '../../shared/resultCacheHints';\nimport {\n cacheHintFallbackOf,\n isCacheableResultMethod,\n isValidCacheScope,\n isValidCacheTtlMs,\n RESULT_CACHE_HINT_FALLBACK\n} from '../../shared/resultCacheHints';\nimport { ProtocolErrorCode } from '../../types/enums';\nimport { ProtocolError } from '../../types/errors';\nimport type { Result } from '../../types/types';\n\n/** The default cache policy when neither the handler nor configuration provides one. */\nexport const DEFAULT_CACHE_TTL_MS = 0;\nexport const DEFAULT_CACHE_SCOPE = 'private';\n\n/**\n * Request methods whose spec result vocabulary goes beyond `'complete'` on the\n * 2026-07-28 revision: their results may be `input_required` (multi\n * round-trip requests), so a handler-provided `resultType` passes through the\n * stamp untouched. `subscriptions/listen` is NOT in this set: it never emits\n * a JSON-RPC result — termination is stream close (HTTP) or\n * `notifications/cancelled` (stdio) per the spec.\n */\nexport const EXTENDED_RESULT_TYPE_METHODS: readonly string[] = ['tools/call', 'prompts/get', 'resources/read'];\n\n/**\n * Step 1 of the encode contract: ensure the outbound result carries the\n * required `resultType` discriminator.\n *\n * - No handler-provided value → stamp `'complete'`.\n * - Handler-provided `'complete'` → kept as-is.\n * - Handler-provided non-`'complete'` value on a method whose vocabulary\n * allows it ({@linkcode EXTENDED_RESULT_TYPE_METHODS}) → passes through.\n * The value is forwarded verbatim — the wire vocabulary is an open union and\n * the SDK does not validate the string, so emitting a `resultType` the\n * negotiated revision does not define is the handler author's\n * responsibility.\n * - Handler-provided non-`'complete'` value on any other method → internal\n * error (loud): the value would be mis-typed on the wire, and silently\n * rewriting it would hide a server bug.\n */\nexport function stampResultType(method: string, result: Result): Result {\n const provided = (result as Record<string, unknown>)['resultType'];\n if (provided === undefined) {\n return { ...result, resultType: 'complete' } as Result;\n }\n if (provided === 'complete') {\n return result;\n }\n if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) {\n return result;\n }\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`\n );\n}\n\n/**\n * Step 2 of the encode contract: fill the required `ttlMs`/`cacheScope` fields\n * on cacheable results.\n *\n * Applies only when the (post-stamp) `resultType` is `'complete'` and the\n * method is one of the cacheable operations; everything else is returned\n * untouched apart from removing the configured-hint carrier. Field resolution\n * is per field, most specific author first: a valid handler-returned value,\n * then the configured cache hint attached by the server layer, then the\n * defaults. Handler-returned values are validated at encode time (`ttlMs`\n * must be a non-negative integer, `cacheScope` must be `'public'` or\n * `'private'`); invalid values are ignored rather than emitted.\n */\nexport function fillCacheFields(method: string, result: Result): Result {\n const fallback = cacheHintFallbackOf(result);\n const resultType = (result as Record<string, unknown>)['resultType'];\n\n if (resultType !== 'complete' || !isCacheableResultMethod(method)) {\n // Not a cache-fill target. Drop the configured-hint carrier if one was\n // attached so it never travels past the encode seam.\n return fallback === undefined ? result : stripCacheHintFallback(result);\n }\n\n const provided = result as Record<string, unknown>;\n const ttlMs = isValidCacheTtlMs(provided['ttlMs']) ? (provided['ttlMs'] as number) : resolveTtlMs(fallback);\n const cacheScope = isValidCacheScope(provided['cacheScope']) ? (provided['cacheScope'] as string) : resolveCacheScope(fallback);\n\n const filled = { ...provided, ttlMs, cacheScope } as Record<string | symbol, unknown>;\n delete filled[RESULT_CACHE_HINT_FALLBACK];\n return filled as Result;\n}\n\nfunction resolveTtlMs(fallback: CacheHint | undefined): number {\n return fallback !== undefined && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS;\n}\n\nfunction resolveCacheScope(fallback: CacheHint | undefined): string {\n return fallback !== undefined && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE;\n}\n\nfunction stripCacheHintFallback(result: Result): Result {\n const copy = { ...result } as Record<string | symbol, unknown>;\n delete copy[RESULT_CACHE_HINT_FALLBACK];\n return copy as Result;\n}\n","/**\n * 2026-era wire schemas (protocol revision 2026-07-28).\n *\n * Fully self-contained — no runtime imports from types/schemas.ts. The\n * neutral types/schemas.ts layer is the public-API superset and is free to\n * evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN\n * against the 2026-07-28 anchor. Every era-shared building block (content\n * blocks, resources, prompts, capabilities, notifications, …) that the wire\n * shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at\n * the point this revision was sealed, dependencies first. The only cross-layer\n * dependency is `import type { JSONObject, JSONValue }` from the neutral types\n * barrel — pure structural type aliases with no parse behavior.\n *\n * This module is the only place the per-request `_meta` envelope is modeled.\n * The envelope is wire-only vocabulary: the protocol layer lifts it off\n * inbound requests before any handler runs and surfaces it at\n * `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at\n * dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc\n * deferral (\"enforced per request at dispatch time, not here\") is now\n * discharged by that codec step.\n *\n * No 2025-era traffic ever touches this module, so requiredness here is\n * bare and spec-exact (the shared-schema `.catch` hazards do not apply).\n */\nimport * as z from 'zod/v4';\n\nimport { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, LOG_LEVEL_META_KEY, PROTOCOL_VERSION_META_KEY } from '../../types/constants';\nimport type { JSONObject, JSONValue } from '../../types/types';\n\n/* ════════════════════════════════════════════════════════════════════════════\n * Frozen neutral-layer building blocks\n *\n * Everything from this point until the next ═-banner is a verbatim frozen\n * copy of a schema that, at the time this revision was sealed, lived in the\n * neutral types/schemas.ts. They are copied dependencies-first so no forward\n * references exist. They are NOT re-derived from the public layer at runtime —\n * a widening or tightening landed on types/schemas.ts has no effect here until\n * a deliberate per-revision re-freeze.\n * ════════════════════════════════════════════════════════════════════════════ */\n\nexport const JSONValueSchema: z.ZodType<JSONValue, JSONValue> = z.lazy(() =>\n z.union([z.string(), z.number(), z.boolean(), z.null(), z.record(z.string(), JSONValueSchema), z.array(JSONValueSchema)])\n);\nexport const JSONObjectSchema: z.ZodType<JSONObject, JSONObject> = z.record(z.string(), JSONValueSchema);\n\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/**\n * An opaque token used to represent a cursor for pagination.\n */\nexport const CursorSchema = z.string();\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/**\n * The sender or recipient of messages and data in a conversation.\n */\nexport const RoleSchema = z.enum(['user', 'assistant']);\n\n/**\n * The severity of a log message.\n */\nexport const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\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(\n val => {\n try {\n atob(val);\n return true;\n } catch {\n return false;\n }\n },\n { message: 'Invalid Base64 string' }\n);\n\n/* ─── Request/notification meta and base params ─── */\n\n/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\nexport const TaskMetadataSchema = z.object({\n ttl: z.number().optional()\n});\n\n/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\nexport const RelatedTaskMetadataSchema = z.object({\n taskId: z.string()\n});\n\nexport const 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 'io.modelcontextprotocol/related-task': RelatedTaskMetadataSchema.optional()\n});\n\nexport const BaseRequestParamsSchema = z.object({\n _meta: RequestMetaSchema.optional()\n});\n\n/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\nexport const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({\n task: TaskMetadataSchema.optional()\n});\n\nexport const NotificationsParamsSchema = z.object({\n _meta: RequestMetaSchema.optional()\n});\n\nexport const NotificationSchema = z.object({\n method: z.string(),\n params: NotificationsParamsSchema.loose().optional()\n});\n\n/* ─── Icons / base metadata / implementation ─── */\n\nexport const IconSchema = z.object({\n src: z.string(),\n mimeType: z.string().optional(),\n sizes: z.array(z.string()).optional(),\n theme: z.enum(['light', 'dark']).optional()\n});\n\nexport const IconsSchema = z.object({\n icons: z.array(IconSchema).optional()\n});\n\nexport const BaseMetadataSchema = z.object({\n name: z.string(),\n title: z.string().optional()\n});\n\nexport const ImplementationSchema = BaseMetadataSchema.extend({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n version: z.string(),\n websiteUrl: z.string().optional(),\n description: z.string().optional()\n});\n\n/* ─── Capability schemas ─── */\n\nconst FormElicitationCapabilitySchema = z.intersection(\n z.object({\n applyDefaults: z.boolean().optional()\n }),\n JSONObjectSchema\n);\n\nconst ElicitationCapabilitySchema = z.preprocess(\n value => {\n if (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value as Record<string, unknown>).length === 0) {\n return { form: {} };\n }\n return value;\n },\n z.intersection(\n z.object({\n form: FormElicitationCapabilitySchema.optional(),\n url: JSONObjectSchema.optional()\n }),\n JSONObjectSchema.optional()\n )\n);\n\n/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\nexport const ClientTasksCapabilitySchema = z.looseObject({\n list: JSONObjectSchema.optional(),\n cancel: JSONObjectSchema.optional(),\n requests: z\n .looseObject({\n sampling: z\n .looseObject({\n createMessage: JSONObjectSchema.optional()\n })\n .optional(),\n elicitation: z\n .looseObject({\n create: JSONObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n\n/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\nexport const ServerTasksCapabilitySchema = z.looseObject({\n list: JSONObjectSchema.optional(),\n cancel: JSONObjectSchema.optional(),\n requests: z\n .looseObject({\n tools: z\n .looseObject({\n call: JSONObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n\nexport const ClientCapabilitiesSchema = z.object({\n experimental: z.record(z.string(), JSONObjectSchema).optional(),\n sampling: z\n .object({\n context: JSONObjectSchema.optional(),\n tools: JSONObjectSchema.optional()\n })\n .optional(),\n elicitation: ElicitationCapabilitySchema.optional(),\n roots: z\n .object({\n listChanged: z.boolean().optional()\n })\n .optional(),\n tasks: ClientTasksCapabilitySchema.optional(),\n extensions: z.record(z.string(), JSONObjectSchema).optional()\n});\n\nexport const ServerCapabilitiesSchema = z.object({\n experimental: z.record(z.string(), JSONObjectSchema).optional(),\n logging: JSONObjectSchema.optional(),\n completions: JSONObjectSchema.optional(),\n prompts: z\n .object({\n listChanged: z.boolean().optional()\n })\n .optional(),\n resources: z\n .object({\n subscribe: z.boolean().optional(),\n listChanged: z.boolean().optional()\n })\n .optional(),\n tools: z\n .object({\n listChanged: z.boolean().optional()\n })\n .optional(),\n tasks: ServerTasksCapabilitySchema.optional(),\n extensions: z.record(z.string(), JSONObjectSchema).optional()\n});\n\n/* ─── Progress / logging notifications ─── */\n\nexport const ProgressSchema = z.object({\n progress: z.number(),\n total: z.optional(z.number()),\n message: z.optional(z.string())\n});\n\nexport const ProgressNotificationParamsSchema = z.object({\n ...NotificationsParamsSchema.shape,\n ...ProgressSchema.shape,\n progressToken: ProgressTokenSchema\n});\n\nexport const ProgressNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/progress'),\n params: ProgressNotificationParamsSchema\n});\n\nexport const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({\n level: LoggingLevelSchema,\n logger: z.string().optional(),\n data: z.unknown()\n});\n\nexport const LoggingMessageNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/message'),\n params: LoggingMessageNotificationParamsSchema\n});\n\n/* ─── Resource contents / annotations ─── */\n\nexport const ResourceContentsSchema = z.object({\n uri: z.string(),\n mimeType: z.optional(z.string()),\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n\nexport const TextResourceContentsSchema = ResourceContentsSchema.extend({\n text: z.string()\n});\n\nexport const BlobResourceContentsSchema = ResourceContentsSchema.extend({\n blob: Base64Schema\n});\n\nexport const AnnotationsSchema = z.object({\n audience: z.array(RoleSchema).optional(),\n priority: z.number().min(0).max(1).optional(),\n lastModified: z.iso.datetime({ offset: true }).optional()\n});\n\n/* ─── Resources / templates / list-changed notifications ─── */\n\nexport const ResourceSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n uri: z.string(),\n description: z.optional(z.string()),\n mimeType: z.optional(z.string()),\n size: z.optional(z.number()),\n annotations: AnnotationsSchema.optional(),\n _meta: z.optional(z.looseObject({}))\n});\n\nexport const ResourceTemplateSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n uriTemplate: z.string(),\n description: z.optional(z.string()),\n mimeType: z.optional(z.string()),\n annotations: AnnotationsSchema.optional(),\n _meta: z.optional(z.looseObject({}))\n});\n\nexport const ResourceListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n\nexport const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({\n uri: z.string()\n});\n\nexport const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/updated'),\n params: ResourceUpdatedNotificationParamsSchema\n});\n\n/* ─── Prompts / content blocks ─── */\n\nexport const PromptArgumentSchema = z.object({\n name: z.string(),\n description: z.optional(z.string()),\n required: z.optional(z.boolean())\n});\n\nexport const PromptSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n description: z.optional(z.string()),\n arguments: z.optional(z.array(PromptArgumentSchema)),\n _meta: z.optional(z.looseObject({}))\n});\n\nexport const PromptListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/prompts/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n\nexport const TextContentSchema = z.object({\n type: z.literal('text'),\n text: z.string(),\n annotations: AnnotationsSchema.optional(),\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n\nexport const ImageContentSchema = z.object({\n type: z.literal('image'),\n data: Base64Schema,\n mimeType: z.string(),\n annotations: AnnotationsSchema.optional(),\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n\nexport const AudioContentSchema = z.object({\n type: z.literal('audio'),\n data: Base64Schema,\n mimeType: z.string(),\n annotations: AnnotationsSchema.optional(),\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n\nexport const ToolUseContentSchema = z.object({\n type: z.literal('tool_use'),\n name: z.string(),\n id: z.string(),\n input: z.record(z.string(), z.unknown()),\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n\nexport const EmbeddedResourceSchema = z.object({\n type: z.literal('resource'),\n resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]),\n annotations: AnnotationsSchema.optional(),\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n\nexport const ResourceLinkSchema = ResourceSchema.extend({\n type: z.literal('resource_link')\n});\n\nexport const ContentBlockSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ResourceLinkSchema,\n EmbeddedResourceSchema\n]);\n\nexport const PromptMessageSchema = z.object({\n role: RoleSchema,\n content: ContentBlockSchema\n});\n\n/* ─── Tool annotations / tool list-changed / sampling primitives ─── */\n\nexport const ToolAnnotationsSchema = z.object({\n title: z.string().optional(),\n readOnlyHint: z.boolean().optional(),\n destructiveHint: z.boolean().optional(),\n idempotentHint: z.boolean().optional(),\n openWorldHint: z.boolean().optional()\n});\n\nexport const ToolListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tools/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n\nexport const ModelHintSchema = z.object({\n name: z.string().optional()\n});\n\nexport const ModelPreferencesSchema = z.object({\n hints: z.array(ModelHintSchema).optional(),\n costPriority: z.number().min(0).max(1).optional(),\n speedPriority: z.number().min(0).max(1).optional(),\n intelligencePriority: z.number().min(0).max(1).optional()\n});\n\nexport const ToolChoiceSchema = z.object({\n mode: z.enum(['auto', 'required', 'none']).optional()\n});\n\n/* ─── Elicitation primitive-schema vocabulary ─── */\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\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\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\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\nexport const TitledSingleSelectEnumSchemaSchema = z.object({\n type: z.literal('string'),\n title: z.string().optional(),\n description: z.string().optional(),\n oneOf: z.array(\n z.object({\n const: z.string(),\n title: z.string()\n })\n ),\n default: z.string().optional()\n});\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\nexport const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\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\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(\n z.object({\n const: z.string(),\n title: z.string()\n })\n )\n }),\n default: z.array(z.string()).optional()\n});\n\nexport const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n\nexport const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n\nexport const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n\nexport const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({\n mode: z.literal('form').optional(),\n message: z.string(),\n requestedSchema: z\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown())\n});\n\n/* ─── Completion references / roots ─── */\n\nexport const ResourceTemplateReferenceSchema = z.object({\n type: z.literal('ref/resource'),\n uri: z.string()\n});\n\nexport const PromptReferenceSchema = z.object({\n type: z.literal('ref/prompt'),\n name: z.string()\n});\n\nexport const RootSchema = z.object({\n uri: z.string().startsWith('file://'),\n name: z.string().optional(),\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n\n/* ════════════════════════════════════════════════════════════════════════════\n * End of frozen neutral-layer building blocks. Everything below is the\n * 2026-07-28 wire-specific vocabulary (envelope, forks, results, requests,\n * notifications) composed against the frozen copies above.\n * ════════════════════════════════════════════════════════════════════════════ */\n\n/* 2026-era capability forks (defined ahead of the envelope, which composes\n * the client fork). The frozen shapes minus the deleted `tasks` key: `tasks`\n * is 2025-only vocabulary with no slot on this revision, consistent with the\n * encode-side deletion (Q1-SD3 iii).\n *\n * Both forks list their members EXPLICITLY (composing the frozen member\n * schemas by reference) rather than using `.omit()`: the envelope schema\n * below reaches the bundled package declarations, and an `.omit()` inference\n * is a mapped type whose printed member order is unstable across dts-rollup\n * builds (api-report flap). The explicit list doubles as the fork's deletion\n * statement — a member added to the frozen shape must be re-adjudicated here. */\nconst sharedClientCapabilityShape = ClientCapabilitiesSchema.shape;\nexport const ClientCapabilities2026Schema = z.object({\n experimental: sharedClientCapabilityShape.experimental,\n sampling: sharedClientCapabilityShape.sampling,\n elicitation: sharedClientCapabilityShape.elicitation,\n roots: sharedClientCapabilityShape.roots,\n extensions: sharedClientCapabilityShape.extensions\n});\nconst sharedServerCapabilityShape = ServerCapabilitiesSchema.shape;\nexport const ServerCapabilities2026Schema = z.object({\n experimental: sharedServerCapabilityShape.experimental,\n logging: sharedServerCapabilityShape.logging,\n completions: sharedServerCapabilityShape.completions,\n prompts: sharedServerCapabilityShape.prompts,\n resources: sharedServerCapabilityShape.resources,\n tools: sharedServerCapabilityShape.tools,\n extensions: sharedServerCapabilityShape.extensions\n});\n\n/* Per-request `_meta` envelope */\n/**\n * The per-request `_meta` envelope carried by every request under protocol revision\n * 2026-07-28: the protocol version governing the request, the client implementation\n * info, and the client's capabilities — declared per request rather than once at\n * initialization — plus the optional log-level opt-in.\n *\n * This schema models the complete envelope on its own (loose: foreign keys\n * pass through - the lift extracts exactly the reserved keys, so enforcement\n * never sees extension material). Requiredness is enforced per request at\n * dispatch time by the 2026-era codec's `checkInboundEnvelope` step.\n */\nexport const RequestMetaEnvelopeSchema = 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 * The MCP protocol version being used for this request. For the HTTP transport,\n * the value must match the `MCP-Protocol-Version` header.\n */\n [PROTOCOL_VERSION_META_KEY]: z.string(),\n /**\n * Identifies the client software making the request.\n */\n [CLIENT_INFO_META_KEY]: ImplementationSchema,\n /**\n * The client's capabilities for this specific request. An empty object means the\n * client supports no optional capabilities. Servers must not infer capabilities\n * from prior requests. Validated with the 2026 fork: `tasks` has no slot on\n * this revision (deleted vocabulary), matching the server-side fork wired\n * into `DiscoverResultSchema`.\n */\n [CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema,\n /**\n * The desired log level for this request. When absent, the server must not send\n * `notifications/message` notifications for the request.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months.\n */\n [LOG_LEVEL_META_KEY]: LoggingLevelSchema.optional()\n});\n\n/* ------------------------------------------------------------------------ *\n * Forked payload vocabulary (shared-tier admission rule, ATK-B section 1):\n * `Tool` and `SamplingMessage` are bidirectionally incomparable between the\n * 2025-11-25 and 2026-07-28 anchors, so they FORK per wire module instead of\n * sitting in the shared tier. The forks below are 2026-anchor-exact:\n * - Tool (2026) has NO `execution` member (ToolExecution and its\n * `taskSupport` carrier are deleted vocabulary) — a 2026 peer's tool that\n * carries one is stripped on parse, and the encode side strips it from\n * outbound tools (Q1-SD3 iii).\n * - SamplingMessage (2026) is composed against the 2026 anchor shape.\n * ------------------------------------------------------------------------ */\n\n/** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */\nexport const ToolSchema = z.object({\n ...BaseMetadataSchema.shape,\n ...IconsSchema.shape,\n description: z.string().optional(),\n // Anchor-exact: { $schema?: string; type: 'object'; [key: string]: unknown }\n inputSchema: z.looseObject({\n $schema: z.string().optional(),\n type: z.literal('object')\n }),\n // Anchor-exact: { $schema?: string; [key: string]: unknown }\n outputSchema: z\n .looseObject({\n $schema: z.string().optional()\n })\n .optional(),\n annotations: ToolAnnotationsSchema.optional(),\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n\n/** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */\nexport const ToolResultContentSchema = z.object({\n type: z.literal('tool_result'),\n toolUseId: z.string(),\n content: z.array(ContentBlockSchema),\n structuredContent: z.unknown().optional(),\n isError: z.boolean().optional(),\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n\n/** 2026-era sampling content union (composes the forked tool-result shape). */\nexport const SamplingMessageContentBlockSchema = z.union([\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n ToolResultContentSchema\n]);\n\n/** 2026-era SamplingMessage (anchor-exact: single block or array). */\nexport const SamplingMessageSchema = z.object({\n role: RoleSchema,\n content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]),\n _meta: z.record(z.string(), z.unknown()).optional()\n});\n\n/* ------------------------------------------------------------------------ *\n * Result side. `resultType` is a sender obligation (spec.types.2026-07-28\n * Result.resultType: \"Servers implementing this protocol version MUST\n * include this field\") and a receiver default (schema.ts:208 — clients MUST\n * treat absent `resultType` as 'complete'). These are the WIRE-TRUE\n * artifacts — the corpus and the parity suite parse them; `decodeResult`\n * parses with them and then LIFTS (drops resultType) to the neutral shape.\n * Sender-side requiredness is enforced by construction (`encodeResult`\n * stamps it), so the parse side carries the receiver default.\n * ------------------------------------------------------------------------ */\n\n/** Open union per the anchor: 'complete' | 'input_required' | string. */\nexport const ResultTypeSchema = z.string();\n\nconst wireMeta = z.record(z.string(), z.unknown()).optional();\n\nfunction wireResult<T extends z.core.$ZodLooseShape>(shape: T) {\n return z.looseObject({\n _meta: wireMeta,\n /** Sender MUST set; receiver defaults absent → 'complete' (spec receiver leniency). */\n resultType: ResultTypeSchema.default('complete'),\n ...shape\n });\n}\n\nexport const ResultSchema = wireResult({});\n\nexport const PaginatedResultSchema = wireResult({\n nextCursor: CursorSchema.optional()\n});\n\nexport const CallToolResultSchema = wireResult({\n content: z.array(ContentBlockSchema),\n structuredContent: z.unknown().optional(),\n isError: z.boolean().optional()\n});\n\nexport const ListToolsResultSchema = wireResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n tools: z.array(ToolSchema),\n nextCursor: CursorSchema.optional()\n});\n\nexport const ListPromptsResultSchema = wireResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n prompts: z.array(PromptSchema),\n nextCursor: CursorSchema.optional()\n});\n\nexport const GetPromptResultSchema = wireResult({\n description: z.string().optional(),\n messages: z.array(PromptMessageSchema)\n});\n\nexport const ListResourcesResultSchema = wireResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n resources: z.array(ResourceSchema),\n nextCursor: CursorSchema.optional()\n});\n\nexport const ListResourceTemplatesResultSchema = wireResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n resourceTemplates: z.array(ResourceTemplateSchema),\n nextCursor: CursorSchema.optional()\n});\n\nexport const ReadResourceResultSchema = wireResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n});\n\nexport const CompleteResultSchema = wireResult({\n completion: z\n .object({\n values: z.array(z.string()).max(100),\n total: z.number().int().optional(),\n hasMore: z.boolean().optional()\n })\n .loose()\n});\n\n/** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */\nexport const CacheableResultSchema = wireResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private'])\n});\n\nexport const DiscoverResultSchema = wireResult({\n // Receiver-side leniency per caching.mdx:56-58 — the probe classifier must\n // accept a DiscoverResult that omits OR malforms the cache hints (spec:\n // \"if ttlMs is negative, clients SHOULD ignore it and treat it as 0\").\n // `.catch()` returns the fallback for both absence and parse failure;\n // sender obligation is enforced by `encodeResult`, not by parse.\n // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise\n ttlMs: z.number().int().min(0).catch(0),\n // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise\n cacheScope: z.enum(['public', 'private']).catch('private'),\n supportedVersions: z.array(z.string()),\n capabilities: ServerCapabilities2026Schema,\n serverInfo: ImplementationSchema,\n instructions: z.string().optional()\n});\n\n/* ------------------------------------------------------------------------ *\n * Multi round-trip requests (SEP-2322). The in-band vocabulary of this\n * revision: server→client interactions are carried as de-JSON-RPC'd embedded\n * requests inside an `input_required` result, fulfilled by the client, and\n * echoed back as embedded responses on the retry. The shapes below are\n * anchor-exact wire artifacts (corpus + parity); the lenient dispatch-time\n * schemas the multi-round-trip driver parses embedded requests with live in\n * `inputRequired.ts`.\n *\n * The sampling shapes fork here (they compose the forked SamplingMessage /\n * Tool payloads); the URL-mode elicitation params fork here (the draft\n * removed `elicitationId`; the shared schema keeps it because it is required\n * on the frozen 2025-11-25 revision); form-mode elicitation params are\n * revision-identical and are composed by reference from the shared schema.\n * ------------------------------------------------------------------------ */\n\n/** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */\nexport const CreateMessageRequestParamsSchema = z.object({\n messages: z.array(SamplingMessageSchema),\n modelPreferences: ModelPreferencesSchema.optional(),\n systemPrompt: z.string().optional(),\n includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(),\n temperature: z.number().optional(),\n maxTokens: z.number().int(),\n stopSequences: z.array(z.string()).optional(),\n metadata: JSONObjectSchema.optional(),\n tools: z.array(ToolSchema).optional(),\n toolChoice: ToolChoiceSchema.optional()\n});\n\n/** 2026-era embedded sampling request (de-JSON-RPC'd). */\nexport const CreateMessageRequestSchema = z.object({\n method: z.literal('sampling/createMessage'),\n params: CreateMessageRequestParamsSchema\n});\n\n/**\n * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input\n * requests do NOT carry the per-request `_meta` envelope on this revision —\n * the anchor declares a bare optional `_meta` on `params`.\n */\nexport const ListRootsRequestSchema = z.object({\n method: z.literal('roots/list'),\n params: z.object({ _meta: z.record(z.string(), z.unknown()).optional() }).optional()\n});\n\n/** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */\nexport const CreateMessageResultSchema = z.object({\n ...SamplingMessageSchema.shape,\n model: z.string(),\n stopReason: z.string().optional()\n});\n\n/** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */\nexport const ListRootsResultSchema = z.object({\n roots: z.array(RootSchema)\n});\n\n/** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */\nexport const ElicitResultSchema = z.object({\n action: z.enum(['accept', 'decline', 'cancel']),\n content: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional()\n});\n\n/**\n * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed\n * `elicitationId` (and the `notifications/elicitation/complete` channel it\n * keyed) — the shared schema keeps the field because it is required on the\n * frozen 2025-11-25 revision.\n */\nexport const ElicitRequestURLParamsSchema = z.object({\n mode: z.literal('url'),\n message: z.string(),\n url: z.string().url()\n});\n\n/** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */\nexport const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);\n\n/** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */\nexport const ElicitRequestSchema = z.object({\n method: z.literal('elicitation/create'),\n params: ElicitRequestParamsSchema\n});\n\n/** A single embedded input request (one of the three demoted server→client requests). */\nexport const InputRequestSchema = z.union([CreateMessageRequestSchema, ListRootsRequestSchema, ElicitRequestSchema]);\n\n/** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */\nexport const InputResponseSchema = z.union([CreateMessageResultSchema, ListRootsResultSchema, ElicitResultSchema]);\n\n/** Map of embedded input requests, keyed by server-assigned identifiers. */\nexport const InputRequestsSchema = z.record(z.string(), InputRequestSchema);\n\n/** Map of embedded input responses, keyed by the corresponding request identifiers. */\nexport const InputResponsesSchema = z.record(z.string(), InputResponseSchema);\n\n/**\n * The wire InputRequiredResult: `resultType: 'input_required'` plus at least\n * one of `inputRequests` / `requestState` (the at-least-one rule is enforced\n * at the server seam, not by this parse shape).\n */\nexport const InputRequiredResultSchema = wireResult({\n inputRequests: InputRequestsSchema.optional(),\n requestState: z.string().optional()\n});\n\n/** The retry-channel members carried by client-initiated requests on this revision. */\nconst retryParamsShape = {\n inputResponses: InputResponsesSchema.optional(),\n requestState: z.string().optional()\n};\n\n/** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */\nexport const InputResponseRequestParamsSchema = z.object({\n _meta: RequestMetaEnvelopeSchema,\n ...retryParamsShape\n});\n\n/* ------------------------------------------------------------------------ *\n * Request side. Two views per method:\n * - WIRE-TRUE (`<Name>RequestSchema`): params `_meta` carries the REQUIRED\n * envelope (anchor RequestParams._meta is required). The corpus and parity\n * suite consume these.\n * - DISPATCH (post-lift, internal to the registry): the protocol layer's\n * universal lift has already extracted the envelope, so dispatch parses a\n * 2025-like shape with optional `_meta` (progressToken/extension keys\n * only) and NO 2025-only members (`task` is undeclared and strips —\n * payload-level deletion is physical on this leg).\n * ------------------------------------------------------------------------ */\n\n/** Post-lift request `_meta` (progressToken + extension keys; loose). */\nconst DispatchRequestMetaSchema = z.looseObject({\n progressToken: ProgressTokenSchema.optional()\n});\n\nfunction wireRequest<M extends string, T extends z.core.$ZodLooseShape>(method: M, paramsShape: T) {\n return z.object({\n method: z.literal(method),\n params: z.object({ _meta: RequestMetaEnvelopeSchema, ...paramsShape })\n });\n}\n\nfunction dispatchRequest<M extends string, T extends z.core.$ZodLooseShape>(method: M, paramsShape: T) {\n return z.object({\n method: z.literal(method),\n params: z.object({ _meta: DispatchRequestMetaSchema.optional(), ...paramsShape }).optional()\n });\n}\n\nconst callToolParamsShape = {\n name: z.string(),\n arguments: z.record(z.string(), z.unknown()).optional(),\n // Multi-round-trip retry channel (the wire-true view models it; dispatch\n // never sees it — the protocol layer lifts it before any handler runs).\n ...retryParamsShape\n};\nconst paginatedParamsShape = { cursor: CursorSchema.optional() };\n\nexport const CallToolRequestSchema = wireRequest('tools/call', callToolParamsShape);\nexport const ListToolsRequestSchema = wireRequest('tools/list', paginatedParamsShape);\nexport const ListPromptsRequestSchema = wireRequest('prompts/list', paginatedParamsShape);\nexport const GetPromptRequestSchema = wireRequest('prompts/get', {\n name: z.string(),\n arguments: z.record(z.string(), z.string()).optional(),\n ...retryParamsShape\n});\nexport const ListResourcesRequestSchema = wireRequest('resources/list', paginatedParamsShape);\nexport const ListResourceTemplatesRequestSchema = wireRequest('resources/templates/list', paginatedParamsShape);\nexport const ReadResourceRequestSchema = wireRequest('resources/read', { uri: z.string(), ...retryParamsShape });\nconst completeParamsShape = {\n ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),\n argument: z.object({ name: z.string(), value: z.string() }),\n context: z.object({ arguments: z.record(z.string(), z.string()).optional() }).optional()\n};\nexport const CompleteRequestSchema = wireRequest('completion/complete', completeParamsShape);\nexport const DiscoverRequestSchema = wireRequest('server/discover', {});\n\n/** Anchor SubscriptionFilter (2026-only). */\nexport const SubscriptionFilterSchema = z.object({\n toolsListChanged: z.boolean().optional(),\n promptsListChanged: z.boolean().optional(),\n resourcesListChanged: z.boolean().optional(),\n resourceSubscriptions: z.array(z.string()).optional()\n});\nconst subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema };\nexport const SubscriptionsListenRequestSchema = wireRequest('subscriptions/listen', subscriptionsListenParamsShape);\n\n/** Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on the graceful-close result. */\nexport const SubscriptionsListenResultMetaSchema = z.looseObject({\n 'io.modelcontextprotocol/subscriptionId': RequestIdSchema\n});\n\n/**\n * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen`\n * response signalling that the subscription has ended gracefully (server\n * shutdown). An abrupt transport close carries no response — the client treats\n * stream-close-without-result as a disconnect.\n */\nexport const SubscriptionsListenResultSchema = z.looseObject({\n /** Required `_meta` (the subscriptionId stamp); the result body is otherwise empty. */\n _meta: SubscriptionsListenResultMetaSchema,\n resultType: ResultTypeSchema.default('complete')\n});\n\n/**\n * The 2026-era request-method set — the hand-registry seed (see registry.ts\n * for the seed decisions). The dispatch maps below are mapped types over this\n * union, so a missing entry, an extra entry, or an entry pointing at another\n * method's schema is a compile error; the CI registry-diff oracle pins the\n * same set against the anchor at runtime.\n */\nexport type Rev2026RequestMethod =\n | 'tools/call'\n | 'tools/list'\n | 'prompts/get'\n | 'prompts/list'\n | 'resources/list'\n | 'resources/templates/list'\n | 'resources/read'\n | 'completion/complete'\n | 'server/discover'\n | 'subscriptions/listen';\n\n/** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */\nexport const dispatchRequestSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType<{ method: M }> } = {\n 'tools/call': dispatchRequest('tools/call', callToolParamsShape),\n 'tools/list': dispatchRequest('tools/list', paginatedParamsShape),\n 'prompts/get': dispatchRequest('prompts/get', {\n name: z.string(),\n arguments: z.record(z.string(), z.string()).optional()\n }),\n 'prompts/list': dispatchRequest('prompts/list', paginatedParamsShape),\n 'resources/list': dispatchRequest('resources/list', paginatedParamsShape),\n 'resources/templates/list': dispatchRequest('resources/templates/list', paginatedParamsShape),\n 'resources/read': dispatchRequest('resources/read', { uri: z.string() }),\n 'completion/complete': dispatchRequest('completion/complete', completeParamsShape),\n 'server/discover': dispatchRequest('server/discover', {}),\n 'subscriptions/listen': dispatchRequest('subscriptions/listen', subscriptionsListenParamsShape)\n};\n\n/** Dispatch (post-lift) result schemas, keyed by method — what the funnel\n * validates AFTER `decodeResult` consumed `resultType`. */\nfunction liftedResult<T extends z.core.$ZodLooseShape>(shape: T) {\n return z.looseObject({ _meta: wireMeta, ...shape });\n}\n\nexport const dispatchResultSchemas: { readonly [M in Rev2026RequestMethod]: z.ZodType } = {\n 'tools/call': liftedResult({\n content: z.array(ContentBlockSchema),\n structuredContent: z.unknown().optional(),\n isError: z.boolean().optional()\n }),\n 'tools/list': liftedResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n tools: z.array(ToolSchema),\n nextCursor: CursorSchema.optional()\n }),\n 'prompts/get': liftedResult({\n description: z.string().optional(),\n messages: z.array(PromptMessageSchema)\n }),\n 'prompts/list': liftedResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n prompts: z.array(PromptSchema),\n nextCursor: CursorSchema.optional()\n }),\n 'resources/list': liftedResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n resources: z.array(ResourceSchema),\n nextCursor: CursorSchema.optional()\n }),\n 'resources/templates/list': liftedResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n resourceTemplates: z.array(ResourceTemplateSchema),\n nextCursor: CursorSchema.optional()\n }),\n 'resources/read': liftedResult({\n ttlMs: z.number().int().min(0),\n cacheScope: z.enum(['public', 'private']),\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n }),\n 'completion/complete': liftedResult({\n completion: z\n .object({\n values: z.array(z.string()).max(100),\n total: z.number().int().optional(),\n hasMore: z.boolean().optional()\n })\n .loose()\n }),\n 'server/discover': liftedResult({\n // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise\n ttlMs: z.number().int().min(0).catch(0),\n // eslint-disable-next-line unicorn/prefer-top-level-await -- Zod `.catch()`, not a Promise\n cacheScope: z.enum(['public', 'private']).catch('private'),\n supportedVersions: z.array(z.string()),\n capabilities: ServerCapabilities2026Schema,\n serverInfo: ImplementationSchema,\n instructions: z.string().optional()\n }),\n // `subscriptions/listen` receives a JSON-RPC result only on a server-side\n // graceful close (the empty `SubscriptionsListenResult` — `_meta` carries\n // the subscriptionId stamp). The dispatch result schema stays the lifted\n // empty body so the mapped type is total; the listen-response demux is\n // entry-layer (`Client._onresponse`) and never reaches `decodeResult`.\n 'subscriptions/listen': liftedResult({})\n};\n\n/* ------------------------------------------------------------------------ *\n * Notifications. The 2026 notification set: cancelled, progress, message,\n * resources/updated, resources/list_changed, tools/list_changed,\n * prompts/list_changed. Deleted: initialized, roots/list_changed,\n * tasks/status, elicitation/complete (removed from the draft together with\n * URL-elicitation's elicitationId — both remain 2025-11-25 vocabulary only).\n * The shapes are revision-identical to the shared schemas, which are\n * composed by reference, EXCEPT cancelled (forks below: this revision\n * requires `requestId`) and the 2026-only subscriptions/acknowledged.\n * ------------------------------------------------------------------------ */\n\n/**\n * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the\n * subscriptions/listen demux key typed when present. Only the anchor-exact\n * SHAPE is modeled here — listen delivery itself (filter gating, demux,\n * teardown) is #14 scope and not implemented by this module.\n */\nexport const NotificationMetaSchema = z.looseObject({\n /**\n * The JSON-RPC ID of the `subscriptions/listen` request that opened the\n * stream a notification was delivered on; absent on notifications not\n * delivered via a subscription stream.\n */\n 'io.modelcontextprotocol/subscriptionId': RequestIdSchema.optional()\n});\n\n/** Anchor SubscriptionsAcknowledgedNotification (2026-only). */\nexport const SubscriptionsAcknowledgedNotificationSchema = z.object({\n method: z.literal('notifications/subscriptions/acknowledged'),\n params: z.object({\n _meta: NotificationMetaSchema.optional(),\n notifications: SubscriptionFilterSchema\n })\n});\n\n/**\n * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId`\n * is REQUIRED on this revision — the shared schema keeps it optional because\n * the frozen 2025-11-25 shape declares it optional (task cancellation goes\n * through `tasks/cancel` there). Requiredness is bare because no 2025-era\n * traffic touches this module.\n */\nexport const CancelledNotificationParamsSchema = z.object({\n _meta: NotificationMetaSchema.optional(),\n /**\n * The ID of the request to cancel. This MUST correspond to the ID of a\n * request the client previously issued.\n */\n requestId: RequestIdSchema,\n /**\n * An optional string describing the reason for the cancellation. This MAY\n * be logged or presented to the user.\n */\n reason: z.string().optional()\n});\n\n/** 2026-era `notifications/cancelled` (see the params fork above). */\nexport const CancelledNotificationSchema = z.object({\n method: z.literal('notifications/cancelled'),\n params: CancelledNotificationParamsSchema\n});\n\n/** The 2026-era notification-method set (the hand-registry seed; see the deletion list above). */\nexport type Rev2026NotificationMethod =\n | 'notifications/cancelled'\n | 'notifications/progress'\n | 'notifications/message'\n | 'notifications/resources/updated'\n | 'notifications/resources/list_changed'\n | 'notifications/tools/list_changed'\n | 'notifications/prompts/list_changed'\n | 'notifications/subscriptions/acknowledged';\n\nexport const notificationSchemas2026: { readonly [M in Rev2026NotificationMethod]: z.ZodType<{ method: M }> } = {\n 'notifications/cancelled': CancelledNotificationSchema,\n 'notifications/progress': ProgressNotificationSchema,\n 'notifications/message': LoggingMessageNotificationSchema,\n 'notifications/resources/updated': ResourceUpdatedNotificationSchema,\n 'notifications/resources/list_changed': ResourceListChangedNotificationSchema,\n 'notifications/tools/list_changed': ToolListChangedNotificationSchema,\n 'notifications/prompts/list_changed': PromptListChangedNotificationSchema,\n 'notifications/subscriptions/acknowledged': SubscriptionsAcknowledgedNotificationSchema\n};\n\n/* ------------------------------------------------------------------------ *\n * Response envelopes (wire-true; parity/corpus artifacts).\n * ------------------------------------------------------------------------ */\nconst wireResultResponse = <T extends z.ZodType>(result: T) =>\n z\n .object({\n jsonrpc: z.literal('2.0'),\n id: z.union([z.string(), z.number().int()]),\n result\n })\n .strict();\n\nexport const JSONRPCResultResponseSchema = wireResultResponse(ResultSchema);\n// The multi-round-trip methods may answer with either their final result or an\n// InputRequiredResult (anchor: `result: CallToolResult | InputRequiredResult`).\nexport const CallToolResultResponseSchema = wireResultResponse(z.union([CallToolResultSchema, InputRequiredResultSchema]));\nexport const ListToolsResultResponseSchema = wireResultResponse(ListToolsResultSchema);\nexport const ListPromptsResultResponseSchema = wireResultResponse(ListPromptsResultSchema);\nexport const GetPromptResultResponseSchema = wireResultResponse(z.union([GetPromptResultSchema, InputRequiredResultSchema]));\nexport const ListResourcesResultResponseSchema = wireResultResponse(ListResourcesResultSchema);\nexport const ListResourceTemplatesResultResponseSchema = wireResultResponse(ListResourceTemplatesResultSchema);\nexport const ReadResourceResultResponseSchema = wireResultResponse(z.union([ReadResourceResultSchema, InputRequiredResultSchema]));\nexport const CompleteResultResponseSchema = wireResultResponse(CompleteResultSchema);\nexport const DiscoverResultResponseSchema = wireResultResponse(DiscoverResultSchema);\n","/**\n * In-band input-request vocabulary of the 2026-07-28 revision (SEP-2322\n * multi round-trip requests), dispatch view.\n *\n * The three former server→client wire requests (`elicitation/create`,\n * `sampling/createMessage`, `roots/list`) are NOT wire request methods on\n * this revision — they are demoted to de-JSON-RPC'd payloads embedded in an\n * `input_required` result. The multi-round-trip driver dispatches those\n * embedded payloads to the client's registered handlers through the normal\n * handler machinery, and these are the schemas that dispatch parses them\n * with: lenient where the anchor's wire-true artifacts are strict (an\n * embedded request never carries the per-request `_meta` envelope), exact\n * where the vocabulary forks (the sampling shapes compose the forked\n * SamplingMessage/Tool payloads).\n *\n * Registry membership is intentionally NOT granted here — these methods stay\n * absent from the 2026-era request registry (a peer sending one as a wire\n * request still gets −32601 by absence). Only the codec's\n * `inputRequestSchema`/`inputResponseSchema` accessors expose them.\n */\nimport * as z from 'zod/v4';\n\nimport type { RequestMethod, RequestTypeMap, ResultTypeMap } from '../../types/types';\nimport {\n CreateMessageRequestParamsSchema,\n CreateMessageResultSchema,\n ElicitRequestParamsSchema,\n ElicitResultSchema,\n ListRootsResultSchema\n} from './schemas';\n\n/** The embedded input-request methods of the 2026-07-28 revision. */\nexport const INPUT_REQUEST_METHODS_2026 = ['elicitation/create', 'sampling/createMessage', 'roots/list'] as const;\n\nexport type InputRequestMethod2026 = (typeof INPUT_REQUEST_METHODS_2026)[number];\n\n/** Dispatch-time (lenient) embedded request schemas, keyed by method. */\nconst inputRequestSchemas2026: Record<InputRequestMethod2026, z.ZodType> = {\n 'elicitation/create': z.object({\n method: z.literal('elicitation/create'),\n params: ElicitRequestParamsSchema\n }),\n 'sampling/createMessage': z.object({\n method: z.literal('sampling/createMessage'),\n params: CreateMessageRequestParamsSchema\n }),\n 'roots/list': z.object({\n method: z.literal('roots/list'),\n params: z.looseObject({}).optional()\n })\n};\n\n/** Embedded (bare) response schemas, keyed by the request method they answer. */\nconst inputResponseSchemas2026: Record<InputRequestMethod2026, z.ZodType> = {\n 'elicitation/create': ElicitResultSchema,\n 'sampling/createMessage': CreateMessageResultSchema,\n 'roots/list': ListRootsResultSchema\n};\n\nexport function isInputRequestMethod2026(method: string): method is InputRequestMethod2026 {\n return (INPUT_REQUEST_METHODS_2026 as readonly string[]).includes(method);\n}\n\n/**\n * Gets the dispatch (lenient) schema for an embedded input request, or\n * `undefined` for methods that are not in-band vocabulary on this era.\n * The typed overload mirrors `WireCodec.inputRequestSchema`.\n */\nexport function getInputRequestSchema2026<M extends RequestMethod>(method: M): z.ZodType<RequestTypeMap[M]> | undefined;\nexport function getInputRequestSchema2026(method: string): z.ZodType | undefined;\nexport function getInputRequestSchema2026(method: string): z.ZodType | undefined {\n return isInputRequestMethod2026(method) ? inputRequestSchemas2026[method] : undefined;\n}\n\n/**\n * Gets the bare embedded-response schema answering an embedded input request,\n * or `undefined` for methods that are not in-band vocabulary on this era.\n */\nexport function getInputResponseSchema2026<M extends RequestMethod>(method: M): z.ZodType<ResultTypeMap[M]> | undefined;\nexport function getInputResponseSchema2026(method: string): z.ZodType | undefined;\nexport function getInputResponseSchema2026(method: string): z.ZodType | undefined {\n return isInputRequestMethod2026(method) ? inputResponseSchemas2026[method] : undefined;\n}\n","/**\n * The 2026-era method registries (protocol revision 2026-07-28).\n *\n * Registry membership IS the deletion story: there are NO entries for\n * `initialize`, `notifications/initialized`, `ping`, `logging/setLevel`,\n * `resources/subscribe`, `resources/unsubscribe`,\n * `notifications/roots/list_changed`, `notifications/elicitation/complete`\n * (removed from the draft schema; 2025-11-25-only vocabulary), the task\n * family, or the server→client wire-request channel — so an era-mismatched\n * method falls to −32601 by absence inbound and a typed local error outbound,\n * with no table to forget.\n *\n * HAND-REGISTRY SEED DECISIONS (pinned by the CI registry-diff oracle, which\n * fails LOUD if this list and the anchor diff ever disagree):\n * - `sampling/createMessage`, `elicitation/create`, `roots/list`: the anchor\n * still carries their method literals on bare interfaces, but 2026 DEMOTES\n * them from wire requests to in-band `InputRequest` payloads — the entire\n * server→client JSON-RPC request channel is deleted (`ServerRequest` has\n * no 2026 export). A generator walking method literals would re-admit them\n * (the ATK-D flavor-b trap); this hand registry excludes them by\n * construction. Their in-band role lands with the MRTR driver (#13).\n * - `subscriptions/listen` + `notifications/subscriptions/acknowledged`\n * (SEP-1865): 2026-only vocabulary, present here as registry shells.\n * Dispatch never reaches a registered handler — the serving entries\n * (`createMcpHandler`, `serveStdio`) recognize listen at the entry layer\n * and own ack/filter/stamp/teardown themselves; on the client side\n * `Client.listen()` sends directly on the transport (string-typed\n * request id, transport-level demux) rather than via `request()`.\n */\nimport type * as z from 'zod/v4';\n\nimport type { NotificationMethod, NotificationTypeMap, RequestMethod, RequestTypeMap, ResultTypeMap } from '../../types/types';\nimport type { Rev2026NotificationMethod, Rev2026RequestMethod } from './schemas';\nimport { dispatchRequestSchemas, dispatchResultSchemas, notificationSchemas2026 } from './schemas';\n\n/** The 2026-era request-method set (registry membership = the deletion story). */\nexport function hasRequestMethod2026(method: string): method is Rev2026RequestMethod {\n return Object.prototype.hasOwnProperty.call(dispatchRequestSchemas, method);\n}\n\n/** The 2026-era notification-method set. */\nexport function hasNotificationMethod2026(method: string): method is Rev2026NotificationMethod {\n return Object.prototype.hasOwnProperty.call(notificationSchemas2026, method);\n}\n\n/** Result-map membership (same key set as the request map on this era). */\nfunction hasResultMethod2026(method: string): method is Rev2026RequestMethod {\n return Object.prototype.hasOwnProperty.call(dispatchResultSchemas, method);\n}\n\n/**\n * Gets the dispatch (post-lift) Zod schema for a given request method.\n * Returns `undefined` for methods this era's registry does not define.\n * The typed overload mirrors `WireCodec.requestSchema` so call sites with a\n * statically known method need no type assertion.\n */\nexport function getRequestSchema2026<M extends RequestMethod>(method: M): z.ZodType<RequestTypeMap[M]> | undefined;\nexport function getRequestSchema2026(method: string): z.ZodType | undefined;\nexport function getRequestSchema2026(method: string): z.ZodType | undefined {\n return hasRequestMethod2026(method) ? dispatchRequestSchemas[method] : undefined;\n}\n\n/**\n * Gets the dispatch (post-lift) Zod schema for validating results of a given\n * request method. Returns `undefined` for methods this era's registry does\n * not define.\n * @see getRequestSchema2026 for the typed-overload contract.\n */\nexport function getResultSchema2026<M extends RequestMethod>(method: M): z.ZodType<ResultTypeMap[M]> | undefined;\nexport function getResultSchema2026(method: string): z.ZodType | undefined;\nexport function getResultSchema2026(method: string): z.ZodType | undefined {\n return hasResultMethod2026(method) ? dispatchResultSchemas[method] : undefined;\n}\n\n/**\n * Gets the Zod schema for a given notification method.\n * Returns `undefined` for methods this era's registry does not define.\n * @see getRequestSchema2026 for the typed-overload contract.\n */\nexport function getNotificationSchema2026<M extends NotificationMethod>(method: M): z.ZodType<NotificationTypeMap[M]> | undefined;\nexport function getNotificationSchema2026(method: string): z.ZodType | undefined;\nexport function getNotificationSchema2026(method: string): z.ZodType | undefined {\n return hasNotificationMethod2026(method) ? notificationSchemas2026[method] : undefined;\n}\n\n/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */\nexport const rev2026RequestMethods: readonly string[] = Object.keys(dispatchRequestSchemas);\nexport const rev2026NotificationMethods: readonly string[] = Object.keys(notificationSchemas2026);\n","/**\n * The 2026-era wire codec (protocol revision 2026-07-28).\n *\n * Decode = raw-first `resultType` discrimination (the structural V-1 home:\n * the RAW value is inspected BEFORE any schema validation, so a non-complete\n * result can never be masked into a hollow success by a tolerant schema),\n * then wire-exact parse, then lift (drop the wire member). Encode = the\n * stamp seam: the known deleted-field set is strictly enforced (Q1-SD3 iii) —\n * the 2026 wire types have no slot for `execution.taskSupport` or\n * `capabilities.tasks`, so the encode mapping deletes them; era-blind\n * handlers stay era-invisible while deleted vocabulary cannot cross eras\n * through the parse-free outbound path — and then the encode contract steps\n * run (see `encodeContract.ts`): the `resultType` stamp (with handler\n * pass-through for the multi round-trip methods) followed by the required\n * `ttlMs`/`cacheScope` fill on cacheable results.\n *\n * Q1-SD3 postures implemented here:\n * (i) absent `resultType` from a 2026-classified peer → typed error NAMING\n * the violation. The spec's absent⇒complete bridge is scoped to\n * EARLIER-revision servers (spec.types.2026-07-28.ts Result.resultType:\n * \"Servers implementing this protocol version MUST include this field\")\n * and is deliberately NOT extended to modern traffic.\n * (ii) `input_required` → the driver-seam payload (the multi-round-trip\n * driver, M4.1/#13, consumes it; until then the protocol layer surfaces\n * the discriminated kind as a typed local error, no retry).\n * (iii) unrecognized kinds → invalid, no retry (DQ5).\n */\nimport type * as z from 'zod/v4';\n\nimport { SdkError, SdkErrorCode } from '../../errors/sdkErrors';\nimport { CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, LOG_LEVEL_META_KEY, PROTOCOL_VERSION_META_KEY } from '../../types/constants';\nimport type { CallToolResult, Result } from '../../types/types';\nimport type { DecodedResult, EnvelopeIssue, LiftedWireMaterial, OutboundEnvelopeMaterial, ValidateOutcome, WireCodec } from '../codec';\nimport { appendTextFallbackForNonObject } from '../textFallback';\nimport { fillCacheFields, stampResultType } from './encodeContract';\nimport { getInputRequestSchema2026, getInputResponseSchema2026 } from './inputRequired';\nimport {\n getNotificationSchema2026,\n getRequestSchema2026,\n getResultSchema2026,\n hasNotificationMethod2026,\n hasRequestMethod2026\n} from './registry';\nimport {\n CallToolResultSchema,\n CompleteResultSchema,\n DiscoverResultSchema,\n GetPromptResultSchema,\n ListPromptsResultSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesResultSchema,\n ListToolsResultSchema,\n ReadResourceResultSchema,\n RequestMetaEnvelopeSchema\n} from './schemas';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */\nfunction triState<T>(schema: z.ZodType<T> | undefined, raw: unknown): ValidateOutcome<T> {\n if (schema === undefined) return { ok: false, reason: 'not-in-era' };\n const parsed = schema.safeParse(raw);\n return parsed.success ? { ok: true, value: parsed.data } : { ok: false, reason: 'invalid', message: String(parsed.error) };\n}\n\nconst NOT_IN_ERA: ValidateOutcome<never> = { ok: false, reason: 'not-in-era' };\n\n/** The reserved `_meta` keys an envelope must carry on this era (in reporting order). */\nconst REQUIRED_ENVELOPE_KEYS: readonly string[] = [PROTOCOL_VERSION_META_KEY, CLIENT_INFO_META_KEY, CLIENT_CAPABILITIES_META_KEY];\n\n/** Strip the known deleted-field set from an outbound result (Q1-SD3 iii). */\nfunction enforceDeletedFields(method: string, result: Result): Result {\n let next: Record<string, unknown> = result as Record<string, unknown>;\n let copied = false;\n const copy = () => {\n if (!copied) {\n next = { ...next };\n copied = true;\n }\n return next;\n };\n\n // tools arrays: execution (the taskSupport carrier) is deleted vocabulary.\n const tools = (result as { tools?: unknown }).tools;\n if (method === 'tools/list' && Array.isArray(tools) && tools.some(tool => isPlainObject(tool) && 'execution' in tool)) {\n copy().tools = tools.map(tool => {\n if (!isPlainObject(tool) || !('execution' in tool)) return tool;\n const rest = { ...tool };\n delete rest['execution'];\n return rest;\n });\n }\n\n // capability objects: the `tasks` capability is deleted vocabulary.\n const capabilities = (result as { capabilities?: unknown }).capabilities;\n if (isPlainObject(capabilities) && 'tasks' in capabilities) {\n const rest = { ...capabilities };\n delete rest['tasks'];\n copy().capabilities = rest;\n }\n\n return next as Result;\n}\n\nexport const rev2026Codec: WireCodec & {\n /**\n * @deprecated Off-interface in-band registry probe retained for the\n * existing inputRequiredFunnel pin. Use {@link WireCodec.validateInputRequest}\n * — its `not-in-era` outcome is the membership signal.\n */\n inputRequestSchema(method: string): unknown;\n} = {\n era: '2026-07-28',\n\n hasRequestMethod: hasRequestMethod2026,\n hasNotificationMethod: hasNotificationMethod2026,\n hasInputRequestMethod: (method: string): boolean => getInputRequestSchema2026(method) !== undefined,\n\n // ── Function-only validation surface ──\n validateRequest: (method: string, raw: unknown) => triState(getRequestSchema2026(method), raw),\n validateResult: (method: string, raw: unknown) => triState(getResultSchema2026(method), raw),\n validateNotification: (method: string, raw: unknown) => triState(getNotificationSchema2026(method), raw),\n // In-band multi-round-trip vocabulary: the demoted elicitation/sampling/\n // roots shapes carried inside `input_required` results (NOT wire request\n // methods on this era — registry membership is deliberately not granted).\n validateInputRequest: (method: string, raw: unknown) => triState(getInputRequestSchema2026(method), raw),\n validateInputResponse: (method: string, raw: unknown) => triState(getInputResponseSchema2026(method), raw),\n\n // Sampling is in-band on this era — callers fall through to\n // `validateInputResponse('sampling/createMessage', …)`.\n samplingResultVariant: (): ValidateOutcome<never> => NOT_IN_ERA,\n\n outboundEnvelope(material: OutboundEnvelopeMaterial): Readonly<Record<string, unknown>> {\n return {\n [PROTOCOL_VERSION_META_KEY]: material.protocolVersion,\n [CLIENT_INFO_META_KEY]: material.clientInfo,\n [CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities,\n ...(material.logLevel !== undefined && { [LOG_LEVEL_META_KEY]: material.logLevel })\n };\n },\n\n validateEnvelopeMeta(meta: Readonly<Record<string, unknown>>): EnvelopeIssue[] {\n const issues: EnvelopeIssue[] = [];\n for (const key of REQUIRED_ENVELOPE_KEYS) {\n if (!(key in meta)) issues.push({ key, problem: 'missing' });\n }\n const parsed = RequestMetaEnvelopeSchema.safeParse(meta);\n if (!parsed.success) {\n for (const issue of parsed.error.issues) {\n const path = issue.path.map(String);\n const key = path.length > 0 ? path.join('.') : '_meta';\n // Missing required keys were already reported above in canonical order.\n if (path.length === 1 && issues.some(existing => existing.key === key && existing.problem === 'missing')) {\n continue;\n }\n issues.push({ key, problem: issue.message });\n }\n }\n return issues;\n },\n\n // SEP-2106 result-side projection: no `{result:…}` wrap on the modern era\n // (the wire shape carries the natural `structuredContent` directly), but\n // the era-agnostic §4.3 TextContent auto-append still applies.\n projectCallToolResult: (result: CallToolResult): CallToolResult => appendTextFallbackForNonObject(result),\n\n // Retained off-interface for the inputRequiredFunnel registry-membership\n // pin (asserts the in-band schema set without exercising parse): the\n // function-only WireCodec contract carries no schema-returning members,\n // so this lives only on the concrete object's widened type.\n inputRequestSchema: getInputRequestSchema2026,\n\n decodeResult(method: string, raw: unknown): DecodedResult {\n if (!isPlainObject(raw)) {\n return {\n kind: 'invalid',\n error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method })\n };\n }\n\n // Step 1 — RAW discrimination, before any schema (V-1).\n const rawResultType = raw['resultType'];\n if (rawResultType === undefined) {\n // Q1-SD3 (i): hard error naming the violation.\n return {\n kind: 'invalid',\n error: new SdkError(\n SdkErrorCode.InvalidResult,\n `Invalid result for ${method}: missing required resultType — servers implementing protocol revision 2026-07-28 ` +\n `MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,\n { method, violation: 'missing-resultType' }\n )\n };\n }\n if (typeof rawResultType !== 'string') {\n return {\n kind: 'invalid',\n error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, {\n method,\n resultType: rawResultType\n })\n };\n }\n if (rawResultType === 'input_required') {\n // The driver seam (#13 consumes this payload).\n const rawInputRequests = raw['inputRequests'];\n const inputRequests = isPlainObject(rawInputRequests) ? rawInputRequests : {};\n const requestState = raw['requestState'];\n if (Object.keys(inputRequests).length === 0 && typeof requestState !== 'string') {\n // At-least-one rule, client side: with neither inputRequests\n // nor requestState there is nothing to fulfil and nothing to\n // echo — retrying would only resend the original params until\n // the round cap is exhausted, so fail fast instead.\n return {\n kind: 'invalid',\n error: new SdkError(\n SdkErrorCode.InvalidResult,\n `Invalid result for ${method}: input_required carries neither inputRequests nor requestState ` +\n `(every input_required result must include at least one of the two)`,\n { method, violation: 'input-required-missing-both' }\n )\n };\n }\n return {\n kind: 'input_required',\n inputRequests,\n ...(typeof requestState === 'string' && { requestState })\n };\n }\n if (rawResultType !== 'complete') {\n // Unrecognized kind ⇒ invalid, no retry (DQ5).\n return {\n kind: 'invalid',\n error: new SdkError(SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, {\n resultType: rawResultType,\n method\n })\n };\n }\n\n // Step 2 — wire-exact parse (registry methods), with resultType present.\n // Own-key lookup: `method` is peer-influenced on related-request\n // paths, and a prototype-chain hit (e.g. 'constructor') must not\n // masquerade as a schema and throw out of the decode hop.\n const wireSchema = Object.hasOwn(WIRE_RESULT_SCHEMAS, method) ? WIRE_RESULT_SCHEMAS[method] : undefined;\n if (wireSchema !== undefined) {\n const parsed = wireSchema.safeParse(raw);\n if (!parsed.success) {\n return {\n kind: 'invalid',\n error: new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method })\n };\n }\n }\n\n // Step 3 — lift: the wire discriminator is consumed.\n const lifted = { ...raw };\n delete lifted['resultType'];\n return { kind: 'complete', result: lifted as Result };\n },\n\n encodeResult(method: string, result: Result): Result {\n // The stamp seam, in pinned order: deleted-field strictness, then the\n // resultType stamp (handler pass-through only for methods whose\n // vocabulary goes beyond 'complete'), then the cache fill for the\n // cacheable operations (only on post-stamp 'complete' results).\n return fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result)));\n },\n\n // The −32002 resource-not-found domain code maps to −32602 Invalid Params\n // on the wire (the 2026-07-28 spec MUST for resources/read misses).\n encodeErrorCode: (code: number): number => (code === -32_002 ? -32_602 : code),\n\n checkInboundEnvelope(material: LiftedWireMaterial): string | undefined {\n if (material.envelope === undefined) {\n return (\n 'Request is missing the required _meta envelope for protocol revision 2026-07-28 ' +\n '(io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientInfo, io.modelcontextprotocol/clientCapabilities)'\n );\n }\n const parsed = RequestMetaEnvelopeSchema.safeParse(material.envelope);\n if (!parsed.success) {\n return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map(issue => issue.message).join('; ')}`;\n }\n return undefined;\n }\n};\n\n/** Wire-true result wrappers consulted by decode step 2, keyed by method. */\nconst WIRE_RESULT_SCHEMAS: Record<string, z.ZodType> = {\n 'tools/call': CallToolResultSchema,\n 'tools/list': ListToolsResultSchema,\n 'prompts/get': GetPromptResultSchema,\n 'prompts/list': ListPromptsResultSchema,\n 'resources/list': ListResourcesResultSchema,\n 'resources/templates/list': ListResourceTemplatesResultSchema,\n 'resources/read': ReadResourceResultSchema,\n 'completion/complete': CompleteResultSchema,\n 'server/discover': DiscoverResultSchema\n};\n","/**\n * The era-granular wire-codec layer (Q1 increment 2).\n *\n * The SDK separates a revision-neutral model layer (the public types — no\n * `resultType`, no `_meta` envelope keys, no retry fields) from per-revision\n * WIRE CODECS that own revision-exact schemas, method registries, and the\n * decode (wire → neutral lift) / encode (neutral → wire stamp) transforms.\n * The codec is a pure function of the negotiated protocol version, which is\n * ordinary connection state on the `Protocol` instance: the client stores it\n * when its handshake completes, the server stores it at `_oninitialize` (and\n * modern-era server instances get it set at instance binding by the entry).\n * There is no side table — era resolution is `codecForVersion(<instance\n * state>)`, with the pre-negotiation window covered by the outbound method\n * pins in `bootstrap.ts`.\n *\n * REQUIRED DISCLOSURE (Q1-SD1, era granularity): \"the negotiated version\n * determines which types are serialized/deserialized over the wire\" cashes\n * out as \"the negotiated wire ERA determines them\". All five legacy protocol\n * versions (2024-10-07 … 2025-11-25) share one wire vocabulary and map to the\n * single 2025-era codec — exactly how the single schema set already served\n * all five — and '2026-07-28' maps to the 2026-era codec. A new codec exists\n * only when wire vocabulary actually diverges; intra-era vocabulary is NOT\n * keyed by exact version.\n *\n * Deletions are physical: registry membership is the deletion story. The\n * 2026-era registry has no `tasks/*`, `initialize`, `ping`, `logging/setLevel`,\n * `resources/(un)subscribe` or server→client wire-request entries, so an\n * inbound era-mismatched method falls to −32601 by absence — even when a\n * handler is registered — and an outbound one dies locally with a typed\n * `SdkError` before anything reaches the transport. The 2025-era registry has\n * no `server/discover`/`subscriptions/listen`/MRTR entries, symmetrically.\n *\n * Custom-handler shadowing policy (both directions): a method that belongs to\n * the SPEC-METHOD UNIVERSE — the union of every codec's registry, derived,\n * not hand-curated — is ALWAYS era-gated, so a custom handler registered for\n * a deleted spec method (e.g. `tasks/get`) serves it only on the era that\n * defines it. Methods outside the universe are consumer-owned extension\n * methods: they are era-blind and require explicit schemas, exactly as today.\n *\n * Everything in `wire/` is internal to the bundled, `private: true` core —\n * nothing per-revision is public surface, and nothing here may ever be\n * exported from `core/public`.\n */\nimport type { SdkError } from '../errors/sdkErrors';\nimport { isModernProtocolVersion } from '../shared/protocolEras';\nimport type {\n CallToolResult,\n ClientCapabilities,\n CreateMessageResult,\n CreateMessageResultWithTools,\n Implementation,\n LoggingLevel,\n MessageClassification,\n NotificationMethod,\n NotificationTypeMap,\n RequestMetaEnvelope,\n RequestMethod,\n RequestTypeMap,\n Result,\n ResultTypeMap\n} from '../types/types';\nimport { rev2025Codec } from './rev2025-11-25/codec';\nimport { rev2026Codec } from './rev2026-07-28/codec';\n\n/** Wire eras with distinct vocabulary. */\nexport type WireEra = '2025-11-25' | '2026-07-28';\n\n/**\n * The modern wire revision literal. Internal only — deliberately NOT a public\n * constant (G-D2-4: no public modern-version constant ships before era-aware\n * list semantics exist).\n */\nexport const MODERN_WIRE_REVISION = '2026-07-28';\n\n/**\n * Wire-only material lifted off an inbound message by the protocol layer\n * before dispatch (the V-3 seam): the reserved `_meta` envelope keys and the\n * multi-round-trip driver fields. This is the typed driver-material channel\n * of the codec contract — handlers never see it; the protocol layer surfaces\n * it via `ctx.mcpReq.envelope` / `.inputResponses` / `.requestState`, and the\n * MRTR driver (M4.1) consumes the retry fields from here.\n */\nexport interface LiftedWireMaterial {\n // Partial: the lift surfaces whichever reserved keys the message actually\n // carried — a peer on an adjacent revision may legally send a subset, and\n // envelope requiredness is enforced per request at dispatch time\n // (`checkInboundEnvelope`), not by the lift.\n envelope?: Partial<RequestMetaEnvelope>;\n inputResponses?: Record<string, unknown>;\n requestState?: string;\n}\n\n/**\n * Tri-state validation outcome — the function-only contract for what the\n * schema-getter pair (`hasRequestMethod` ⇒ −32601-by-absence; `…Schema(m)\n * .parse` throw ⇒ −32602) used to encode in two pieces. Preserving the split\n * is the point: collapsing 'absent from this era's registry' into 'invalid'\n * would make the in-band fallback chain (validate → on `not-in-era` fall to\n * validateInputRequest) treat absence as failure and never fall through.\n */\nexport type ValidateOutcome<T> =\n | { readonly ok: true; readonly value: T }\n /**\n * Method is spec vocabulary but absent from THIS era's registry. Callers\n * map to −32601 (inbound) or a typed local SdkError (outbound), or fall\n * through to the in-band validator.\n */\n | { readonly ok: false; readonly reason: 'not-in-era' }\n /**\n * Method is in this era's registry; payload failed the era-exact schema.\n * Callers map to −32602.\n */\n | { readonly ok: false; readonly reason: 'invalid'; readonly message: string };\n\n/** A single self-identifying problem found while validating a per-request `_meta` envelope. */\nexport interface EnvelopeIssue {\n /**\n * The envelope key the problem is about: one of the reserved `_meta`\n * keys, or a dotted path inside one.\n */\n readonly key: string;\n /** A short description of what is wrong with that key (`missing`, or a validation message). */\n readonly problem: string;\n}\n\n/** Material a Client supplies for an era to build its per-request `_meta` envelope from. */\nexport interface OutboundEnvelopeMaterial {\n readonly protocolVersion: string;\n readonly clientInfo: Implementation;\n readonly clientCapabilities: ClientCapabilities;\n readonly logLevel?: LoggingLevel;\n}\n\n/** Result decode outcomes — the raw-first discrimination (V-1) lives in `decodeResult`. */\nexport type DecodedResult =\n | {\n kind: 'complete';\n /** The neutral result value: wire-only material consumed/stripped. */\n result: Result;\n }\n | {\n kind: 'input_required';\n /**\n * Driver-only material (never consumer-visible). The full\n * multi-round-trip driver is M4.1 scope; this seam carries the\n * discriminated payload to it.\n */\n inputRequests: Record<string, unknown>;\n requestState?: string;\n }\n | { kind: 'invalid'; error: SdkError };\n\n/**\n * The per-era wire codec contract (design C §3, adapted to the live funnel\n * layout: the universal wire-only LIFT runs once in the protocol layer for\n * every message — spec, custom, and fallback paths alike — and codecs consume\n * the lifted material rather than re-implementing the strip per era).\n */\nexport interface WireCodec {\n readonly era: WireEra;\n\n /** Registry membership — the deletion story (inbound −32601 by absence; outbound typed local error). */\n hasRequestMethod(method: string): boolean;\n hasNotificationMethod(method: string): boolean;\n hasInputRequestMethod(method: string): boolean;\n\n // ── Function-only validation surface ──────────────────────────────────\n // The validator-agnostic contract: callers never see a Zod schema, only a\n // tri-state outcome. The method-literal overloads carry the typed parse\n // result exactly as the (now-deprecated) *Schema getters did.\n\n /** Era-exact request validation. `not-in-era` ≡ −32601-by-absence; `invalid` ≡ −32602. */\n validateRequest<M extends RequestMethod>(method: M, raw: unknown): ValidateOutcome<RequestTypeMap[M]>;\n validateRequest(method: string, raw: unknown): ValidateOutcome<unknown>;\n\n /** Era-exact result validation (same registry as `validateRequest`). */\n validateResult<M extends RequestMethod>(method: M, raw: unknown): ValidateOutcome<ResultTypeMap[M]>;\n validateResult(method: string, raw: unknown): ValidateOutcome<unknown>;\n\n /** Era-exact notification validation. */\n validateNotification<M extends NotificationMethod>(method: M, raw: unknown): ValidateOutcome<NotificationTypeMap[M]>;\n validateNotification(method: string, raw: unknown): ValidateOutcome<unknown>;\n\n /**\n * In-band (de-JSON-RPC'd) input-request validation — the embedded\n * requests a multi-round-trip `input_required` result may carry. Always\n * `not-in-era` on the 2025 era (elicitation/sampling/roots are wire\n * request methods there). Does NOT grant registry membership.\n */\n validateInputRequest<M extends RequestMethod>(method: M, raw: unknown): ValidateOutcome<RequestTypeMap[M]>;\n validateInputRequest(method: string, raw: unknown): ValidateOutcome<unknown>;\n\n /** In-band bare-response validation answering an embedded input request. */\n validateInputResponse<M extends RequestMethod>(method: M, raw: unknown): ValidateOutcome<ResultTypeMap[M]>;\n validateInputResponse(method: string, raw: unknown): ValidateOutcome<unknown>;\n\n /**\n * Param-conditional `sampling/createMessage` result validation — the one\n * spec result whose schema depends on REQUEST params (tools vs no tools).\n * The 2025 era owns the with-tools/plain frozen schemas; the 2026 era\n * returns `not-in-era` (sampling is in-band there — callers fall through\n * to `validateInputResponse`).\n */\n samplingResultVariant(hasTools: true, raw: unknown): ValidateOutcome<CreateMessageResultWithTools>;\n samplingResultVariant(hasTools: false, raw: unknown): ValidateOutcome<CreateMessageResult>;\n samplingResultVariant(hasTools: boolean, raw: unknown): ValidateOutcome<CreateMessageResult | CreateMessageResultWithTools>;\n\n /**\n * Outbound per-request `_meta` envelope encode. Returns the keyed object\n * to merge into `params._meta` on this era, or `undefined` when this era\n * carries no per-request envelope (the 2025 era — legacy wire stays\n * byte-identical).\n */\n outboundEnvelope(material: OutboundEnvelopeMaterial): Readonly<Record<string, unknown>> | undefined;\n\n /**\n * Structured envelope validation: maps a `_meta` object to\n * self-identifying issues. The 2025 era never requires an envelope and\n * always returns `[]`; the 2026 era owns the required-key pre-pass plus\n * the wire-exact `RequestMetaEnvelopeSchema` parse.\n */\n validateEnvelopeMeta(meta: Readonly<Record<string, unknown>>): EnvelopeIssue[];\n\n /**\n * Per-registration `tools/call` result projection. Two independent\n * decisions, both owned here so server-side code never re-derives them:\n *\n * - SEP-2106 §4.3 TextContent auto-append (EVERY era, value-shape-based):\n * when `structuredContent` is a non-object value (array/primitive/\n * `null`) and the handler authored no `type:'text'` block, append\n * `{type:'text', text: JSON.stringify(value)}` so consumers that read\n * only `content` still receive a rendering. The author opts out by\n * returning any `text` block themselves.\n *\n * - `{result:…}` wrap (2025 era only): wrap as `{result:<value>}` when the\n * value is non-object (the 2025 wire shape requires `structuredContent`\n * to be an object — a schema-less tool returning `[1,2,3]` would\n * otherwise ship wire-illegal bytes) OR when the tool's ADVERTISED\n * `outputSchema` has a non-object root (so the result matches the\n * `encodeResult('tools/list')` projection of the same tool). Identity on\n * the 2026 era — the wire shape carries the natural value directly.\n */\n projectCallToolResult(result: CallToolResult, advertisedOutputSchema: Readonly<Record<string, unknown>> | undefined): CallToolResult;\n\n /**\n * Step 1 of result decoding: RAW `resultType` handling BEFORE any schema\n * validation (V-1's structural home). Era postures (Q1-SD3):\n * - 2026 era: required discriminator — absent ⇒ typed error naming the\n * spec violation; `input_required` ⇒ driver payload; unknown ⇒ invalid,\n * no retry; `complete` ⇒ consume + lift.\n * - 2025 era: `resultType` is foreign vocabulary ⇒ strip-on-lift.\n */\n decodeResult(method: string, raw: unknown): DecodedResult;\n\n /**\n * Outbound result mapping (the stamp seam). The 2025-era codec is the\n * identity — it has NO stamp code path (the never-stamp guarantee). The\n * 2026-era codec strictly enforces the 2026 wire shape for the known\n * deleted-field set (`execution.taskSupport`, `capabilities.tasks` —\n * Q1-SD3 iii), stamps `resultType`, and fills the required\n * `ttlMs`/`cacheScope` fields on cacheable results.\n */\n encodeResult(method: string, result: Result): Result;\n\n /**\n * Outbound error-code mapping (the error half of the stamp seam). A\n * handler-thrown `ProtocolError`'s numeric code passes through here on\n * its way to the JSON-RPC error response, so per-era wire-code selection\n * lives in the codec rather than in handler/funnel code. The current\n * mapping is identical on both eras (the `-32002` resource-not-found\n * domain code maps to `-32602` Invalid Params on the wire — the\n * 2026-07-28 spec MUST, and what the deployed v1.x SDK already emits on\n * earlier revisions); the seam is the structural home for any future\n * per-era divergence. Unknown codes pass through unchanged.\n */\n encodeErrorCode(code: number): number;\n\n /**\n * @deprecated Use {@link validateEnvelopeMeta}. Inbound envelope\n * enforcement for era-classified traffic: validates the lifted envelope\n * material of a request. Returns an error message when the era requires\n * an envelope and it is missing/invalid (→ −32602 at the dispatch\n * layer); `undefined` when acceptable. The 2025 era never requires an\n * envelope.\n */\n checkInboundEnvelope(material: LiftedWireMaterial): string | undefined;\n}\n\n/**\n * Era resolution, many-to-one (Q1-SD1): every modern-era revision\n * (`>= 2026-07-28`) → the 2026-era codec; every legacy revision (the five\n * `SUPPORTED_PROTOCOL_VERSIONS`) and `undefined`/unknown → the 2025-era\n * codec (the DV-13 default posture — hand-constructed instances and\n * unclassified traffic are legacy-era). This is the same era predicate the\n * rest of the SDK uses ({@link isModernProtocolVersion}); a pinned modern\n * revision other than the literal '2026-07-28' must still resolve modern.\n */\nexport function codecForVersion(version: string | undefined): WireCodec {\n return version !== undefined && isModernProtocolVersion(version) ? rev2026Codec : rev2025Codec;\n}\n\n/**\n * The wire era an edge classification names (Q2 — produced at the\n * transport/entry edge; this layer only CONSUMES it). The dispatch funnel no\n * longer resolves a codec FROM the classification: era is instance state, and\n * a classified inbound message is VALIDATED against the instance era — a\n * mismatch is an entry/routing error, never a per-message era switch. The\n * exact `revision` wins over the coarse era flag when both are present.\n */\nexport function classifiedWireEra(classification: MessageClassification): WireEra {\n if (classification.revision !== undefined) return codecForVersion(classification.revision).era;\n return classification.era === 'modern' ? rev2026Codec.era : rev2025Codec.era;\n}\n\n/**\n * The derived spec-method universe: the union of every codec registry. A\n * method in this set is era-gated at dispatch and send time; a method outside\n * it is a consumer-owned extension method (era-blind, schema-explicit).\n * Derived from the registries — never hand-curated (the LEGACY_ONLY_METHODS\n * table class is exactly what registry membership replaces).\n */\nexport function isSpecRequestMethod(method: string): boolean {\n return ALL_CODECS.some(codec => codec.hasRequestMethod(method));\n}\n\nexport function isSpecNotificationMethod(method: string): boolean {\n return ALL_CODECS.some(codec => codec.hasNotificationMethod(method));\n}\n\nconst ALL_CODECS: readonly WireCodec[] = [rev2025Codec, rev2026Codec];\n","/**\n * Per-request `_meta` envelope claim helpers (protocol revision 2026-07-28).\n *\n * Pure, value-returning helpers used by the inbound HTTP classifier\n * (`classifyInboundRequest`): claim detection and envelope validation with\n * self-identifying issues. The envelope schema itself stays the wire layer's\n * single source of truth (`RequestMetaEnvelopeSchema`); this module only maps\n * its outcomes into the shapes the validation ladder emits.\n *\n * Claim detection is deliberately narrow: a message claims the 2026-07-28\n * envelope mechanism if and only if the reserved protocol-version `_meta` key\n * is present in `params._meta`. Other reserved keys (client info, client\n * capabilities, log level), a bare `progressToken`, or unrelated keys under\n * the `io.modelcontextprotocol/` prefix do NOT constitute a claim on their\n * own — but once the claim key is present, a malformed envelope is a\n * validation error, never a silent fall back to legacy handling.\n *\n * The wire-exact envelope schema, the required-key set, and the per-key issue\n * mapping live in the wire layer (the 2026-era codec's `validateEnvelopeMeta`).\n * This module never reaches into a per-revision wire module directly.\n */\nimport { PROTOCOL_VERSION_META_KEY } from '../types/constants';\nimport type { EnvelopeIssue } from '../wire/codec';\nimport { codecForVersion, MODERN_WIRE_REVISION } from '../wire/codec';\n\n// Re-export from the wire layer (the canonical home): the issue shape is part\n// of the function-only WireCodec contract. Imported above for the local return\n// type, so the bare re-export form is used.\n// eslint-disable-next-line unicorn/prefer-export-from\nexport type { EnvelopeIssue };\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\n/** The `_meta` object of a message's params, when present. */\nexport function requestMetaOf(params: unknown): Record<string, unknown> | undefined {\n if (!isPlainObject(params)) return undefined;\n const meta = params['_meta'];\n return isPlainObject(meta) ? meta : undefined;\n}\n\n/**\n * Whether a message's params carry the per-request envelope claim: the\n * reserved protocol-version `_meta` key is present (regardless of whether the\n * rest of the envelope is valid — validation is a separate, later step).\n */\nexport function hasEnvelopeClaim(params: unknown): boolean {\n const meta = requestMetaOf(params);\n return meta !== undefined && PROTOCOL_VERSION_META_KEY in meta;\n}\n\n/**\n * The protocol version named by a message's envelope claim, when the claim is\n * present and carries a string value. A present claim with a non-string value\n * still counts as a claim ({@linkcode hasEnvelopeClaim}); it surfaces as a\n * validation issue instead of a version.\n */\nexport function envelopeClaimVersion(params: unknown): string | undefined {\n const meta = requestMetaOf(params);\n const value = meta?.[PROTOCOL_VERSION_META_KEY];\n return typeof value === 'string' ? value : undefined;\n}\n\n/**\n * Validates a request's `_meta` object as a 2026-07-28 per-request envelope\n * and reports problems as self-identifying issues (which key, what problem).\n *\n * Returns an empty array when the envelope is valid. Missing required keys are\n * reported first (as `problem: 'missing'`), then schema violations inside\n * present keys, in a stable order.\n */\nexport function validateEnvelopeMeta(meta: Record<string, unknown>): EnvelopeIssue[] {\n // Delegate to the era codec: the required-key pre-pass and the wire-exact\n // `RequestMetaEnvelopeSchema` parse live in `wire/rev2026-07-28/` — this\n // module never reaches into per-revision wire vocabulary.\n return codecForVersion(MODERN_WIRE_REVISION).validateEnvelopeMeta(meta);\n}\n","import * as z from 'zod/v4';\n\nimport { JSONRPC_VERSION, RELATED_TASK_META_KEY, SUBSCRIPTION_ID_META_KEY } from './constants';\nimport type { JSONArray, JSONObject, JSONValue } from './types';\n\nexport const JSONValueSchema: z.ZodType<JSONValue, JSONValue> = z.lazy(() =>\n z.union([z.string(), z.number(), z.boolean(), z.null(), z.record(z.string(), JSONValueSchema), z.array(JSONValueSchema)])\n);\nexport const JSONObjectSchema: z.ZodType<JSONObject, JSONObject> = z.record(z.string(), JSONValueSchema);\nexport const JSONArraySchema: z.ZodType<JSONArray, JSONArray> = z.array(JSONValueSchema);\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/**\n * An opaque token used to represent a cursor for pagination.\n */\nexport const CursorSchema = z.string();\n\n/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */\nexport const TaskMetadataSchema = z.object({\n ttl: z.number().optional()\n});\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 *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const RelatedTaskMetadataSchema = z.object({\n taskId: z.string()\n});\n\nexport const 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/**\n * Common params for any request.\n */\nexport const 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/**\n * Common params for any task-augmented request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\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\nexport const RequestSchema = z.object({\n method: z.string(),\n params: BaseRequestParamsSchema.loose().optional()\n});\n\nexport const 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});\n\nexport const NotificationSchema = z.object({\n method: z.string(),\n params: NotificationsParamsSchema.loose().optional()\n});\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 // `resultType` is wire-only vocabulary (protocol revision 2026-07-28) and\n // is deliberately NOT modeled here: the neutral result schemas carry no\n // slot for it. It exists only inside the 2026-era wire codec, which\n // consumes it on decode and stamps it on encode. (Q1 increment 2 - the\n // former optional member here was the masking surface that let modern\n // vocabulary leak through every legacy-leg parse.)\n});\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/**\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();\n\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();\n\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/**\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\nexport const JSONRPCMessageSchema = z.union([\n JSONRPCRequestSchema,\n JSONRPCNotificationSchema,\n JSONRPCResultResponseSchema,\n JSONRPCErrorResponseSchema\n]);\n\nexport const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);\n\n/* Empty result */\n/**\n * A response that indicates success but carries no data.\n */\nexport const EmptyResultSchema = ResultSchema.strict();\n\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 {@linkcode InitializeRequest | initialize} request.\n */\nexport const CancelledNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/cancelled'),\n params: CancelledNotificationParamsSchema\n});\n\n/* Base Metadata */\n/**\n * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | 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/**\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/**\n * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | 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\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 /**\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});\n\nconst FormElicitationCapabilitySchema = z.intersection(\n z.object({\n applyDefaults: z.boolean().optional()\n }),\n JSONObjectSchema\n);\n\nconst ElicitationCapabilitySchema = z.preprocess(\n value => {\n if (value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value as Record<string, unknown>).length === 0) {\n return { form: {} };\n }\n return value;\n },\n z.intersection(\n z.object({\n form: FormElicitationCapabilitySchema.optional(),\n url: JSONObjectSchema.optional()\n }),\n JSONObjectSchema.optional()\n )\n);\n\n/**\n * Task capabilities for clients, indicating which request types support task creation.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const ClientTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the client supports listing tasks.\n */\n list: JSONObjectSchema.optional(),\n /**\n * Present if the client supports cancelling tasks.\n */\n cancel: JSONObjectSchema.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: JSONObjectSchema.optional()\n })\n .optional(),\n /**\n * Task support for elicitation requests.\n */\n elicitation: z\n .looseObject({\n create: JSONObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\n\n/**\n * Task capabilities for servers, indicating which request types support task creation.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const ServerTasksCapabilitySchema = z.looseObject({\n /**\n * Present if the server supports listing tasks.\n */\n list: JSONObjectSchema.optional(),\n /**\n * Present if the server supports cancelling tasks.\n */\n cancel: JSONObjectSchema.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: JSONObjectSchema.optional()\n })\n .optional()\n })\n .optional()\n});\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(), JSONObjectSchema).optional(),\n /**\n * Present if the client supports sampling from an LLM.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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: JSONObjectSchema.optional(),\n /**\n * Present if the client supports tool use via `tools` and `toolChoice` parameters.\n */\n tools: JSONObjectSchema.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 * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\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 * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; parsed for interoperability only — servers built on this SDK never advertise it.\n */\n tasks: ClientTasksCapabilitySchema.optional(),\n /**\n * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), JSONObjectSchema).optional()\n});\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});\n\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(), JSONObjectSchema).optional(),\n /**\n * Present if the server supports sending log messages to the client.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\n logging: JSONObjectSchema.optional(),\n /**\n * Present if the server supports sending completions to the client.\n */\n completions: JSONObjectSchema.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 /**\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 * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; parsed for interoperability only — servers built on this SDK never advertise it.\n */\n tasks: ServerTasksCapabilitySchema.optional(),\n /**\n * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).\n */\n extensions: z.record(z.string(), JSONObjectSchema).optional()\n});\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/**\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});\n\n/* Discovery */\n/**\n * A request from the client asking the server to advertise its supported protocol\n * versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers\n * MUST implement `server/discover`. Clients MAY call it but are not required to —\n * version negotiation can also happen inline via the per-request `_meta` envelope.\n */\nexport const DiscoverRequestSchema = RequestSchema.extend({\n method: z.literal('server/discover'),\n params: BaseRequestParamsSchema.optional()\n});\n\n/**\n * The result returned by the server for a `server/discover` request.\n */\nexport const DiscoverResultSchema = ResultSchema.extend({\n /**\n * MCP protocol versions this server supports. The client should choose a\n * version from this list for use in subsequent requests.\n */\n supportedVersions: z.array(z.string()),\n /**\n * The capabilities of the server.\n */\n capabilities: ServerCapabilitiesSchema,\n /**\n * Information about the server software implementation.\n */\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/* 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\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});\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});\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\n/* Pagination */\nexport const PaginatedRequestSchema = RequestSchema.extend({\n params: PaginatedRequestParamsSchema.optional()\n});\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/* 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});\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/**\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(\n 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 } catch {\n return false;\n }\n },\n { message: 'Invalid Base64 string' }\n);\n\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/**\n * The sender or recipient of messages and data in a conversation.\n */\nexport const RoleSchema = z.enum(['user', 'assistant']);\n\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 /**\n * Importance hint for the resource, from 0 (least) to 1 (most).\n */\n priority: z.number().min(0).max(1).optional(),\n\n /**\n * ISO 8601 timestamp for the most recent modification.\n */\n lastModified: z.iso.datetime({ offset: true }).optional()\n});\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 /**\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 /**\n * The MIME type of this resource, if known.\n */\n mimeType: z.optional(z.string()),\n\n /**\n * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.\n *\n * This can be used by Hosts to display file sizes and estimate context window usage.\n */\n size: z.optional(z.number()),\n\n /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n\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/**\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 /**\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 /**\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 /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n\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/**\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/**\n * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client.\n */\nexport const ListResourcesResultSchema = PaginatedResultSchema.extend({\n resources: z.array(ResourceSchema)\n});\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/**\n * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client.\n */\nexport const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({\n resourceTemplates: z.array(ResourceTemplateSchema)\n});\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/**\n * Parameters for a {@linkcode ReadResourceRequest | resources/read} request.\n */\nexport const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;\n\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/**\n * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client.\n */\nexport const ReadResourceResultSchema = ResultSchema.extend({\n contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema]))\n});\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});\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});\n\nexport const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;\n/**\n * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request.\n */\nexport const UnsubscribeRequestSchema = RequestSchema.extend({\n method: z.literal('resources/unsubscribe'),\n params: UnsubscribeRequestParamsSchema\n});\n\n/* Subscriptions (protocol revision 2026-07-28) */\n/**\n * The set of notification types a client opts in to on a `subscriptions/listen`\n * request. Each type is opt-in; the server MUST NOT send a notification type\n * the client has not explicitly requested here.\n */\nexport const SubscriptionFilterSchema = z.object({\n /**\n * If true, receive `notifications/tools/list_changed`.\n */\n toolsListChanged: z.boolean().optional(),\n /**\n * If true, receive `notifications/prompts/list_changed`.\n */\n promptsListChanged: z.boolean().optional(),\n /**\n * If true, receive `notifications/resources/list_changed`.\n */\n resourcesListChanged: z.boolean().optional(),\n /**\n * Subscribe to `notifications/resources/updated` for these resource URIs.\n * Replaces the former `resources/subscribe` RPC on the 2026-07-28 revision.\n */\n resourceSubscriptions: z.array(z.string()).optional()\n});\n\nexport const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({\n /**\n * The notifications the client opts in to on this stream. The server MUST\n * NOT send notification types the client has not explicitly requested.\n */\n notifications: SubscriptionFilterSchema\n});\n\n/**\n * Sent from the client to open a long-lived channel for receiving notifications\n * outside the context of a specific request (protocol revision 2026-07-28).\n * Replaces the previous HTTP GET endpoint and `resources/subscribe`.\n */\nexport const SubscriptionsListenRequestSchema = RequestSchema.extend({\n method: z.literal('subscriptions/listen'),\n params: SubscriptionsListenRequestParamsSchema\n});\n\nexport const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The subset of requested notification types the server agreed to honor.\n */\n notifications: SubscriptionFilterSchema\n});\n\n/**\n * Sent by the server as the first message on a `subscriptions/listen` stream\n * to acknowledge that the subscription has been established and report which\n * notification types it agreed to honor (protocol revision 2026-07-28).\n */\nexport const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/subscriptions/acknowledged'),\n params: SubscriptionsAcknowledgedNotificationParamsSchema\n});\n\n/**\n * `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's\n * JSON-RPC ID under the canonical subscription-id key (mirroring the same key\n * on every notification delivered on the stream).\n */\nexport const SubscriptionsListenResultMetaSchema = z.looseObject({\n [SUBSCRIPTION_ID_META_KEY]: RequestIdSchema\n});\n\n/**\n * The response to a `subscriptions/listen` request, signalling that the\n * subscription has ended gracefully (for example, during server shutdown).\n * Because the listen stream is long-lived, this result is sent only when the\n * server tears the subscription down; an abrupt transport close carries no\n * response. The result body is otherwise empty.\n */\nexport const SubscriptionsListenResultSchema = ResultSchema.extend({\n _meta: SubscriptionsListenResultMetaSchema\n});\n\n/**\n * Parameters for a {@linkcode ResourceUpdatedNotification | 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/**\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 {@linkcode SubscribeRequest | resources/subscribe} request.\n */\nexport const ResourceUpdatedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/resources/updated'),\n params: ResourceUpdatedNotificationParamsSchema\n});\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/**\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/**\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/**\n * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client.\n */\nexport const ListPromptsResultSchema = PaginatedResultSchema.extend({\n prompts: z.array(PromptSchema)\n});\n\n/**\n * Parameters for a {@linkcode GetPromptRequest | 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/**\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 /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n\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/**\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 /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n\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/**\n * Audio content 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 /**\n * Optional annotations for the client.\n */\n annotations: AnnotationsSchema.optional(),\n\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/**\n * A tool call request from an assistant (LLM).\n * Represents the assistant's request to use a tool.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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/**\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/**\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 {@linkcode ListResourcesRequest | resources/list} requests.\n */\nexport const ResourceLinkSchema = ResourceSchema.extend({\n type: z.literal('resource_link')\n});\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/**\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/**\n * The server's response to a {@linkcode GetPromptRequest | 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/**\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\n/* Tools */\n/**\n * Additional properties describing a `Tool` to clients.\n *\n * NOTE: all properties in {@linkcode 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 /**\n * If `true`, the tool does not modify its environment.\n *\n * Default: `false`\n */\n readOnlyHint: z.boolean().optional(),\n\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 /**\n * If `true`, calling the tool repeatedly with the same arguments\n * will have no additional effect on its environment.\n *\n * (This property is meaningful only when `readOnlyHint == false`)\n *\n * Default: `false`\n */\n idempotentHint: z.boolean().optional(),\n\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/**\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/**\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(), JSONValueSchema).optional(),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown()),\n /**\n * An optional JSON Schema 2020-12 document describing the structure of the tool's output\n * returned in the `structuredContent` field of a `CallToolResult`.\n *\n * SEP-2106: any JSON Schema root is permitted (e.g. `type:'array'`, `oneOf`, `$ref`).\n * The 2025-11-25 wire parse retains the `type:'object'` constraint via the frozen schema in\n * `wire/rev2025-11-25/schemas.ts`; this neutral/public schema widens.\n */\n outputSchema: z.looseObject({ $schema: z.string().optional() }).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 /**\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/**\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/**\n * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client.\n */\nexport const ListToolsResultSchema = PaginatedResultSchema.extend({\n tools: z.array(ToolSchema)\n});\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 * Required on the wire per the specification (it may be an empty array).\n */\n content: z.array(ContentBlockSchema),\n\n /**\n * Structured tool output.\n *\n * If the `Tool` defines an `outputSchema`, this field MUST be present in the result and\n * contain a JSON value that matches the schema.\n *\n * SEP-2106: any JSON value is permitted (arrays, primitives, `null`). Narrow before property\n * access. The 2025-11-25 wire parse retains the object-only constraint via the frozen schema\n * in `wire/rev2025-11-25/schemas.ts`; this neutral/public schema widens.\n */\n structuredContent: z.unknown().optional(),\n\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/**\n * {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07.\n */\nexport const CompatibilityCallToolResultSchema = CallToolResultSchema.or(\n ResultSchema.extend({\n toolResult: z.unknown()\n })\n);\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/**\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/**\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/**\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\n/* Logging */\n/**\n * The severity of a log message.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\nexport const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']);\n\n/**\n * Parameters for a `logging/setLevel` request.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\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 *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\nexport const SetLevelRequestSchema = RequestSchema.extend({\n method: z.literal('logging/setLevel'),\n params: SetLevelRequestParamsSchema\n});\n\n/**\n * Parameters for a `notifications/message` notification.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\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 *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to stderr logging\n * (STDIO servers) or OpenTelemetry.\n */\nexport const LoggingMessageNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/message'),\n params: LoggingMessageNotificationParamsSchema\n});\n\n/* Sampling */\n/**\n * Hints to use for model selection.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const ModelHintSchema = z.object({\n /**\n * A hint for a model name.\n */\n name: z.string().optional()\n});\n\n/**\n * The server's preferences for model selection, requested of the client during sampling.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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/**\n * Controls tool usage behavior in sampling requests.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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/**\n * The result of a tool execution, provided by the user (server).\n * Represents the outcome of invoking a tool requested via `ToolUseContent`.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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),\n /**\n * SEP-2106: any JSON value is permitted. The 2025-11-25 wire parse retains the object-only\n * constraint via the frozen schema in `wire/rev2025-11-25/schemas.ts`.\n */\n structuredContent: z.unknown().optional(),\n isError: z.boolean().optional(),\n\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/**\n * Basic content types for sampling responses (without tool use).\n * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]);\n\n/**\n * Content block types allowed in sampling messages.\n * This includes text, image, audio, tool use requests, and tool results.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [\n TextContentSchema,\n ImageContentSchema,\n AudioContentSchema,\n ToolUseContentSchema,\n ToolResultContentSchema\n]);\n\n/**\n * Describes a message issued to or received from an LLM API.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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/**\n * Parameters for a `sampling/createMessage` request.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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\"`. The values `\"thisServer\"` and `\"allServers\"` are deprecated (SEP-2596): servers SHOULD\n * omit this field or use `\"none\"`, and SHOULD only use the deprecated values if the client declares\n * `ClientCapabilities`.`sampling.context`.\n *\n * @deprecated The `\"thisServer\"` and `\"allServers\"` values are deprecated as of protocol version 2025-11-25\n * (SEP-2596) and will be removed no later than the Sampling feature itself (SEP-2577). Omit this field or use `\"none\"`.\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: JSONObjectSchema.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 *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\n */\nexport const CreateMessageRequestSchema = RequestSchema.extend({\n method: z.literal('sampling/createMessage'),\n params: CreateMessageRequestParamsSchema\n});\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 *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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/**\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 *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to calling LLM\n * provider APIs directly.\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\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/**\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/**\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/**\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/**\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(\n z.object({\n const: z.string(),\n title: z.string()\n })\n ),\n default: z.string().optional()\n});\n\n/**\n * Use {@linkcode 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\n// Combined single selection enumeration\nexport const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);\n\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/**\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(\n z.object({\n const: z.string(),\n title: z.string()\n })\n )\n }),\n default: z.array(z.string()).optional()\n});\n\n/**\n * Combined schema for multiple-selection enumeration\n */\nexport const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);\n\n/**\n * Primitive schema definition for enum fields.\n */\nexport const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);\n\n/**\n * Union of all primitive schema definitions.\n */\nexport const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);\n\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\n .object({\n type: z.literal('object'),\n properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema),\n required: z.array(z.string()).optional()\n })\n .catchall(z.unknown())\n});\n\n/**\n * Parameters for an {@linkcode ElicitRequest | 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 * @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the\n * outcome of an out-of-band interaction by retrying the original request; no\n * server-initiated completion signal exists in the 2026-07-28 revision. Kept here\n * for the 2025-era URL-mode flow only.\n */\n elicitationId: z.string(),\n /**\n * The URL that the user should navigate to.\n */\n url: z.string().url()\n});\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/**\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/**\n * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification.\n *\n * @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome\n * of an out-of-band interaction by retrying the original request; no server-initiated\n * completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow\n * only. The 2026-07-28 wire codec excludes this notification.\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({\n /**\n * The ID of the elicitation that completed.\n *\n * @deprecated See {@linkcode ElicitationCompleteNotificationParamsSchema}.\n */\n elicitationId: z.string()\n});\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 * @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome\n * of an out-of-band interaction by retrying the original request; no server-initiated\n * completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow\n * only. The 2026-07-28 wire codec excludes this notification.\n * @category notifications/elicitation/complete\n */\nexport const ElicitationCompleteNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/elicitation/complete'),\n params: ElicitationCompleteNotificationParamsSchema\n});\n\n/**\n * The client's response to an {@linkcode ElicitRequest | 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 declined 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(\n val => (val === null ? undefined : val),\n z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional()\n )\n});\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/**\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/**\n * Parameters for a {@linkcode CompleteRequest | 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});\n\n/**\n * The server's response to a {@linkcode CompleteRequest | 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\n/* Roots */\n/**\n * Represents a root directory or file that the server can operate on.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\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 /**\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/**\n * Sent from the server to request a list of root URIs from the client.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\n */\nexport const ListRootsRequestSchema = RequestSchema.extend({\n method: z.literal('roots/list'),\n params: BaseRequestParamsSchema.optional()\n});\n\n/**\n * The client's response to a `roots/list` request from the server.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\n */\nexport const ListRootsResultSchema = ResultSchema.extend({\n roots: z.array(RootSchema)\n});\n\n/**\n * A notification from the client to the server, informing it that the list of roots has changed.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains\n * in the specification for at least twelve months. Migrate to passing paths via\n * tool parameters, resource URIs, or configuration.\n */\nexport const RootsListChangedNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/roots/list_changed'),\n params: NotificationsParamsSchema.optional()\n});\n\n/* ───────────────────────────────────────────────────────────────────────────\n * Tasks (2025-11-25 wire vocabulary, DEPRECATED)\n *\n * The task message surface defined by the 2025-11-25 protocol revision. These\n * schemas are kept in the neutral layer so the public Task* types stay\n * nameable without a cross-layer import into wire/rev*; the wire-parse\n * contract for them is the FROZEN copy in wire/rev2025-11-25/schemas.ts.\n *\n * They appear in NO role aggregate below and no API signature — nameable-only\n * vocabulary for interop with task-capable 2025 peers (#2248). Removable at\n * the major version that drops 2025-era support.\n * ─────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Task creation parameters, used to ask that the server create a task to represent a request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const TaskCreationParamsSchema = z.looseObject({\n /**\n * Requested duration in milliseconds to retain task from creation.\n */\n ttl: z.number().optional(),\n\n /**\n * Time in milliseconds to wait between task status requests.\n */\n pollInterval: z.number().optional()\n});\n\n/**\n * The status of a task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']);\n\n/**\n * A pollable state object associated with a request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\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/**\n * Result returned when a task is created, containing the task data wrapped in a `task` field.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const CreateTaskResultSchema = ResultSchema.extend({\n task: TaskSchema\n});\n\n/**\n * Parameters for task status notification.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);\n\n/**\n * A notification sent when a task's status changes.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const TaskStatusNotificationSchema = NotificationSchema.extend({\n method: z.literal('notifications/tasks/status'),\n params: TaskStatusNotificationParamsSchema\n});\n\n/**\n * A request to get the state of a specific task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const GetTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/get'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n\n/**\n * The response to a {@linkcode GetTaskRequest | tasks/get} request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const GetTaskResultSchema = ResultSchema.merge(TaskSchema);\n\n/**\n * A request to get the result of a specific task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const GetTaskPayloadRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/result'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\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 {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure.\n *\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const GetTaskPayloadResultSchema = ResultSchema.loose();\n\n/**\n * A request to list tasks.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const ListTasksRequestSchema = PaginatedRequestSchema.extend({\n method: z.literal('tasks/list')\n});\n\n/**\n * The response to a {@linkcode ListTasksRequest | tasks/list} request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const ListTasksResultSchema = PaginatedResultSchema.extend({\n tasks: z.array(TaskSchema)\n});\n\n/**\n * A request to cancel a specific task.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const CancelTaskRequestSchema = RequestSchema.extend({\n method: z.literal('tasks/cancel'),\n params: BaseRequestParamsSchema.extend({\n taskId: z.string()\n })\n});\n\n/**\n * The response to a {@linkcode CancelTaskRequest | tasks/cancel} request.\n *\n * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only.\n */\nexport const CancelTaskResultSchema = ResultSchema.merge(TaskSchema);\n\n/* Client messages */\n// NOTE (Q1 increment 2): the role unions below are the NEUTRAL message sets.\n// The 2025-era task vocabulary (tasks/* methods, task results, the task\n// status notification) is 2025-only WIRE vocabulary; the deprecated Task*\n// schemas above are nameable-only and appear in NO role aggregate and no API\n// signature. The era's full wire role unions live in\n// `wire/rev2025-11-25/schemas.ts`.\nexport const ClientRequestSchema = z.union([\n PingRequestSchema,\n InitializeRequestSchema,\n DiscoverRequestSchema,\n CompleteRequestSchema,\n SetLevelRequestSchema,\n GetPromptRequestSchema,\n ListPromptsRequestSchema,\n ListResourcesRequestSchema,\n ListResourceTemplatesRequestSchema,\n ReadResourceRequestSchema,\n SubscribeRequestSchema,\n UnsubscribeRequestSchema,\n SubscriptionsListenRequestSchema,\n CallToolRequestSchema,\n ListToolsRequestSchema\n]);\n\nexport const ClientNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n InitializedNotificationSchema,\n RootsListChangedNotificationSchema\n]);\n\nexport const ClientResultSchema = z.union([\n EmptyResultSchema,\n CreateMessageResultSchema,\n CreateMessageResultWithToolsSchema,\n ElicitResultSchema,\n ListRootsResultSchema\n]);\n\n/* Server messages */\nexport const ServerRequestSchema = z.union([PingRequestSchema, CreateMessageRequestSchema, ElicitRequestSchema, ListRootsRequestSchema]);\n\nexport const ServerNotificationSchema = z.union([\n CancelledNotificationSchema,\n ProgressNotificationSchema,\n LoggingMessageNotificationSchema,\n ResourceUpdatedNotificationSchema,\n ResourceListChangedNotificationSchema,\n ToolListChangedNotificationSchema,\n PromptListChangedNotificationSchema,\n SubscriptionsAcknowledgedNotificationSchema,\n ElicitationCompleteNotificationSchema\n]);\n\nexport const ServerResultSchema = z.union([\n EmptyResultSchema,\n InitializeResultSchema,\n DiscoverResultSchema,\n CompleteResultSchema,\n GetPromptResultSchema,\n ListPromptsResultSchema,\n ListResourcesResultSchema,\n ListResourceTemplatesResultSchema,\n ReadResourceResultSchema,\n CallToolResultSchema,\n ListToolsResultSchema,\n SubscriptionsListenResultSchema\n]);\n","import {\n CallToolResultSchema,\n InitializedNotificationSchema,\n InitializeRequestSchema,\n JSONRPCErrorResponseSchema,\n JSONRPCMessageSchema,\n JSONRPCNotificationSchema,\n JSONRPCRequestSchema,\n JSONRPCResponseSchema,\n JSONRPCResultResponseSchema,\n TaskAugmentedRequestParamsSchema\n} from './schemas';\nimport type {\n CallToolResult,\n CompleteRequest,\n CompleteRequestPrompt,\n CompleteRequestResourceTemplate,\n InitializedNotification,\n InitializeRequest,\n InputRequiredResult,\n JSONRPCErrorResponse,\n JSONRPCMessage,\n JSONRPCNotification,\n JSONRPCRequest,\n JSONRPCResponse,\n JSONRPCResultResponse,\n TaskAugmentedRequestParams\n} from './types';\n\n/**\n * Validates and parses an unknown value as a JSON-RPC message.\n *\n * Use this to validate incoming messages in custom transport implementations.\n * Throws if the value does not conform to the JSON-RPC message schema.\n *\n * @param value - The value to validate (typically a parsed JSON object).\n * @returns The validated {@linkcode JSONRPCMessage}.\n * @throws If validation fails.\n */\nexport function parseJSONRPCMessage(value: unknown): JSONRPCMessage {\n return JSONRPCMessageSchema.parse(value);\n}\n\nexport const isJSONRPCRequest = (value: unknown): value is JSONRPCRequest => JSONRPCRequestSchema.safeParse(value).success;\n\nexport const isJSONRPCNotification = (value: unknown): value is JSONRPCNotification => JSONRPCNotificationSchema.safeParse(value).success;\n\n/**\n * Checks if a value is a valid {@linkcode JSONRPCResultResponse}.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise.\n */\nexport const isJSONRPCResultResponse = (value: unknown): value is JSONRPCResultResponse =>\n JSONRPCResultResponseSchema.safeParse(value).success;\n\n/**\n * Checks if a value is a valid {@linkcode JSONRPCErrorResponse}.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise.\n */\nexport const isJSONRPCErrorResponse = (value: unknown): value is JSONRPCErrorResponse =>\n JSONRPCErrorResponseSchema.safeParse(value).success;\n\n/**\n * Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response).\n * @param value - The value to check.\n *\n * @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise.\n */\nexport const isJSONRPCResponse = (value: unknown): value is JSONRPCResponse => JSONRPCResponseSchema.safeParse(value).success;\n\n/**\n * Checks if a value is a valid {@linkcode CallToolResult}.\n *\n * This is a consumer-side VALUE check against the neutral model, not a wire\n * validator: a raw wire object that additionally carries wire-only members\n * (e.g. `resultType`) still passes through the loose index signature. Use a\n * transport-level parse to validate raw wire traffic.\n *\n * @param value - The value to check.\n *\n * @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise.\n */\nexport const isCallToolResult = (value: unknown): value is CallToolResult => {\n if (typeof value !== 'object' || value === null || !('content' in value)) return false;\n return CallToolResultSchema.safeParse(value).success;\n};\n\n/**\n * Checks whether a value is an input-required result (protocol revision\n * 2026-07-28): the multi-round-trip return shape discriminated by\n * `resultType: 'input_required'`.\n *\n * This is a discriminator check, not a full validator — the at-least-one rule\n * (`inputRequests` or `requestState`) is enforced by the `inputRequired()`\n * builder and re-checked by the server seam for hand-built values.\n *\n * @param value - The value to check.\n * @returns True if the value carries the `input_required` discriminator.\n */\nexport const isInputRequiredResult = (value: unknown): value is InputRequiredResult =>\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value) &&\n (value as { resultType?: unknown }).resultType === 'input_required';\n\n/**\n * Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}.\n * @param value - The value to check.\n *\n * @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise.\n *\n * @deprecated Recognizes 2025-11-25 task wire vocabulary, which has no SDK\n * runtime; kept importable for interoperability only.\n */\nexport const isTaskAugmentedRequestParams = (value: unknown): value is TaskAugmentedRequestParams =>\n TaskAugmentedRequestParamsSchema.safeParse(value).success;\n\nexport const isInitializeRequest = (value: unknown): value is InitializeRequest => InitializeRequestSchema.safeParse(value).success;\n\nexport const isInitializedNotification = (value: unknown): value is InitializedNotification =>\n InitializedNotificationSchema.safeParse(value).success;\n\nexport function assertCompleteRequestPrompt(request: CompleteRequest): asserts request is CompleteRequestPrompt {\n if (request.params.ref.type !== 'ref/prompt') {\n throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`);\n }\n void (request as CompleteRequestPrompt);\n}\n\nexport function assertCompleteRequestResourceTemplate(request: CompleteRequest): asserts request is CompleteRequestResourceTemplate {\n if (request.params.ref.type !== 'ref/resource') {\n throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`);\n }\n void (request as CompleteRequestResourceTemplate);\n}\n","/**\n * SEP-2243 `Mcp-Param-*` header codec (protocol revision 2026-07-28).\n *\n * Pure functions for the custom-header half of SEP-2243: scanning a tool's\n * `inputSchema` for `x-mcp-header` declarations, encoding argument values into\n * `Mcp-Param-{Name}` HTTP headers (with the `=?base64?…?=` sentinel for values\n * that cannot be safely represented as plain ASCII field values), decoding\n * those headers, and validating that the headers a request carries match the\n * argument values in its body.\n *\n * The standard-header half (`MCP-Protocol-Version`, `Mcp-Method`, `Mcp-Name`)\n * lives with the inbound classifier — this module is the custom-header half\n * only, and it consumes the same `-32020` (`HeaderMismatch`) emission shape the\n * classifier established for header/body cross-check failures.\n *\n * Spec text at the implementation's spec pin:\n * - draft/basic/transports/streamable-http.mdx § \"Custom Headers from Tool Parameters\"\n * (constraints, value encoding, the 5-step client algorithm, the\n * server-behavior table, the `400` + `-32020` rejection)\n * - draft/server/tools.mdx § \"x-mcp-header\" (the schema-extension property and\n * its constraints)\n */\nimport type { InboundLadderRejection } from './inboundClassification';\nimport { HEADER_MISMATCH_ERROR_CODE } from './inboundClassification';\n\n/* ------------------------------------------------------------------------ *\n * Declaration scan\n * ------------------------------------------------------------------------ */\n\n/** The fixed prefix every custom-parameter header carries. */\nexport const MCP_PARAM_HEADER_PREFIX = 'Mcp-Param-';\n\n/** The schema-extension property name a tool's `inputSchema` carries. */\nexport const X_MCP_HEADER_KEY = 'x-mcp-header';\n\n/**\n * One `x-mcp-header` declaration found inside a tool's `inputSchema`.\n *\n * `path` is the property path from the arguments root (the spec permits\n * declarations at any nesting depth under `properties`); `headerName` is the\n * `{Name}` portion as declared (case preserved for emission; comparison is\n * case-insensitive); `type` is the JSON Schema `type` of the declaring\n * property.\n */\nexport interface XMcpHeaderDeclaration {\n path: readonly string[];\n headerName: string;\n type: string;\n}\n\n/** The result of scanning a tool's `inputSchema` for `x-mcp-header` declarations. */\nexport type XMcpHeaderScanResult = { valid: true; declarations: readonly XMcpHeaderDeclaration[] } | { valid: false; reason: string };\n\n/**\n * RFC 9110 §5.1 `token` syntax (`1*tchar`). Rejects empty, space, control\n * characters (including CR/LF), and the listed delimiters.\n */\nconst RFC9110_TOKEN = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\n\n/**\n * JSON Schema `type` values the spec admits on an `x-mcp-header` property.\n *\n * The spec text names `integer`, `string`, `boolean` and explicitly excludes\n * `number`. The published conformance referee at the pinned release ships its\n * `http-custom-headers` scenario with two `type: \"number\"` `x-mcp-header`\n * parameters and expects the client to mirror them, so `number` is accepted\n * here so that the conformance gate passes; the discrepancy is tracked\n * upstream. Everything else (`object`, `array`, `null`, absent) is rejected.\n */\nconst PERMITTED_X_MCP_HEADER_TYPES: ReadonlySet<string> = new Set(['string', 'integer', 'boolean', 'number']);\n\n/**\n * Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations\n * and validate every constraint the spec places on them. Returns either the\n * collected declarations (possibly empty) or the first violated constraint.\n *\n * The walk descends through `properties` at any depth (the spec's \"any nesting\n * depth\" clause). The static-reachability MUST is enforced as a structural\n * sweep: every position the chain MUST NOT pass through (`items`/\n * `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`,\n * `$defs`, `$ref` targets within `$defs`) is visited too, and an\n * `x-mcp-header` found anywhere on that path invalidates the schema — \"an\n * annotation anywhere else makes the tool definition invalid\".\n */\nexport function scanXMcpHeaderDeclarations(inputSchema: unknown): XMcpHeaderScanResult {\n const declarations: XMcpHeaderDeclaration[] = [];\n const seenLower = new Map<string, string>();\n\n const visit = (node: unknown, path: readonly string[], reachable: boolean): string | undefined => {\n if (node === null || typeof node !== 'object') return undefined;\n const schema = node as Record<string, unknown>;\n\n if (X_MCP_HEADER_KEY in schema) {\n if (!reachable || path.length === 0) {\n return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;\n }\n const raw = schema[X_MCP_HEADER_KEY];\n if (typeof raw !== 'string' || raw.length === 0) {\n return `${pathName(path)}: x-mcp-header MUST be a non-empty string`;\n }\n if (!RFC9110_TOKEN.test(raw)) {\n return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;\n }\n const type = typeof schema.type === 'string' ? schema.type : undefined;\n if (type === undefined || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) {\n return `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? '<none>'}`;\n }\n const lower = raw.toLowerCase();\n const prior = seenLower.get(lower);\n if (prior !== undefined) {\n return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`;\n }\n seenLower.set(lower, raw);\n declarations.push({ path, headerName: raw, type });\n }\n\n const properties = schema.properties;\n if (properties !== null && typeof properties === 'object') {\n for (const [key, child] of Object.entries(properties as Record<string, unknown>)) {\n const fault = visit(child, [...path, key], reachable);\n if (fault !== undefined) return fault;\n }\n }\n // Static-reachability sweep: descend the keywords the chain MUST NOT\n // pass through with `reachable: false` so an annotation under any of\n // them is reported (rather than silently ignored). `$defs` covers\n // `$ref`-within-`$defs` — chasing arbitrary `$ref` URIs is out of scope.\n for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) {\n const sub = schema[k];\n if (sub === undefined) continue;\n const branches: unknown[] = Array.isArray(sub)\n ? sub\n : sub !== null && typeof sub === 'object' && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k)\n ? Object.values(sub as Record<string, unknown>)\n : [sub];\n for (const branch of branches) {\n const fault = visit(branch, [...path, `<${k}>`], false);\n if (fault !== undefined) return fault;\n }\n }\n return undefined;\n };\n\n const fault = visit(inputSchema, [], true);\n return fault === undefined ? { valid: true, declarations } : { valid: false, reason: fault };\n}\n\n/**\n * JSON Schema keywords whose subschemas the SEP-2243 static-reachability\n * constraint excludes from the `properties`-only chain. An `x-mcp-header`\n * found under any of these invalidates the tool definition.\n */\nconst NON_REACHABLE_SUBSCHEMA_KEYWORDS = [\n 'items',\n 'prefixItems',\n 'contains',\n 'additionalProperties',\n 'unevaluatedProperties',\n 'unevaluatedItems',\n 'propertyNames',\n 'patternProperties',\n 'dependentSchemas',\n 'oneOf',\n 'anyOf',\n 'allOf',\n 'not',\n 'if',\n 'then',\n 'else',\n '$defs',\n 'definitions'\n] as const;\n\n/**\n * Subschema-carrying keywords whose value is a `name → subschema` object\n * (not a single subschema or array of subschemas). The visit branches over\n * `Object.values()` for these.\n */\nconst OBJECT_VALUED_SUBSCHEMA_KEYWORDS: ReadonlySet<string> = new Set(['patternProperties', 'dependentSchemas', '$defs', 'definitions']);\n\nfunction pathName(path: readonly string[]): string {\n return path.length === 0 ? '<root>' : path.join('.');\n}\n\n/* ------------------------------------------------------------------------ *\n * Value encoding\n * ------------------------------------------------------------------------ */\n\nconst BASE64_SENTINEL_PREFIX = '=?base64?';\nconst BASE64_SENTINEL_SUFFIX = '?=';\n// RFC 4648 §4, padding required (the spec's encoding-examples table and the\n// conformance referee's invalid-padding cell both require canonical padding).\nconst BASE64_CANONICAL = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\n// Strict decimal — gates the numeric comparison in `validateMcpParamHeaders`\n// so `Number()` never sees the looser forms it would otherwise accept\n// (`'0x1a'`, `' 42 '`, `'1e3'`).\nconst CANONICAL_DECIMAL = /^-?\\d+(\\.\\d+)?$/;\n\n/**\n * Convert a primitive argument value to its string representation per the\n * spec's type-conversion rules: strings pass through, integers and numbers\n * become their decimal string, booleans become lowercase `'true'` / `'false'`.\n * Non-finite numbers and integers outside the safe range are refused (the\n * caller treats `undefined` as \"do not emit a header for this value\").\n */\nexport function mcpParamPrimitiveToString(value: unknown): string | undefined {\n if (typeof value === 'string') return value;\n if (typeof value === 'boolean') return value ? 'true' : 'false';\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) return undefined;\n if (Number.isInteger(value) && !Number.isSafeInteger(value)) return undefined;\n return String(value);\n }\n return undefined;\n}\n\n/**\n * `true` when `s` cannot be safely represented as a plain ASCII HTTP field\n * value per RFC 9110 §5.5: it contains a byte outside `0x20–0x7E` / `0x09`, it\n * has leading or trailing whitespace (which field parsing strips), or it\n * already matches the Base64 sentinel pattern (the spec's \"to avoid ambiguity\"\n * rule).\n */\nfunction needsBase64(s: string): boolean {\n if (s.length === 0) return true;\n if (s.startsWith(BASE64_SENTINEL_PREFIX) && s.endsWith(BASE64_SENTINEL_SUFFIX)) return true;\n if (s !== s.trim()) return true;\n for (let i = 0; i < s.length; i++) {\n const c = s.codePointAt(i)!;\n // Visible ASCII 0x21–0x7E, plus space 0x20 and horizontal tab 0x09; a\n // tab is only safe when it is interior whitespace (the trim() check\n // above already covered leading/trailing).\n if (c === 0x09 || (c >= 0x20 && c <= 0x7e)) continue;\n return true;\n }\n return false;\n}\n\nfunction utf8ToBase64(s: string): string {\n const bytes = new TextEncoder().encode(s);\n let bin = '';\n for (const b of bytes) bin += String.fromCodePoint(b);\n return btoa(bin);\n}\n\nfunction base64ToUtf8(b64: string): string {\n const bin = atob(b64);\n const bytes = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i)!;\n return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n}\n\n/**\n * Encode a string value as an HTTP field value per the spec's value-encoding\n * rules: a value that is already a safe plain-ASCII field value is passed\n * through unchanged; anything else is wrapped as `=?base64?{b64-of-utf8}?=`.\n */\nexport function encodeMcpParamValue(value: string): string {\n return needsBase64(value) ? `${BASE64_SENTINEL_PREFIX}${utf8ToBase64(value)}${BASE64_SENTINEL_SUFFIX}` : value;\n}\n\n/**\n * Decode an `Mcp-Param-*` header value: when it carries the Base64 sentinel,\n * the payload is decoded as UTF-8; otherwise the value is returned as-is.\n * Returns `undefined` when the sentinel is present but the payload is not\n * canonical Base64 (or not valid UTF-8) — the spec requires servers to reject\n * such values.\n */\nexport function decodeMcpParamValue(value: string): string | undefined {\n if (!(value.startsWith(BASE64_SENTINEL_PREFIX) && value.endsWith(BASE64_SENTINEL_SUFFIX))) {\n return value;\n }\n const b64 = value.slice(BASE64_SENTINEL_PREFIX.length, value.length - BASE64_SENTINEL_SUFFIX.length);\n if (!BASE64_CANONICAL.test(b64)) return undefined;\n try {\n return base64ToUtf8(b64);\n } catch {\n return undefined;\n }\n}\n\n/* ------------------------------------------------------------------------ *\n * Client-side header construction (the 5-step MUST algorithm, steps 3–5)\n * ------------------------------------------------------------------------ */\n\nfunction valueAtPath(root: unknown, path: readonly string[]): unknown {\n let node: unknown = root;\n for (const key of path) {\n if (node === null || typeof node !== 'object') return undefined;\n node = (node as Record<string, unknown>)[key];\n }\n return node;\n}\n\n/**\n * Build the `Mcp-Param-{Name}` headers for one `tools/call` from a scan of the\n * tool's `inputSchema` and the call's `arguments`. A declaration whose value is\n * `null` or absent in `arguments` is omitted (the spec's \"client MUST omit the\n * header\" rows); a value that is not a primitive of the declared kind is\n * omitted rather than emitted malformed.\n */\nexport function buildMcpParamHeaders(\n declarations: readonly XMcpHeaderDeclaration[],\n args: Record<string, unknown> | undefined\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const decl of declarations) {\n const raw = valueAtPath(args, decl.path);\n if (raw === undefined || raw === null) continue;\n const stringValue = mcpParamPrimitiveToString(raw);\n if (stringValue === undefined) continue;\n out[`${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`] = encodeMcpParamValue(stringValue);\n }\n return out;\n}\n\n/* ------------------------------------------------------------------------ *\n * Server-side validation\n * ------------------------------------------------------------------------ */\n\n/**\n * The header/body comparison the server performs at tool-resolution time.\n *\n * For each `x-mcp-header` declaration on the named tool: when the body\n * `arguments` carries a value, the matching `Mcp-Param-{Name}` header MUST be\n * present and decode to an equal value; when the body value is `null` or\n * absent the server MUST NOT expect the header (a present header is ignored).\n * A sentinel-carrying header whose payload is not canonical Base64 / valid\n * UTF-8 is rejected as invalid characters.\n *\n * Integer-typed declarations are compared numerically (the spec's SHOULD —\n * `42.0` and `42` are equal); everything else is compared as decoded strings.\n *\n * Returns `undefined` when every check passes, or an\n * {@linkcode InboundLadderRejection} carrying the same `-32020`\n * (`HeaderMismatch`) shape the inbound classifier emits for the\n * standard-header cross-checks — `400 Bad Request` with the disagreeing pair\n * in `data.mismatch`.\n */\nexport function validateMcpParamHeaders(\n declarations: readonly XMcpHeaderDeclaration[],\n args: Record<string, unknown> | undefined,\n headers: Headers\n): InboundLadderRejection | undefined {\n for (const decl of declarations) {\n const headerKey = `${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`;\n const headerValue = headers.get(headerKey);\n const bodyRaw = valueAtPath(args, decl.path);\n\n if (bodyRaw === undefined || bodyRaw === null) {\n // Server MUST NOT expect the header for a null/absent value.\n continue;\n }\n const bodyString = mcpParamPrimitiveToString(bodyRaw);\n if (bodyString === undefined) {\n // Body carries a non-primitive where the schema declares one;\n // params validation owns that fault. Skip the header check.\n continue;\n }\n if (headerValue === null) {\n return paramHeaderMismatchRejection(\n 'param-header-missing',\n headerKey,\n `the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`\n );\n }\n const decoded = decodeMcpParamValue(headerValue);\n if (decoded === undefined) {\n return paramHeaderMismatchRejection(\n 'param-header-invalid-encoding',\n headerKey,\n `the ${headerKey} header carries an invalid Base64 sentinel value`\n );\n }\n // Integer/number-typed declarations compare numerically (the spec's\n // SHOULD — `42.0` and `42` are equal). The strict-decimal gate is\n // applied to the *header* side only (so `'0x1a'`, `' 42 '`, `'1e3'`\n // etc. never coerce); the body side is gated on being an actual JS\n // number — `String(0.0000001) === '1e-7'` would fail the regex even\n // though the value is perfectly canonical. A non-numeric body\n // primitive (e.g. `'abc'` where the schema declares `integer`) is a\n // body-vs-schema fault that params validation owns; fall back to\n // string comparison and let dispatch emit `-32602` instead so an\n // identical non-numeric pair never reports a mismatch.\n const numericComparable =\n (decl.type === 'integer' || decl.type === 'number') && CANONICAL_DECIMAL.test(decoded) && typeof bodyRaw === 'number';\n const equal = numericComparable ? Number(decoded) === bodyRaw : decoded === bodyString;\n if (!equal) {\n return paramHeaderMismatchRejection(\n 'param-header-mismatch',\n headerKey,\n `the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`\n );\n }\n }\n return undefined;\n}\n\n/**\n * Build the `-32020` (`HeaderMismatch`) rejection for an `Mcp-Param-*`\n * disagreement. Same shape as the inbound classifier's standard-header\n * cross-check mismatch (HTTP `400`, `data.mismatch` naming the disagreeing\n * pair, `settled: true`); only the rung differs because this check runs at the\n * pre-dispatch step against a known tool's schema rather than at the edge.\n */\nexport function paramHeaderMismatchRejection(cell: string, header: string, body: string): InboundLadderRejection {\n return {\n kind: 'reject',\n rung: 'param-header-validation',\n cell,\n httpStatus: 400,\n code: HEADER_MISMATCH_ERROR_CODE,\n message: `Bad Request: the request headers and body disagree: ${body}`,\n data: { mismatch: { header, body } },\n settled: true\n };\n}\n","/**\n * Inbound HTTP request classification and the inbound validation ladder\n * (protocol revision 2026-07-28).\n *\n * `classifyInboundRequest` is the body-primary era predicate for an HTTP\n * entry that serves both protocol eras on one endpoint. It is evaluated\n * exactly once, at the entry boundary, on the already-parsed request body:\n *\n * - `initialize` is a legacy-era request by definition (the modern era has no\n * `initialize` handshake) — unless it carries a valid envelope claim naming\n * a modern revision, in which case the claim wins and the request is\n * classified like any other enveloped request (the modern era then answers\n * it with method-not-found, exactly like every other method it does not\n * define).\n * - A request whose `params._meta` carries the reserved protocol-version key\n * claims the per-request envelope mechanism and classifies into the era the\n * named revision belongs to (a malformed envelope behind a present claim is\n * a validation error, never a silent fall back to legacy handling).\n * - A request without a claim is legacy-era traffic.\n * - The `MCP-Protocol-Version` header is a cross-check only: it never\n * upgrades or downgrades a body-derived classification, and a disagreement\n * between header and body is an explicit ladder outcome.\n * - Notifications carry no envelope claim of their own under the current\n * spec, so for notification POSTs without a body claim the modern header is\n * determinative; the `Mcp-Method` header is validated against the body when\n * the message classifies modern and is never enforced on legacy traffic.\n * A notification that does carry a claim is treated body-primary like a\n * request, and a malformed claim is rejected the same way a request's\n * malformed claim is — never silently resolved against the header.\n * The notification-POST header cross-checks here are an SDK-defensive\n * posture, not a spec requirement: the spec leaves header rules for posted\n * notifications undefined (core client notifications do not occur over\n * Streamable HTTP); applying the request rules symmetrically is what an\n * ecosystem custom-notification POST expects, and the −32020 cells stay\n * passing for them.\n * - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era\n * session operations: the modern era is `POST`-only, so they are routed to\n * legacy serving when it is configured and rejected otherwise.\n * - Array (batch) bodies are classified element-wise: an array containing a\n * modern-claiming or invalid element is rejected, an all-legacy array is\n * legacy traffic unchanged, and a single-element array is still an array.\n *\n * The classifier returns plain values (it never throws and never touches a\n * transport): a routing outcome (`legacy`/`modern`) or a ladder rejection\n * carrying the JSON-RPC error to emit and the HTTP status to emit it with.\n * Legacy routing outcomes deliberately carry NO `MessageClassification` —\n * legacy and hand-wired traffic is never classified, which keeps its\n * dispatch behavior byte-identical to today's.\n *\n * Error codes for the modern-path rejection cells follow the published\n * conformance suite (and the spec text it asserts):\n *\n * - A header/body cross-check mismatch (the `MCP-Protocol-Version` header\n * disagreeing with the body, or the `Mcp-Method` header disagreeing with the\n * body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400.\n * - A request whose protocol-version header names a modern revision but whose\n * body carries no `_meta` envelope claim — including an envelope present but\n * missing the required protocol-version key — is rejected with `-32602`\n * (invalid params) naming the missing key(s), on HTTP 400.\n *\n * Should a future spec revision or conformance release change these\n * assignments, the affected cells are re-derived against that release; the\n * `settled` flag on {@linkcode InboundLadderRejection} stays available to mark\n * a cell provisional again while such a change is in flight.\n */\nimport { PROTOCOL_VERSION_META_KEY } from '../types/constants';\nimport { ProtocolErrorCode } from '../types/enums';\nimport { ProtocolError, UnsupportedProtocolVersionError } from '../types/errors';\nimport { isJSONRPCErrorResponse, isJSONRPCNotification, isJSONRPCRequest, isJSONRPCResultResponse } from '../types/guards';\nimport type { JSONRPCNotification, JSONRPCRequest, MessageClassification } from '../types/types';\nimport { envelopeClaimVersion, hasEnvelopeClaim, requestMetaOf, validateEnvelopeMeta } from './envelope';\n// Value encoding is shared between the standard `Mcp-Name` header and the\n// custom `Mcp-Param-*` headers; the codec module already imports the\n// `HeaderMismatch` constant and rejection type from here, so this is a benign\n// two-module cycle (both sides only consume the other's exports inside\n// function bodies, never at module-evaluation time).\nimport { decodeMcpParamValue } from './mcpParamHeaders';\nimport { isModernProtocolVersion } from './protocolEras';\n\n/* ------------------------------------------------------------------------ *\n * Classifier input\n * ------------------------------------------------------------------------ */\n\n/**\n * The transport-neutral description of an inbound HTTP request the classifier\n * evaluates. The caller (the HTTP entry) reads the body exactly once and\n * extracts the two protocol headers; the classifier never touches a request\n * object itself.\n */\nexport interface InboundHttpRequest {\n /** The HTTP request method, e.g. `POST`, `GET`, `DELETE`. */\n httpMethod: string;\n /** The value of the `MCP-Protocol-Version` header, when present. */\n protocolVersionHeader?: string;\n /** The value of the `Mcp-Method` header, when present. */\n mcpMethodHeader?: string;\n /** The value of the `Mcp-Name` header, when present. */\n mcpNameHeader?: string;\n /** The parsed JSON request body (`undefined` for body-less methods). */\n body?: unknown;\n}\n\n/* ------------------------------------------------------------------------ *\n * Classifier outcomes\n * ------------------------------------------------------------------------ */\n\n/** Why an inbound request was routed to legacy-era serving. */\nexport type InboundLegacyRouteReason =\n /** Non-`POST` HTTP method: a body-less 2025-era session operation. */\n | 'http-method'\n /** An `initialize` request without a valid modern envelope claim — the legacy handshake by definition. */\n | 'initialize'\n /** A request without a per-request envelope claim. */\n | 'no-claim'\n /** A notification without a body claim or a modern protocol-version header. */\n | 'notification'\n /** An all-legacy JSON-RPC batch array. */\n | 'batch'\n /** A JSON-RPC response posted to the endpoint (2025-era session traffic). */\n | 'response';\n\n/**\n * The request is legacy-era traffic. It carries no classification on purpose:\n * legacy serving receives it exactly as a hand-wired 2025 transport would.\n */\nexport interface InboundLegacyRoute {\n kind: 'legacy';\n reason: InboundLegacyRouteReason;\n /**\n * The protocol version the request named, when it named one (an\n * `initialize` body's `protocolVersion`, or the `MCP-Protocol-Version`\n * header). Used to echo `requested` when legacy serving is not configured.\n */\n requestedVersion?: string;\n}\n\n/**\n * The request claims the per-request envelope mechanism and is served on the\n * modern path. Discriminated by `messageKind` so the typed `message` narrows\n * with it — the classifier has already proved the JSON-RPC shape via the\n * `isJSONRPCRequest` / `isJSONRPCNotification` guards, so consumers never\n * cast the body again.\n */\nexport type InboundModernRoute =\n | {\n kind: 'modern';\n messageKind: 'request';\n /** The classified body — guard-proved {@linkcode JSONRPCRequest} shape. */\n message: JSONRPCRequest;\n /**\n * The classification handed to the per-request transport and validated by\n * the protocol layer against the serving instance's negotiated era.\n */\n classification: MessageClassification;\n }\n | {\n kind: 'modern';\n messageKind: 'notification';\n /** The classified body — guard-proved {@linkcode JSONRPCNotification} shape. */\n message: JSONRPCNotification;\n classification: MessageClassification;\n };\n\n/** The named steps of the inbound validation ladder, in evaluation order. */\nexport type InboundValidationRung =\n | 'http-method'\n | 'jsonrpc-shape'\n | 'era-classification'\n | 'envelope'\n | 'method-registry'\n | 'request-params'\n | 'standard-header-validation'\n | 'client-capabilities'\n | 'param-header-validation';\n\n/** A ladder rejection: the JSON-RPC error to emit and the HTTP status to emit it with. */\nexport interface InboundLadderRejection {\n kind: 'reject';\n /** The ladder rung that produced the rejection. */\n rung: InboundValidationRung;\n /** The cell this rejection corresponds to on the ladder cell sheet (stable identifier for tests). */\n cell: string;\n /** The HTTP status the rejection is emitted with. */\n httpStatus: number;\n /** The JSON-RPC error code. */\n code: number;\n /** The JSON-RPC error message. */\n message: string;\n /** Structured error data (recognizers parse this; they never rely on class identity). */\n data?: unknown;\n /**\n * `false` when the exact error code for this cell is not settled upstream\n * yet and the emitted code is provisional.\n */\n settled: boolean;\n}\n\n/** The outcome of classifying one inbound HTTP request. */\nexport type InboundClassificationOutcome = InboundLegacyRoute | InboundModernRoute | InboundLadderRejection;\n\n/* ------------------------------------------------------------------------ *\n * Header cross-check mismatches\n * ------------------------------------------------------------------------ */\n\n/**\n * The error code emitted for header/body cross-check mismatches: the\n * `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or\n * with the body's classification), and the `Mcp-Method` header disagreeing\n * with the body method.\n *\n * `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243\n * `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted\n * by the published conformance suite for header-validation failures. It has no\n * {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era\n * wire vocabulary; the validation ladder is its only emitter.\n */\nexport const HEADER_MISMATCH_ERROR_CODE = -32_020;\n\n/* ------------------------------------------------------------------------ *\n * The validation ladder as data\n * ------------------------------------------------------------------------ */\n\n/** One rung of the inbound validation ladder. */\nexport interface InboundValidationRungDescriptor {\n rung: InboundValidationRung;\n /** Evaluation order: lower runs first; an earlier rung's outcome wins over a later rung's. */\n order: number;\n /**\n * Where the rung is evaluated: at the HTTP entry edge by\n * {@linkcode classifyInboundRequest} (`edge`), by the HTTP entry after\n * classification but before dispatch (`pre-dispatch`), or by the protocol\n * layer at dispatch (`dispatch`).\n */\n evaluatedAt: 'edge' | 'pre-dispatch' | 'dispatch';\n /** The JSON-RPC error codes this rung can produce (empty when the rung only routes). */\n codes: readonly number[];\n /** Conformance scenarios that exercise this rung (where one exists). */\n conformance: readonly string[];\n /** Why the rung sits where it does. */\n rationale: string;\n}\n\n/**\n * The inbound validation ladder, expressed as data rather than control flow.\n *\n * The edge rungs are evaluated by {@linkcode classifyInboundRequest}; the\n * dispatch rungs are evaluated by the protocol layer once the classified\n * message is injected into a per-request server instance (the era registry\n * gate, the envelope requiredness check, and per-method params validation).\n * The client-capability rung is evaluated by the HTTP entry itself,\n * pre-dispatch, on the validated envelope the classifier produced — see that\n * rung's rationale for the ordering caveat. The order is the precedence: a\n * request that fails several rungs is answered by the earliest one.\n */\nexport const INBOUND_VALIDATION_LADDER: readonly InboundValidationRungDescriptor[] = [\n {\n rung: 'http-method',\n order: 1,\n evaluatedAt: 'edge',\n codes: [-32_000],\n conformance: [],\n rationale:\n 'The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy ' +\n 'serving (405 when legacy serving is not configured), before any body is read.'\n },\n {\n rung: 'jsonrpc-shape',\n order: 2,\n evaluatedAt: 'edge',\n codes: [ProtocolErrorCode.InvalidRequest],\n conformance: ['server-stateless'],\n rationale:\n 'The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or ' +\n 'invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic.'\n },\n {\n rung: 'era-classification',\n order: 3,\n evaluatedAt: 'edge',\n codes: [HEADER_MISMATCH_ERROR_CODE, ProtocolErrorCode.UnsupportedProtocolVersion],\n conformance: ['server-stateless', 'http-header-validation', 'http-custom-header-server-validation'],\n rationale:\n 'Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected ' +\n 'with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the ' +\n 'unsupported-protocol-version error naming the supported revisions.'\n },\n {\n rung: 'envelope',\n order: 4,\n evaluatedAt: 'edge',\n codes: [ProtocolErrorCode.InvalidParams],\n conformance: ['server-stateless'],\n rationale:\n 'A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header ' +\n 'names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall ' +\n 'back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400.'\n },\n {\n rung: 'method-registry',\n order: 5,\n evaluatedAt: 'dispatch',\n codes: [ProtocolErrorCode.MethodNotFound],\n conformance: ['server-stateless'],\n rationale:\n 'Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no ' +\n 'handler installed) answers method-not-found before params or capabilities are looked at.'\n },\n {\n rung: 'request-params',\n order: 6,\n evaluatedAt: 'dispatch',\n codes: [ProtocolErrorCode.InvalidParams],\n conformance: [],\n rationale: 'Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table.'\n },\n {\n rung: 'standard-header-validation',\n order: 7,\n evaluatedAt: 'pre-dispatch',\n codes: [HEADER_MISMATCH_ERROR_CODE],\n conformance: ['http-header-validation'],\n rationale:\n 'SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check ' +\n '— are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before ' +\n 'dispatch. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge ' +\n '`era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the ' +\n 'capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by ' +\n 'the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the ' +\n 'observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request ' +\n 'that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted.'\n },\n {\n rung: 'client-capabilities',\n order: 8,\n evaluatedAt: 'pre-dispatch',\n codes: [ProtocolErrorCode.MissingRequiredClientCapability],\n conformance: ['server-stateless'],\n rationale:\n 'The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the ' +\n 'classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced ' +\n 'errors are mapped. The documented order (after method resolution and params validation) is preserved observably ' +\n 'only while the requirement table is empty: once a served method gains a requirement entry, a request that is ' +\n 'missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must ' +\n 'consult the method registry before the gate if the documented precedence is to stay observable.'\n },\n {\n rung: 'param-header-validation',\n order: 9,\n evaluatedAt: 'pre-dispatch',\n codes: [HEADER_MISMATCH_ERROR_CODE],\n conformance: ['http-custom-header-server-validation'],\n rationale:\n 'SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body ' +\n '`arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed ' +\n 'header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order ' +\n '(after method resolution and params validation) is preserved observably only when the body `arguments` would ' +\n 'otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time ' +\n 'rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the ' +\n 'earlier-ordered rung.'\n }\n];\n\n/* ------------------------------------------------------------------------ *\n * HTTP status mapping for ladder-originated errors\n * ------------------------------------------------------------------------ */\n\n/**\n * HTTP status for ladder-originated JSON-RPC error codes.\n *\n * Keyed on origin, not on the bare code: this table only applies to errors\n * the ladder (or a pre-handler protocol gate) produced. Errors produced by\n * request handlers — whatever their code — stay in-band on HTTP 200, and are\n * never mapped to an HTTP status by this table; in particular `-32603` and\n * domain-specific codes never become a blanket 500.\n *\n * `-32602` (invalid params) deliberately has NO entry: the only invalid-params\n * rejection that maps to HTTP 400 is the classifier's own envelope rung\n * short-circuit, which carries its HTTP status directly. A dispatch- or\n * handler-produced invalid-params error is always in-band.\n */\nexport const LADDER_ERROR_HTTP_STATUS: Readonly<Record<number, number>> = {\n [ProtocolErrorCode.ParseError]: 400,\n [ProtocolErrorCode.InvalidRequest]: 400,\n [ProtocolErrorCode.MethodNotFound]: 404,\n [ProtocolErrorCode.UnsupportedProtocolVersion]: 400,\n [ProtocolErrorCode.MissingRequiredClientCapability]: 400,\n [HEADER_MISMATCH_ERROR_CODE]: 400\n};\n\n/**\n * The HTTP status to answer a JSON-RPC error with, keyed on the error's\n * origin. `in-band` errors (anything produced by a request handler) are\n * always HTTP 200 — the JSON-RPC error response is the payload, not an HTTP\n * failure. `ladder` errors map through {@linkcode LADDER_ERROR_HTTP_STATUS}.\n */\nexport function httpStatusForErrorCode(code: number, origin: 'ladder' | 'in-band'): number {\n if (origin === 'in-band') return 200;\n return LADDER_ERROR_HTTP_STATUS[code] ?? 400;\n}\n\n/* ------------------------------------------------------------------------ *\n * The classifier\n * ------------------------------------------------------------------------ */\n\nfunction rejection(\n rung: InboundValidationRung,\n cell: string,\n httpStatus: number,\n error: ProtocolError,\n settled: boolean\n): InboundLadderRejection {\n return {\n kind: 'reject',\n rung,\n cell,\n httpStatus,\n code: error.code,\n message: error.message,\n ...(error.data !== undefined && { data: error.data }),\n settled\n };\n}\n\nfunction crossCheckMismatch(\n cell: string,\n header: string,\n body: string,\n rung: InboundValidationRung = 'era-classification'\n): InboundLadderRejection {\n return rejection(\n rung,\n cell,\n 400,\n new ProtocolError(HEADER_MISMATCH_ERROR_CODE, `Bad Request: the request headers and body disagree: ${body}`, {\n mismatch: { header, body }\n }),\n true\n );\n}\n\n/**\n * The methods whose body carries a `params.name` / `params.uri` value the\n * `Mcp-Name` header must mirror, and which body field supplies it (SEP-2243\n * § Standard Request Headers, `Required For` column).\n */\nexport const MCP_NAME_HEADER_SOURCE: Readonly<Record<string, 'name' | 'uri'>> = {\n 'tools/call': 'name',\n 'prompts/get': 'name',\n 'resources/read': 'uri'\n};\n\n/**\n * SEP-2243 standard-header server-side validation, evaluated by the HTTP\n * entry on a modern-classified request immediately after\n * {@linkcode classifyInboundRequest} returns a modern route.\n *\n * Returns the `-32020` (`HeaderMismatch`) ladder rejection (HTTP `400`,\n * `standard-header-validation` rung — the same shape\n * {@linkcode classifyInboundRequest} already emits on the edge\n * `era-classification` rung for the `MCP-Protocol-Version` and\n * `Mcp-Method` *mismatch* cells) when:\n *\n * - the required `Mcp-Method` header is absent;\n * - the required `Mcp-Name` header is absent on a `tools/call`,\n * `prompts/get`, or `resources/read` request whose body carries the\n * `params.name` / `params.uri` value the header mirrors;\n * - the `Mcp-Name` header carries an invalid `=?base64?…?=` sentinel; or\n * - the (decoded) `Mcp-Name` value disagrees with the body's\n * `params.name` / `params.uri`.\n *\n * Returns `undefined` (pass) for notifications (the spec table reads\n * \"All requests\"), for methods that have no `Mcp-Name` source, and when the\n * headers agree with the body. Never enforced on legacy traffic — the entry\n * only calls this on a modern route.\n *\n * Kept separate from {@linkcode classifyInboundRequest} so that a body-only\n * call to the classifier (no headers passed) keeps routing a modern request\n * unchanged: the classifier remains a pure body-primary router, and this\n * function is the presence/`Mcp-Name` half of the standard-header rung the\n * entry layers on top.\n */\nexport function validateStandardRequestHeaders(request: InboundHttpRequest, route: InboundModernRoute): InboundLadderRejection | undefined {\n if (route.messageKind !== 'request') {\n return undefined;\n }\n const method = route.message.method;\n\n if (request.mcpMethodHeader === undefined) {\n return crossCheckMismatch(\n 'method-header-missing',\n '(missing)',\n `the body names method ${method} but the required Mcp-Method header is absent`,\n 'standard-header-validation'\n );\n }\n\n // `method` is the JSON-RPC method string from the body — peer-controlled,\n // so guard the plain-object lookup against `Object.prototype` collisions\n // (`constructor`, `toString`, …) the same way the client-capability table\n // lookup does.\n const sourceField = Object.hasOwn(MCP_NAME_HEADER_SOURCE, method) ? MCP_NAME_HEADER_SOURCE[method] : undefined;\n if (sourceField === undefined) {\n return undefined;\n }\n const params = route.message.params as Record<string, unknown> | undefined;\n const sourceValue = params?.[sourceField];\n const bodyValue = typeof sourceValue === 'string' ? sourceValue : undefined;\n\n if (request.mcpNameHeader === undefined) {\n // The header is required for these methods whenever the body carries\n // the source value. A body without `params.name`/`params.uri` is a\n // params-validation failure further down the ladder; this rung only\n // answers the missing-header case it can observe.\n if (bodyValue === undefined) {\n return undefined;\n }\n return crossCheckMismatch(\n 'name-header-missing',\n '(missing)',\n `the body carries params.${sourceField}=\"${bodyValue}\" but the required Mcp-Name header is absent`,\n 'standard-header-validation'\n );\n }\n\n const decoded = decodeMcpParamValue(request.mcpNameHeader);\n if (decoded === undefined) {\n return crossCheckMismatch(\n 'name-header-invalid-encoding',\n request.mcpNameHeader,\n 'the Mcp-Name header carries an invalid Base64 sentinel value',\n 'standard-header-validation'\n );\n }\n if (bodyValue !== undefined && decoded !== bodyValue) {\n return crossCheckMismatch(\n 'name-header-mismatch',\n request.mcpNameHeader,\n `the body carries params.${sourceField}=\"${bodyValue}\" but the Mcp-Name header names \"${decoded}\"`,\n 'standard-header-validation'\n );\n }\n return undefined;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction classificationForClaim(claimedVersion: string | undefined): MessageClassification {\n if (claimedVersion === undefined) {\n return { era: 'modern' };\n }\n return { era: isModernProtocolVersion(claimedVersion) ? 'modern' : 'legacy', revision: claimedVersion };\n}\n\n/**\n * Whether a request's params carry a per-request envelope claim that is both\n * well-formed and names a modern protocol revision.\n *\n * Used by the `initialize` precedence rule: only such a claim overrides the\n * `initialize` ⇒ legacy-handshake classification — a request carrying a valid\n * modern envelope is a modern request regardless of its method name, and the\n * modern era then answers `initialize` exactly like any other method it does\n * not define (method-not-found). A malformed claim, or one naming a pre-2026\n * revision, keeps the legacy-handshake routing unchanged.\n *\n * Exported on the core internal barrel for the stdio serving entry, which\n * applies the same precedence rule to a connection's opening message; not\n * public API.\n */\nexport function carriesValidModernEnvelopeClaim(params: unknown): boolean {\n if (!hasEnvelopeClaim(params)) {\n return false;\n }\n const claimedVersion = envelopeClaimVersion(params);\n if (claimedVersion === undefined || !isModernProtocolVersion(claimedVersion)) {\n return false;\n }\n const meta = requestMetaOf(params);\n return meta !== undefined && validateEnvelopeMeta(meta).length === 0;\n}\n\nfunction classifyBatch(body: readonly unknown[]): InboundClassificationOutcome {\n if (body.length === 0) {\n return rejection(\n 'jsonrpc-shape',\n 'empty-batch',\n 400,\n new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Bad Request: empty JSON-RPC batch'),\n true\n );\n }\n for (const element of body) {\n const params = isPlainObject(element) ? element['params'] : undefined;\n if (hasEnvelopeClaim(params)) {\n // Element-wise rule: a single modern element makes the whole array\n // unservable — modern requests are single-message POSTs, and the\n // legacy path must never serve an envelope-claiming element.\n return rejection(\n 'jsonrpc-shape',\n 'batch-with-modern-element',\n 400,\n new ProtocolError(\n ProtocolErrorCode.InvalidRequest,\n 'Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later'\n ),\n true\n );\n }\n const valid =\n isJSONRPCRequest(element) ||\n isJSONRPCNotification(element) ||\n isJSONRPCResultResponse(element) ||\n isJSONRPCErrorResponse(element);\n if (!valid) {\n return rejection(\n 'jsonrpc-shape',\n 'batch-with-invalid-element',\n 400,\n new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Bad Request: JSON-RPC batch contains an invalid message'),\n true\n );\n }\n }\n // All elements are legacy-era messages: legacy serving takes the array unchanged.\n return { kind: 'legacy', reason: 'batch' };\n}\n\nfunction classifyRequestBody(request: InboundHttpRequest, body: JSONRPCRequest): InboundClassificationOutcome {\n const params = body.params;\n const method = body.method;\n const headerVersion = request.protocolVersionHeader;\n const headerNamesModern = headerVersion !== undefined && isModernProtocolVersion(headerVersion);\n\n // `initialize` is the legacy handshake by definition — unless the request\n // carries a valid envelope claim naming a modern revision, in which case\n // the claim wins: the request is classified like any other enveloped\n // request and served on the modern path, where the modern registry answers\n // `initialize` as method-not-found like every other method it does not\n // define. A malformed or absent claim, or a claim naming a pre-2026\n // revision, keeps the legacy-handshake classification below.\n if (method === 'initialize' && !carriesValidModernEnvelopeClaim(params)) {\n if (headerNamesModern) {\n return crossCheckMismatch(\n 'initialize-with-modern-header',\n headerVersion,\n 'an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header'\n );\n }\n const requestedVersion =\n isPlainObject(params) && typeof params['protocolVersion'] === 'string' ? params['protocolVersion'] : undefined;\n return { kind: 'legacy', reason: 'initialize', ...(requestedVersion !== undefined && { requestedVersion }) };\n }\n\n if (hasEnvelopeClaim(params)) {\n // A present claim is validated, never silently ignored: a malformed\n // envelope behind the claim is an invalid-params rejection naming the\n // offending key, not a fall back to legacy handling.\n const meta = requestMetaOf(params);\n const issues = meta === undefined ? [] : validateEnvelopeMeta(meta);\n const firstIssue = issues[0];\n if (firstIssue !== undefined) {\n return rejection(\n 'envelope',\n 'envelope-invalid',\n 400,\n new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`,\n { envelope: firstIssue }\n ),\n true\n );\n }\n\n const claimedVersion = envelopeClaimVersion(params);\n if (headerVersion !== undefined && claimedVersion !== undefined && headerVersion !== claimedVersion) {\n return crossCheckMismatch(\n 'header-body-version-mismatch',\n headerVersion,\n `the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`\n );\n }\n if (request.mcpMethodHeader !== undefined && request.mcpMethodHeader !== method) {\n return crossCheckMismatch(\n 'method-header-mismatch',\n request.mcpMethodHeader,\n `the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`\n );\n }\n return { kind: 'modern', messageKind: 'request', message: body, classification: classificationForClaim(claimedVersion) };\n }\n\n // No claim: legacy-era traffic — unless the protocol-version header names a\n // modern revision. The modern revisions carry their request metadata in the\n // per-request `_meta` envelope, so a modern-classified request without one\n // is missing required params: it is rejected with invalid params naming the\n // missing key(s), never silently served as legacy traffic and never\n // upgraded from the header alone.\n if (headerNamesModern) {\n const meta = requestMetaOf(params);\n const missingFromEnvelope = validateEnvelopeMeta(meta ?? {})\n .filter(issue => issue.problem === 'missing')\n .map(issue => issue.key);\n const missing = meta === undefined ? ['_meta'] : missingFromEnvelope.length > 0 ? missingFromEnvelope : [PROTOCOL_VERSION_META_KEY];\n return rejection(\n 'envelope',\n 'modern-header-without-claim',\n 400,\n new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing ` +\n `the required per-request envelope key(s): ${missing.join(', ')}`,\n { envelope: { missing } }\n ),\n true\n );\n }\n return { kind: 'legacy', reason: 'no-claim', ...(headerVersion !== undefined && { requestedVersion: headerVersion }) };\n}\n\nfunction classifyNotificationBody(request: InboundHttpRequest, body: JSONRPCNotification): InboundClassificationOutcome {\n const params = body.params;\n const method = body.method;\n const headerVersion = request.protocolVersionHeader;\n const headerNamesModern = headerVersion !== undefined && isModernProtocolVersion(headerVersion);\n\n if (hasEnvelopeClaim(params)) {\n // Body-primary even for notifications: a body claim wins over the\n // header, and a disagreement between them is rejected rather than\n // letting either signal silently pick the serving path.\n const claimedVersion = envelopeClaimVersion(params);\n if (claimedVersion === undefined) {\n // The claim key is present but its value is malformed (not a\n // string). Validated exactly like a request claim: an\n // invalid-params rejection naming the offending key — never a\n // silent win against (or loss to) a disagreeing header.\n const meta = requestMetaOf(params);\n const issues = meta === undefined ? [] : validateEnvelopeMeta(meta);\n const claimIssue = issues.find(issue => issue.key === PROTOCOL_VERSION_META_KEY) ?? {\n key: PROTOCOL_VERSION_META_KEY,\n problem: 'expected a protocol version string'\n };\n return rejection(\n 'envelope',\n 'notification-envelope-invalid',\n 400,\n new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`,\n { envelope: claimIssue }\n ),\n true\n );\n }\n if (headerVersion !== undefined && headerVersion !== claimedVersion) {\n return crossCheckMismatch(\n 'notification-header-body-version-mismatch',\n headerVersion,\n `the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`\n );\n }\n const classification = classificationForClaim(claimedVersion);\n if (classification.era === 'modern' && request.mcpMethodHeader !== undefined && request.mcpMethodHeader !== method) {\n return crossCheckMismatch(\n 'notification-method-header-mismatch',\n request.mcpMethodHeader,\n `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`\n );\n }\n return { kind: 'modern', messageKind: 'notification', message: body, classification };\n }\n\n // Notifications carry no body claim under the current spec, so the\n // protocol-version header is determinative for them: a modern header\n // routes the notification to modern serving; a missing or legacy header\n // keeps it legacy traffic. The Mcp-Method header is validated only when\n // the notification classifies modern — it is never enforced on legacy\n // notifications.\n if (headerNamesModern) {\n if (request.mcpMethodHeader !== undefined && request.mcpMethodHeader !== method) {\n return crossCheckMismatch(\n 'notification-method-header-mismatch',\n request.mcpMethodHeader,\n `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`\n );\n }\n return {\n kind: 'modern',\n messageKind: 'notification',\n message: body,\n classification: { era: 'modern', revision: headerVersion }\n };\n }\n return { kind: 'legacy', reason: 'notification', ...(headerVersion !== undefined && { requestedVersion: headerVersion }) };\n}\n\n/**\n * Classifies one inbound HTTP request for dual-era serving.\n *\n * The body-primary predicate, evaluated once at the entry boundary: see the\n * module documentation for the rules. Returns a routing outcome (`legacy` or\n * `modern`) or a ladder rejection; it never throws.\n */\nexport function classifyInboundRequest(request: InboundHttpRequest): InboundClassificationOutcome {\n if (request.httpMethod.toUpperCase() !== 'POST') {\n // Body-less 2025-era session operations (and any other non-POST\n // method): the modern era is POST-only.\n return { kind: 'legacy', reason: 'http-method' };\n }\n\n const body = request.body;\n if (Array.isArray(body)) {\n return classifyBatch(body);\n }\n if (isJSONRPCResultResponse(body) || isJSONRPCErrorResponse(body)) {\n // Posted responses are 2025-era session traffic (replies to\n // server-initiated requests over a session); the modern era has no\n // such channel.\n return { kind: 'legacy', reason: 'response' };\n }\n if (isPlainObject(body) && isJSONRPCRequest(body)) {\n return classifyRequestBody(request, body);\n }\n if (isPlainObject(body) && isJSONRPCNotification(body)) {\n return classifyNotificationBody(request, body);\n }\n return rejection(\n 'jsonrpc-shape',\n 'invalid-json-rpc-body',\n 400,\n new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Bad Request: the request body is not a valid JSON-RPC message'),\n true\n );\n}\n\n/* ------------------------------------------------------------------------ *\n * Modern-only (strict) mapping of legacy routes\n * ------------------------------------------------------------------------ */\n\n/**\n * The rejection a modern-only endpoint (no legacy serving configured)\n * answers a legacy-classified request with.\n *\n * - Envelope-less requests (including `initialize`) are answered with the\n * unsupported-protocol-version error carrying the endpoint's supported\n * versions and echoing the version the request named (when it named one —\n * `requested` is omitted rather than fabricated when the request named no\n * version at all), so a legacy client can discover what the endpoint serves\n * from the error alone.\n * - Posted responses and batch arrays are invalid requests on the modern era.\n * - Non-`POST` methods are not allowed.\n * - Legacy-classified notifications return `undefined`: the caller answers\n * 202 with no body and does not dispatch the notification (accept-and-drop).\n */\nexport function modernOnlyStrictRejection(\n route: InboundLegacyRoute,\n supportedVersions: readonly string[]\n): InboundLadderRejection | undefined {\n switch (route.reason) {\n case 'http-method': {\n return rejection('http-method', 'modern-only-method-not-allowed', 405, new ProtocolError(-32_000, 'Method not allowed.'), true);\n }\n case 'batch': {\n return rejection(\n 'jsonrpc-shape',\n 'modern-only-batch-not-supported',\n 400,\n new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Bad Request: JSON-RPC batches are not supported by this endpoint'),\n true\n );\n }\n case 'response': {\n return rejection(\n 'jsonrpc-shape',\n 'modern-only-response-post',\n 400,\n new ProtocolError(ProtocolErrorCode.InvalidRequest, 'Bad Request: JSON-RPC responses cannot be posted to this endpoint'),\n true\n );\n }\n case 'notification': {\n return undefined;\n }\n case 'initialize':\n case 'no-claim': {\n // `requested` reflects what the request actually named (an\n // initialize body's `protocolVersion` or the protocol-version\n // header); when the request named no version at all the field is\n // omitted rather than fabricated.\n const requested = route.requestedVersion;\n const error =\n requested === undefined\n ? new ProtocolError(\n ProtocolErrorCode.UnsupportedProtocolVersion,\n 'Unsupported protocol version: the request did not name a protocol version',\n { supported: [...supportedVersions] }\n )\n : new UnsupportedProtocolVersionError({ supported: [...supportedVersions], requested });\n return rejection('era-classification', 'modern-only-missing-envelope', 400, error, true);\n }\n }\n}\n","/**\n * Authoring helpers for multi-round-trip requests (protocol revision\n * 2026-07-28).\n *\n * A handler for one of the multi-round-trip methods (`tools/call`,\n * `prompts/get`, `resources/read`) requests additional client input by\n * returning an {@linkcode InputRequiredResult} instead of a final result. The\n * helpers here build that return value and its embedded requests as NEUTRAL\n * values; only the 2026-07-28 wire codec maps them to/from the wire. The\n * 2025-era codec has no input-required vocabulary — on a 2025-era request the\n * server's legacy shim (on by default) fulfils the embedded requests as real\n * server→client requests and re-enters the handler, so the same return shape\n * serves both eras; `ServerOptions.inputRequired.legacyShim: false` restores\n * the pre-shim loud failure.\n *\n * There is no nominal brand: `resultType: 'input_required'` is the\n * discriminator, and hand-built result literals are equally legal — the\n * server seam re-checks the at-least-one rule for them.\n */\nimport { isInputRequiredResult } from '../types/guards';\nimport type {\n CreateMessageRequestParams,\n CreateMessageResult,\n CreateMessageResultWithTools,\n ElicitRequestFormParams,\n ElicitRequestURLParams,\n InputRequest,\n InputRequests,\n InputRequiredResult,\n InputResponses,\n Root\n} from '../types/types';\nimport type { StandardSchemaV1 } from '../util/standardSchema';\n\n/** The shape accepted by {@linkcode inputRequired}. */\nexport interface InputRequiredSpec {\n /** Embedded requests the client must fulfil before retrying. */\n inputRequests?: InputRequests;\n /** Opaque server state echoed back verbatim by the client on retry. */\n requestState?: string;\n}\n\ninterface InputRequiredBuilder {\n /**\n * Builds the input-required return value for a multi-round-trip handler.\n *\n * At least one of `inputRequests` or `requestState` must be provided\n * (spec: basic/patterns/mrtr, server requirements) — the builder throws a\n * `TypeError` otherwise, and the server seam re-checks the same rule for\n * hand-built results.\n *\n * `requestState` is opaque, server-minted state. It round-trips through\n * the client and comes back as attacker-controlled input: a server that\n * lets it influence authorization, resource access, or business logic\n * MUST integrity-protect it (e.g. HMAC or AEAD) and MUST reject state\n * that fails verification. The SDK does not do this for you.\n */\n (spec: InputRequiredSpec): InputRequiredResult;\n\n /** Builds an embedded form-mode elicitation request (`elicitation/create`). */\n elicit(params: Omit<ElicitRequestFormParams, 'mode'> & { mode?: 'form' }): InputRequest;\n\n /**\n * Builds an embedded URL-mode elicitation request (`elicitation/create`).\n * On the 2026-07-28 revision URL elicitation rides the multi-round-trip\n * flow — the `-32042` error of earlier revisions never appears on this\n * era's wire. The 2025-era `elicitationId` is not part of the 2026-07-28\n * URL-mode shape; correlation across retries is the server's own\n * identifier inside `requestState`.\n */\n elicitUrl(params: Omit<ElicitRequestURLParams, 'mode' | 'elicitationId'>): InputRequest;\n\n /** Builds an embedded sampling request (`sampling/createMessage`). */\n createMessage(params: CreateMessageRequestParams): InputRequest;\n\n /** Builds an embedded roots listing request (`roots/list`). */\n listRoots(): InputRequest;\n}\n\nfunction buildInputRequired(spec: InputRequiredSpec): InputRequiredResult {\n const hasInputRequests = spec.inputRequests !== undefined && Object.keys(spec.inputRequests).length > 0;\n const hasRequestState = typeof spec.requestState === 'string';\n if (!hasInputRequests && !hasRequestState) {\n throw new TypeError(\n 'inputRequired() requires at least one of inputRequests (with at least one entry) or requestState ' +\n '(spec: every InputRequiredResult MUST include at least one of the two)'\n );\n }\n return {\n resultType: 'input_required',\n ...(spec.inputRequests !== undefined && { inputRequests: spec.inputRequests }),\n ...(spec.requestState !== undefined && { requestState: spec.requestState })\n };\n}\n\n/**\n * Builder for the input-required return value of multi-round-trip handlers,\n * with per-kind constructors for the embedded requests\n * (`inputRequired.elicit`, `inputRequired.elicitUrl`,\n * `inputRequired.createMessage`, `inputRequired.listRoots`).\n *\n * @example Write-once tool requesting confirmation\n * ```ts\n * server.registerTool('deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => {\n * const confirmed = acceptedContent<{ confirm: boolean }>(ctx.mcpReq.inputResponses, 'confirm');\n * if (!confirmed) {\n * return inputRequired({\n * inputRequests: {\n * confirm: inputRequired.elicit({\n * message: `Deploy to ${env}?`,\n * requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean' } }, required: ['confirm'] }\n * })\n * }\n * });\n * }\n * return { content: [{ type: 'text', text: `deployed to ${env}` }] };\n * });\n * ```\n */\nexport const inputRequired: InputRequiredBuilder = Object.assign(buildInputRequired, {\n elicit(params: Omit<ElicitRequestFormParams, 'mode'> & { mode?: 'form' }): InputRequest {\n return { method: 'elicitation/create', params: { ...params, mode: 'form' } };\n },\n elicitUrl(params: Omit<ElicitRequestURLParams, 'mode' | 'elicitationId'>): InputRequest {\n // The neutral ElicitRequestURLParams keeps `elicitationId` (it is required on the\n // frozen 2025-11-25 revision); the 2026-07-28 in-band shape does not carry it.\n return { method: 'elicitation/create', params: { ...params, mode: 'url' } as ElicitRequestURLParams };\n },\n createMessage(params: CreateMessageRequestParams): InputRequest {\n return { method: 'sampling/createMessage', params };\n },\n listRoots(): InputRequest {\n return { method: 'roots/list' };\n }\n});\n\n/**\n * Reads the accepted content of a form-mode elicitation response from a\n * retried request's `inputResponses` (`ctx.mcpReq.inputResponses`).\n *\n * Returns the response's `content` for `key` when the entry is an accepted\n * elicitation result, and `undefined` otherwise (missing key, declined or\n * cancelled elicitation, or a response of another kind). The values arrive\n * from the client and are not re-validated here — treat them as untrusted\n * input.\n */\nexport function acceptedContent<T extends Record<string, unknown> = Record<string, unknown>>(\n responses: InputResponses | Record<string, unknown> | undefined,\n key: string\n): T | undefined;\n\n/**\n * Schema-aware overload: validates the accepted content against the given\n * schema (any Standard Schema, e.g. a zod object) before returning it, so the\n * untrusted client value arrives in the handler already validated and typed.\n *\n * Returns `undefined` when the response is missing/declined/of another kind\n * (as the two-argument form does) AND when the accepted content fails schema\n * validation — handlers treat both the same way (re-issue the request or\n * give up). Only synchronous schemas are supported (zod schemas without async\n * refinements are synchronous); an asynchronously-validating schema throws a\n * `TypeError`.\n */\nexport function acceptedContent<S extends StandardSchemaV1>(\n responses: InputResponses | Record<string, unknown> | undefined,\n key: string,\n schema: S\n): StandardSchemaV1.InferOutput<S> | undefined;\n\nexport function acceptedContent(\n responses: InputResponses | Record<string, unknown> | undefined,\n key: string,\n schema?: StandardSchemaV1\n): unknown {\n const view = inputResponse(responses, key);\n if (view.kind !== 'elicit' || view.action !== 'accept' || view.content === undefined) return undefined;\n if (schema === undefined) return view.content;\n const outcome = schema['~standard'].validate(view.content);\n if (outcome instanceof Promise) {\n throw new TypeError('acceptedContent(responses, key, schema) requires a synchronously-validating schema');\n }\n return outcome.issues === undefined ? outcome.value : undefined;\n}\n\n/**\n * The discriminated view {@linkcode inputResponse} returns: which kind of\n * embedded response (if any) a retried request carried for a key. Bare\n * response objects are discriminated structurally — an `action` member means\n * an elicitation result, a `roots` array a roots listing, a `role` + `content`\n * pair a sampling result. A missing key or an entry that matches none of the\n * three shapes reads as `{ kind: 'missing' }`.\n */\nexport type InputResponseView =\n | { kind: 'missing' }\n | { kind: 'elicit'; action: 'accept' | 'decline' | 'cancel'; content?: Record<string, unknown> }\n | { kind: 'sampling'; result: CreateMessageResult | CreateMessageResultWithTools }\n | { kind: 'roots'; roots: Root[] };\n\n/**\n * Reads one entry of a retried request's `inputResponses`\n * (`ctx.mcpReq.inputResponses`) as a discriminated view, covering\n * decline/cancel detection and the non-elicitation response kinds that\n * {@linkcode acceptedContent} does not surface.\n *\n * The values arrive from the client and are not re-validated here — treat\n * them as untrusted input (validate elicitation content with the\n * schema-aware {@linkcode acceptedContent} overload where it matters).\n */\nexport function inputResponse(responses: InputResponses | Record<string, unknown> | undefined, key: string): InputResponseView {\n if (responses === undefined || typeof responses !== 'object' || responses === null) return { kind: 'missing' };\n const entry = (responses as Record<string, unknown>)[key];\n if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return { kind: 'missing' };\n const candidate = entry as Record<string, unknown>;\n if (candidate['action'] === 'accept' || candidate['action'] === 'decline' || candidate['action'] === 'cancel') {\n const content = candidate['content'];\n return {\n kind: 'elicit',\n action: candidate['action'],\n ...(content !== null &&\n typeof content === 'object' &&\n !Array.isArray(content) && { content: content as Record<string, unknown> })\n };\n }\n if (Array.isArray(candidate['roots'])) {\n return { kind: 'roots', roots: candidate['roots'] as Root[] };\n }\n if (typeof candidate['role'] === 'string' && candidate['content'] !== undefined) {\n return { kind: 'sampling', result: candidate as unknown as CreateMessageResult | CreateMessageResultWithTools };\n }\n return { kind: 'missing' };\n}\n\n/**\n * Wraps a result schema so a request issued through `client.request()` /\n * `ctx.mcpReq.send()` with `allowInputRequired: true` is typed as either the\n * schema's result or an {@linkcode InputRequiredResult}.\n *\n * The manual multi-round-trip path: pass `{ allowInputRequired: true }` in the\n * request options so an `input_required` response is handed back to the\n * caller instead of being auto-fulfilled (or rejected), and wrap the result\n * schema with `withInputRequired()` so the returned value is typed and\n * validated correctly for both outcomes — `input_required` values pass\n * through as-is, complete results validate against the wrapped schema.\n */\nexport function withInputRequired<S extends StandardSchemaV1>(\n schema: S\n): StandardSchemaV1<unknown, StandardSchemaV1.InferOutput<S> | InputRequiredResult> {\n return {\n '~standard': {\n version: 1,\n vendor: 'modelcontextprotocol',\n validate: (value: unknown, options?: StandardSchemaV1.Options) => {\n if (isInputRequiredResult(value)) {\n return { value };\n }\n return schema['~standard'].validate(value, options) as\n | StandardSchemaV1.Result<StandardSchemaV1.InferOutput<S> | InputRequiredResult>\n | Promise<StandardSchemaV1.Result<StandardSchemaV1.InferOutput<S> | InputRequiredResult>>;\n }\n }\n };\n}\n","/**\n * The multi-round-trip auto-fulfilment driver (protocol revision 2026-07-28).\n *\n * When a request to one of the multi-round-trip methods comes back as\n * `input_required`, the driver fulfils the embedded input requests by\n * dispatching them to the client's already-registered handlers (elicitation,\n * sampling, roots — one generic engine, no per-feature API), then retries the\n * original request with the collected `inputResponses` and a byte-exact echo\n * of `requestState`, on a fresh request id, until the server returns a\n * complete result or the round cap is exhausted.\n *\n * The driver is a LAYER OVER THE MANUAL PATH: each retry is issued with the\n * same primitive a manual caller uses (`allowInputRequired` semantics — the\n * retry hands back the next `input_required` payload instead of recursing),\n * so the loop, the cap, and the pacing live in one place and disabling\n * auto-fulfilment (`inputRequired.autoFulfill: false`) simply skips this\n * module. Timeouts ride the EXISTING knobs: the per-leg `timeout` applies to\n * every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by\n * shrinking the budget passed to each leg — no new timer system.\n */\nimport { SdkError, SdkErrorCode } from '../errors/sdkErrors';\nimport { isInputRequiredResult } from '../types/guards';\nimport type { Progress } from '../types/types';\n\n/**\n * Whether the multi-round-trip driver fulfils `input_required` results\n * automatically when the consumer has not configured\n * `inputRequired.autoFulfill`. The single switch for the default posture.\n */\nexport const DEFAULT_INPUT_REQUIRED_AUTO_FULFILL = true;\n\n/**\n * Default round cap for the auto-fulfilment driver (both request legs and\n * requestState-only legs count). Aligned with the other SDK client engines.\n */\nexport const DEFAULT_INPUT_REQUIRED_MAX_ROUNDS = 10;\n\n/**\n * Fixed pacing applied before retrying a requestState-only (load-shedding)\n * leg — a leg that carries no embedded input requests, so nothing slows the\n * loop down naturally. Counted in the same round cap.\n */\nexport const REQUEST_STATE_ONLY_LEG_PACING_MS = 250;\n\n/**\n * Multi-round-trip driver options (`inputRequired` on the client options bag).\n */\nexport interface InputRequiredOptions {\n /**\n * Fulfil `input_required` results automatically by dispatching the\n * embedded requests to the registered handlers and retrying.\n *\n * Set to `false` for manual mode: an `input_required` response then\n * surfaces as a typed error unless the individual call opts in with\n * `allowInputRequired: true` (and, for typed results on the explicit\n * schema path, `withInputRequired()`).\n *\n * @default true\n */\n autoFulfill?: boolean;\n\n /**\n * Maximum number of rounds (retries) the driver performs for a single\n * call before failing with a typed\n * {@linkcode SdkErrorCode.InputRequiredRoundsExceeded} error.\n *\n * @default 10\n */\n maxRounds?: number;\n}\n\n/** The driver configuration with defaults applied. */\nexport interface ResolvedInputRequiredDriverConfig {\n autoFulfill: boolean;\n maxRounds: number;\n}\n\nexport function resolveInputRequiredDriverConfig(options: InputRequiredOptions | undefined): ResolvedInputRequiredDriverConfig {\n return {\n autoFulfill: options?.autoFulfill ?? DEFAULT_INPUT_REQUIRED_AUTO_FULFILL,\n maxRounds: options?.maxRounds ?? DEFAULT_INPUT_REQUIRED_MAX_ROUNDS\n };\n}\n\n/** The discriminated `input_required` payload the wire codec hands to the driver. */\nexport interface InputRequiredPayload {\n inputRequests: Record<string, unknown>;\n requestState?: string;\n}\n\n/** The slice of per-request options the driver consumes. */\nexport interface InputRequiredDriverRequestOptions {\n timeout?: number;\n maxTotalTimeout?: number;\n onprogress?: (progress: Progress) => void;\n}\n\n/** Per-leg options the driver passes back to the funnel for each retry. */\nexport interface InputRequiredRetryLegOptions {\n timeout?: number;\n maxTotalTimeout?: number;\n}\n\n/** The hooks the engine provides to the driver. */\nexport interface InputRequiredDriverHooks {\n /**\n * Dispatches one embedded input request to the locally registered handler\n * and resolves with the bare response value. Rejections fail the whole\n * call (typed errors: unknown kind, missing handler, handler failure).\n * The signal is the per-round abort: when one sibling fails (or the\n * caller aborts the originating call) the remaining dispatches are\n * cancelled.\n */\n dispatchInputRequest(key: string, entry: unknown, signal: AbortSignal): Promise<unknown>;\n\n /**\n * Re-issues the original request with the given params on a fresh request\n * id, using the manual primitive: a complete result resolves validated,\n * and a further `input_required` response resolves as the raw\n * input-required value (never recursing into another driver run).\n */\n retry(params: Record<string, unknown> | undefined, legOptions: InputRequiredRetryLegOptions): Promise<unknown>;\n}\n\n/** Builds the retry params: original params + this round's responses + byte-exact requestState echo. */\nexport function buildInputRequiredRetryParams(\n originalParams: Record<string, unknown> | undefined,\n responses: Record<string, unknown> | undefined,\n requestState: string | undefined\n): Record<string, unknown> | undefined {\n const hasResponses = responses !== undefined && Object.keys(responses).length > 0;\n if (!hasResponses && requestState === undefined) {\n return originalParams;\n }\n return {\n ...originalParams,\n ...(hasResponses && { inputResponses: responses }),\n // Byte-exact echo: the opaque string is copied verbatim, never parsed.\n // When the result carried no requestState, the retry carries none.\n ...(requestState !== undefined && { requestState })\n };\n}\n\n/**\n * The message both multi-round-trip loops emit when the round cap is\n * exhausted — the client driver as a typed error, the server-side legacy\n * shim as its per-family failure. One formatter so the texts cannot drift\n * (hosts and models read the tool-result copy verbatim).\n */\nexport function inputRequiredRoundsExceededMessage(method: string, maxRounds: number): string {\n return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;\n}\n\n/**\n * Abortable delay: resolves after `ms`, or rejects with the signal's reason\n * (wrapped in an `SdkError` when it isn't already one) if the signal aborts\n * first. Aborting after resolution is a no-op. Shared with the server-side\n * legacy shim (the pacing semantics must match per era).\n */\nexport function sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal.reason)));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(signal?.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal?.reason)));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/**\n * A per-round abort linked to the caller's signal: the embedded sibling\n * dispatches share it, so the first failure (or a caller abort) cancels the\n * others instead of leaving them running. Shared with the server-side legacy\n * shim (the abort-linkage semantics must match per era).\n */\nexport function linkedRoundAbort(outer: AbortSignal | undefined): {\n signal: AbortSignal;\n abort: (reason: unknown) => void;\n dispose: () => void;\n} {\n const controller = new AbortController();\n const onOuterAbort = (): void => controller.abort(outer?.reason);\n outer?.addEventListener('abort', onOuterAbort, { once: true });\n if (outer?.aborted) controller.abort(outer.reason);\n return {\n signal: controller.signal,\n abort: reason => controller.abort(reason),\n dispose: () => outer?.removeEventListener('abort', onOuterAbort)\n };\n}\n\n/**\n * Runs the auto-fulfilment loop for one originating request. Resolves with\n * the final complete result (already validated by the retry leg) or rejects\n * with a typed error.\n *\n * `flowStartedAt` is the timestamp the ORIGINAL request was issued at (not\n * when the driver started): `maxTotalTimeout` bounds the whole flow, so the\n * first wire leg counts against the budget too. When omitted, accounting\n * starts when the driver starts.\n */\nexport async function runInputRequiredDriver(args: {\n config: ResolvedInputRequiredDriverConfig;\n method: string;\n originalParams: Record<string, unknown> | undefined;\n firstPayload: InputRequiredPayload;\n requestOptions: InputRequiredDriverRequestOptions;\n hooks: InputRequiredDriverHooks;\n /** The originating call's abort signal — chains through every round and the pacing sleep. */\n signal?: AbortSignal;\n flowStartedAt?: number;\n}): Promise<unknown> {\n const { config, method, originalParams, requestOptions, hooks, signal } = args;\n const startedAt = args.flowStartedAt ?? Date.now();\n let payload = args.firstPayload;\n let round = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n round += 1;\n if (round > config.maxRounds) {\n throw new SdkError(SdkErrorCode.InputRequiredRoundsExceeded, inputRequiredRoundsExceededMessage(method, config.maxRounds), {\n rounds: config.maxRounds,\n lastResult: {\n inputRequests: payload.inputRequests,\n ...(payload.requestState !== undefined && { requestState: payload.requestState })\n }\n });\n }\n\n // Surface the round as synthetic progress: long interactive flows stay\n // observable, and consumers composing `resetTimeoutOnProgress`-style\n // watchdogs around the call see liveness instead of silence.\n requestOptions.onprogress?.({ progress: round, message: `Fulfilling input required by '${method}' (round ${round})` });\n\n const entries = Object.entries(payload.inputRequests ?? {});\n let responses: Record<string, unknown> | undefined;\n if (entries.length > 0) {\n // Fulfil concurrently (the embedded requests are independent); a\n // single failure fails the call AND aborts the siblings via the\n // linked per-round signal so they do not keep running.\n const round = linkedRoundAbort(signal);\n try {\n const fulfilled = await Promise.all(\n entries.map(async ([key, entry]) => {\n try {\n return [key, await hooks.dispatchInputRequest(key, entry, round.signal)] as const;\n } catch (error) {\n round.abort(error);\n throw error;\n }\n })\n );\n responses = Object.fromEntries(fulfilled);\n } finally {\n round.dispose();\n }\n } else {\n // requestState-only (load-shedding) leg: fixed pacing so the loop\n // never hot-spins; counted in the same round cap. The sleep\n // honors the caller's abort signal.\n await sleep(REQUEST_STATE_ONLY_LEG_PACING_MS, signal);\n }\n\n const legOptions: InputRequiredRetryLegOptions = {\n ...(requestOptions.timeout !== undefined && { timeout: requestOptions.timeout })\n };\n if (requestOptions.maxTotalTimeout !== undefined) {\n const totalElapsed = Date.now() - startedAt;\n const remaining = requestOptions.maxTotalTimeout - totalElapsed;\n if (remaining <= 0) {\n throw new SdkError(SdkErrorCode.RequestTimeout, 'Maximum total timeout exceeded', {\n maxTotalTimeout: requestOptions.maxTotalTimeout,\n totalElapsed\n });\n }\n legOptions.maxTotalTimeout = remaining;\n }\n\n const result = await hooks.retry(buildInputRequiredRetryParams(originalParams, responses, payload.requestState), legOptions);\n if (isInputRequiredResult(result)) {\n payload = {\n inputRequests: result.inputRequests ?? {},\n ...(result.requestState !== undefined && { requestState: result.requestState })\n };\n continue;\n }\n return result;\n }\n}\n","import type * as z from 'zod/v4';\n\nimport {\n IdJagTokenExchangeResponseSchema,\n OAuthClientInformationFullSchema,\n OAuthClientInformationSchema,\n OAuthClientMetadataSchema,\n OAuthClientRegistrationErrorSchema,\n OAuthErrorResponseSchema,\n OAuthMetadataSchema,\n OAuthProtectedResourceMetadataSchema,\n OAuthTokenRevocationRequestSchema,\n OAuthTokensSchema,\n OpenIdProviderDiscoveryMetadataSchema,\n OpenIdProviderMetadataSchema\n} from '../shared/auth';\nimport type { StandardSchemaV1, StandardSchemaV1Sync } from '../util/standardSchema';\nimport * as schemas from './schemas';\n\n/**\n * Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`.\n *\n * This intentionally excludes internal helper schemas exported from `schemas.ts` that have no\n * matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`,\n * `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`).\n * Keeping the list explicit means new public spec types must be added here deliberately, and\n * internals never leak into `SpecTypeName`.\n *\n * `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType`\n * (the bare name collides with the server package's `ResourceTemplate` class), so\n * `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to\n * a type literally named `ResourceTemplate`.\n */\nconst SPEC_SCHEMA_KEYS = [\n 'AnnotationsSchema',\n 'AudioContentSchema',\n 'BaseMetadataSchema',\n 'BlobResourceContentsSchema',\n 'BooleanSchemaSchema',\n 'CallToolRequestSchema',\n 'CallToolRequestParamsSchema',\n 'CallToolResultSchema',\n 'CancelledNotificationSchema',\n 'CancelledNotificationParamsSchema',\n 'CancelTaskRequestSchema',\n 'CancelTaskResultSchema',\n 'ClientCapabilitiesSchema',\n 'ClientNotificationSchema',\n 'ClientRequestSchema',\n 'ClientResultSchema',\n 'CompatibilityCallToolResultSchema',\n 'CompleteRequestSchema',\n 'CompleteRequestParamsSchema',\n 'CompleteResultSchema',\n 'ContentBlockSchema',\n 'CreateMessageRequestSchema',\n 'CreateMessageRequestParamsSchema',\n 'CreateMessageResultSchema',\n 'CreateMessageResultWithToolsSchema',\n 'CreateTaskResultSchema',\n 'CursorSchema',\n 'DiscoverRequestSchema',\n 'DiscoverResultSchema',\n 'ElicitationCompleteNotificationSchema',\n 'ElicitationCompleteNotificationParamsSchema',\n 'ElicitRequestSchema',\n 'ElicitRequestFormParamsSchema',\n 'ElicitRequestParamsSchema',\n 'ElicitRequestURLParamsSchema',\n 'ElicitResultSchema',\n 'EmbeddedResourceSchema',\n 'EmptyResultSchema',\n 'EnumSchemaSchema',\n 'GetPromptRequestSchema',\n 'GetPromptRequestParamsSchema',\n 'GetPromptResultSchema',\n 'GetTaskPayloadRequestSchema',\n 'GetTaskPayloadResultSchema',\n 'GetTaskRequestSchema',\n 'GetTaskResultSchema',\n 'IconSchema',\n 'IconsSchema',\n 'ImageContentSchema',\n 'ImplementationSchema',\n 'InitializedNotificationSchema',\n 'InitializeRequestSchema',\n 'InitializeRequestParamsSchema',\n 'InitializeResultSchema',\n 'JSONArraySchema',\n 'JSONObjectSchema',\n 'JSONRPCErrorResponseSchema',\n 'JSONRPCMessageSchema',\n 'JSONRPCNotificationSchema',\n 'JSONRPCRequestSchema',\n 'JSONRPCResponseSchema',\n 'JSONRPCResultResponseSchema',\n 'JSONValueSchema',\n 'LegacyTitledEnumSchemaSchema',\n 'ListPromptsRequestSchema',\n 'ListPromptsResultSchema',\n 'ListResourcesRequestSchema',\n 'ListResourcesResultSchema',\n 'ListResourceTemplatesRequestSchema',\n 'ListResourceTemplatesResultSchema',\n 'ListRootsRequestSchema',\n 'ListRootsResultSchema',\n 'ListTasksRequestSchema',\n 'ListTasksResultSchema',\n 'ListToolsRequestSchema',\n 'ListToolsResultSchema',\n 'LoggingLevelSchema',\n 'LoggingMessageNotificationSchema',\n 'LoggingMessageNotificationParamsSchema',\n 'ModelHintSchema',\n 'ModelPreferencesSchema',\n 'MultiSelectEnumSchemaSchema',\n 'NotificationSchema',\n 'NumberSchemaSchema',\n 'PaginatedRequestSchema',\n 'PaginatedRequestParamsSchema',\n 'PaginatedResultSchema',\n 'PingRequestSchema',\n 'PrimitiveSchemaDefinitionSchema',\n 'ProgressSchema',\n 'ProgressNotificationSchema',\n 'ProgressNotificationParamsSchema',\n 'ProgressTokenSchema',\n 'PromptSchema',\n 'PromptArgumentSchema',\n 'PromptListChangedNotificationSchema',\n 'PromptMessageSchema',\n 'PromptReferenceSchema',\n 'ReadResourceRequestSchema',\n 'ReadResourceRequestParamsSchema',\n 'ReadResourceResultSchema',\n 'RelatedTaskMetadataSchema',\n 'RequestSchema',\n 'RequestIdSchema',\n 'RequestMetaSchema',\n 'ResourceSchema',\n 'ResourceContentsSchema',\n 'ResourceLinkSchema',\n 'ResourceListChangedNotificationSchema',\n 'ResourceRequestParamsSchema',\n 'ResourceTemplateSchema',\n 'ResourceTemplateReferenceSchema',\n 'ResourceUpdatedNotificationSchema',\n 'ResourceUpdatedNotificationParamsSchema',\n 'ResultSchema',\n 'RoleSchema',\n 'RootSchema',\n 'RootsListChangedNotificationSchema',\n 'SamplingContentSchema',\n 'SamplingMessageSchema',\n 'SamplingMessageContentBlockSchema',\n 'ServerCapabilitiesSchema',\n 'ServerNotificationSchema',\n 'ServerRequestSchema',\n 'ServerResultSchema',\n 'SetLevelRequestSchema',\n 'SetLevelRequestParamsSchema',\n 'SingleSelectEnumSchemaSchema',\n 'StringSchemaSchema',\n 'SubscribeRequestSchema',\n 'SubscribeRequestParamsSchema',\n 'SubscriptionFilterSchema',\n 'SubscriptionsAcknowledgedNotificationSchema',\n 'SubscriptionsAcknowledgedNotificationParamsSchema',\n 'SubscriptionsListenRequestSchema',\n 'SubscriptionsListenRequestParamsSchema',\n 'SubscriptionsListenResultSchema',\n 'SubscriptionsListenResultMetaSchema',\n 'TaskAugmentedRequestParamsSchema',\n 'TaskCreationParamsSchema',\n 'TaskMetadataSchema',\n 'TaskSchema',\n 'TaskStatusSchema',\n 'TaskStatusNotificationSchema',\n 'TaskStatusNotificationParamsSchema',\n 'TextContentSchema',\n 'TextResourceContentsSchema',\n 'TitledMultiSelectEnumSchemaSchema',\n 'TitledSingleSelectEnumSchemaSchema',\n 'ToolSchema',\n 'ToolAnnotationsSchema',\n 'ToolChoiceSchema',\n 'ToolExecutionSchema',\n 'ToolListChangedNotificationSchema',\n 'ToolResultContentSchema',\n 'ToolUseContentSchema',\n 'UnsubscribeRequestSchema',\n 'UnsubscribeRequestParamsSchema',\n 'UntitledMultiSelectEnumSchemaSchema',\n 'UntitledSingleSelectEnumSchemaSchema'\n] as const satisfies readonly (keyof typeof schemas)[];\n\nconst authSchemas = {\n IdJagTokenExchangeResponseSchema,\n OAuthClientInformationFullSchema,\n OAuthClientInformationSchema,\n OAuthClientMetadataSchema,\n OAuthClientRegistrationErrorSchema,\n OAuthErrorResponseSchema,\n OAuthMetadataSchema,\n OAuthProtectedResourceMetadataSchema,\n OAuthTokenRevocationRequestSchema,\n OAuthTokensSchema,\n OpenIdProviderDiscoveryMetadataSchema,\n OpenIdProviderMetadataSchema\n} as const;\n\ntype ProtocolSchemaKey = (typeof SPEC_SCHEMA_KEYS)[number];\ntype AuthSchemaKey = keyof typeof authSchemas;\ntype SchemaKey = ProtocolSchemaKey | AuthSchemaKey;\n\ntype SchemaFor<K extends SchemaKey> = K extends ProtocolSchemaKey\n ? (typeof schemas)[K]\n : K extends AuthSchemaKey\n ? (typeof authSchemas)[K]\n : never;\n\ntype StripSchemaSuffix<K> = K extends `${infer N}Schema` ? N : never;\n\n/**\n * Union of every named type in the SDK's protocol and OAuth schemas (e.g. `'CallToolResult'`,\n * `'ContentBlock'`, `'Tool'`, `'OAuthTokens'`). Derived from the internal Zod schemas, so it stays\n * in sync with the spec.\n */\nexport type SpecTypeName = StripSchemaSuffix<SchemaKey>;\n\n/**\n * Maps each {@linkcode SpecTypeName} to its TypeScript type.\n *\n * `SpecTypes['Tool']` is equivalent to importing the `Tool` type directly.\n * These validators cover the NEUTRAL model — the consumer-facing shapes with\n * no wire-only members (`resultType`, the reserved `_meta` envelope keys).\n * Per-revision WIRE validators are deliberately not public surface; they are\n * planned to return as versioned `zod-schemas/<revision>` exports for\n * consumers who validate raw wire traffic themselves.\n */\nexport type SpecTypes = {\n [K in SchemaKey as StripSchemaSuffix<K>]: SchemaFor<K> extends z.ZodType ? z.output<SchemaFor<K>> : never;\n};\n\n/**\n * Input shape for each {@linkcode SpecTypeName}. For most types this equals {@linkcode SpecTypes},\n * but a few schemas apply defaults/preprocessing, so the accepted input may be looser than the\n * resulting output type.\n */\ntype SpecTypeInputs = {\n [K in SchemaKey as StripSchemaSuffix<K>]: SchemaFor<K> extends z.ZodType ? z.input<SchemaFor<K>> : never;\n};\n\ntype SchemaRecord = { readonly [K in SpecTypeName]: StandardSchemaV1Sync<SpecTypeInputs[K], SpecTypes[K]> };\ntype GuardRecord = { readonly [K in SpecTypeName]: (value: unknown) => value is SpecTypeInputs[K] };\n\nconst _specTypeSchemas: Record<string, StandardSchemaV1> = {};\nconst _isSpecType: Record<string, (value: unknown) => boolean> = {};\nfunction register(key: string, schema: z.ZodType): void {\n const name = key.slice(0, -'Schema'.length);\n _specTypeSchemas[name] = schema;\n _isSpecType[name] = (v: unknown) => schema.safeParse(v).success;\n}\nfor (const key of SPEC_SCHEMA_KEYS) {\n // eslint-disable-next-line import/namespace -- key is constrained to keyof typeof schemas via the satisfies clause above\n register(key, schemas[key]);\n}\nfor (const [key, schema] of Object.entries(authSchemas)) {\n register(key, schema);\n}\n\n/**\n * Runtime validators for every MCP spec type, keyed by type name.\n *\n * Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for\n * example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from\n * storage that should be a `Tool`.\n *\n * Each entry implements the Standard Schema interface, so it composes with any\n * Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead.\n *\n * @example\n * ```ts source=\"./specTypeSchema.examples.ts#specTypeSchemas_basicUsage\"\n * const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted);\n * if (result.issues === undefined) {\n * // result.value is CallToolResult\n * }\n * ```\n */\nexport const specTypeSchemas: SchemaRecord = Object.freeze(_specTypeSchemas as SchemaRecord);\n\n/**\n * Type predicates for every MCP spec type, keyed by type name.\n *\n * Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and\n * transforms are applied), and narrows to that input type. For schemas with `.default()` or\n * `.preprocess()`, this may accept values that do not structurally match the named output type;\n * for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use\n * `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value.\n *\n * Each guard is a standalone function, so it can be passed directly as a callback.\n *\n * @example\n * ```ts source=\"./specTypeSchema.examples.ts#isSpecType_basicUsage\"\n * if (isSpecType.ContentBlock(value)) {\n * // value is ContentBlock\n * }\n *\n * const blocks = mixed.filter(isSpecType.ContentBlock);\n * ```\n */\nexport const isSpecType: GuardRecord = Object.freeze(_isSpecType as GuardRecord);\n","/**\n * Standard Schema utilities for user-provided schemas.\n * Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations.\n * @see https://standardschema.dev\n */\n\n/* eslint-disable @typescript-eslint/no-namespace */\n\nimport * as z from 'zod/v4';\n\n// Standard Schema interfaces — vendored from https://standardschema.dev (spec v1, Jan 2025)\n\nexport interface StandardTypedV1<Input = unknown, Output = Input> {\n readonly '~standard': StandardTypedV1.Props<Input, Output>;\n}\n\nexport namespace StandardTypedV1 {\n export interface Props<Input = unknown, Output = Input> {\n readonly version: 1;\n readonly vendor: string;\n readonly types?: Types<Input, Output> | undefined;\n }\n\n export interface Types<Input = unknown, Output = Input> {\n readonly input: Input;\n readonly output: Output;\n }\n\n export type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema['~standard']['types']>['input'];\n export type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema['~standard']['types']>['output'];\n}\n\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n readonly '~standard': StandardSchemaV1.Props<Input, Output>;\n}\n\nexport namespace StandardSchemaV1 {\n export interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {\n readonly validate: (value: unknown, options?: Options | undefined) => Result<Output> | Promise<Result<Output>>;\n }\n\n export interface Options {\n readonly libraryOptions?: Record<string, unknown> | undefined;\n }\n\n export type Result<Output> = SuccessResult<Output> | FailureResult;\n\n export interface SuccessResult<Output> {\n readonly value: Output;\n readonly issues?: undefined;\n }\n\n export interface FailureResult {\n readonly issues: ReadonlyArray<Issue>;\n }\n\n export interface Issue {\n readonly message: string;\n readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;\n }\n\n export interface PathSegment {\n readonly key: PropertyKey;\n }\n\n export type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;\n export type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;\n}\n\nexport interface StandardJSONSchemaV1<Input = unknown, Output = Input> {\n readonly '~standard': StandardJSONSchemaV1.Props<Input, Output>;\n}\n\nexport namespace StandardJSONSchemaV1 {\n export interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {\n readonly jsonSchema: Converter;\n }\n\n export interface Converter {\n readonly input: (options: Options) => Record<string, unknown>;\n readonly output: (options: Options) => Record<string, unknown>;\n }\n\n export type Target = 'draft-2020-12' | 'draft-07' | 'openapi-3.0' | (object & string);\n\n export interface Options {\n readonly target: Target;\n readonly libraryOptions?: Record<string, unknown> | undefined;\n }\n\n export type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;\n export type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;\n}\n\n/**\n * Combined interface for schemas with both validation and JSON Schema conversion —\n * the intersection of {@linkcode StandardSchemaV1} and {@linkcode StandardJSONSchemaV1}.\n *\n * This is the type accepted by `registerTool` / `registerPrompt`. The SDK needs\n * `~standard.jsonSchema` to advertise the tool's argument shape in `tools/list`, and\n * `~standard.validate` to check incoming arguments when a `tools/call` arrives.\n *\n * Zod v4, ArkType, and Valibot (via `@valibot/to-json-schema`'s `toStandardJsonSchema`)\n * all implement both interfaces.\n *\n * @see https://standardschema.dev/ for the Standard Schema specification\n */\nexport interface StandardSchemaWithJSON<Input = unknown, Output = Input> {\n readonly '~standard': StandardSchemaV1.Props<Input, Output> & StandardJSONSchemaV1.Props<Input, Output>;\n}\n\nexport namespace StandardSchemaWithJSON {\n export type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;\n export type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;\n}\n\n/**\n * Narrowing of {@linkcode StandardSchemaV1} whose `validate` is guaranteed synchronous.\n *\n * The Zod schemas backing `specTypeSchemas` contain no async refinements or transforms,\n * so every entry satisfies this interface. Consumers can call `validate()` and access\n * `.issues` / `.value` on the result without `await`.\n *\n * `StandardSchemaV1Sync` is assignable to `StandardSchemaV1` — it is a strict subtype.\n */\nexport interface StandardSchemaV1Sync<Input = unknown, Output = Input> extends StandardSchemaV1<Input, Output> {\n readonly '~standard': StandardSchemaV1Sync.Props<Input, Output>;\n}\n\nexport namespace StandardSchemaV1Sync {\n export interface Props<Input = unknown, Output = Input> extends StandardSchemaV1.Props<Input, Output> {\n readonly validate: (value: unknown, options?: StandardSchemaV1.Options | undefined) => StandardSchemaV1.Result<Output>;\n }\n\n export type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;\n export type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;\n}\n\n// Type guards\n\nexport function isStandardJSONSchema(schema: unknown): schema is StandardJSONSchemaV1 {\n if (schema == null) return false;\n const schemaType = typeof schema;\n if (schemaType !== 'object' && schemaType !== 'function') return false;\n if (!('~standard' in (schema as object))) return false;\n const std = (schema as StandardJSONSchemaV1)['~standard'];\n return typeof std?.jsonSchema?.input === 'function' && typeof std?.jsonSchema?.output === 'function';\n}\n\nexport function isStandardSchema(schema: unknown): schema is StandardSchemaV1 {\n if (schema == null) return false;\n const schemaType = typeof schema;\n if (schemaType !== 'object' && schemaType !== 'function') return false;\n if (!('~standard' in (schema as object))) return false;\n const std = (schema as StandardSchemaV1)['~standard'];\n return typeof std?.validate === 'function';\n}\n\nexport function isStandardSchemaWithJSON(schema: unknown): schema is StandardSchemaWithJSON {\n return isStandardJSONSchema(schema) && isStandardSchema(schema);\n}\n\n// JSON Schema conversion\n\nlet warnedZodFallback = false;\n\n/**\n * Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema.\n *\n * MCP requires `type: \"object\"` at the root of tool `inputSchema` and prompt\n * argument schemas; `outputSchema` may have any JSON Schema root (SEP-2106).\n * Zod's discriminated unions emit `{oneOf: [...]}` without a top-level `type`,\n * so for `io: 'input'` this function defaults `type` to `\"object\"` when absent\n * and throws on an explicit non-object `type` (e.g. `z.string()`). For\n * `io: 'output'` a non-object root is returned as-is; the `\"object\"` default is\n * applied only when the root is provably object-shaped.\n */\nexport function standardSchemaToJsonSchema(schema: StandardJSONSchemaV1, io: 'input' | 'output' = 'input'): Record<string, unknown> {\n const std = schema['~standard'];\n let result: Record<string, unknown>;\n if (std.jsonSchema) {\n result = std.jsonSchema[io]({ target: 'draft-2020-12' });\n } else if (std.vendor === 'zod') {\n // zod 4.0–4.1 implements StandardSchemaV1 but not StandardJSONSchemaV1 (`~standard.jsonSchema`).\n // The SDK already bundles zod 4, so fall back to its converter rather than crashing on tools/list.\n // zod 3 schemas (which also report vendor 'zod') have `_def` but not `_zod`; the SDK-bundled\n // zod 4 `z.toJSONSchema()` cannot introspect them, so throw a clear error instead of crashing.\n if (!('_zod' in (schema as object))) {\n throw new Error(\n 'Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. ' +\n 'Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().'\n );\n }\n if (!warnedZodFallback) {\n warnedZodFallback = true;\n console.warn(\n '[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). ' +\n 'Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.'\n );\n }\n result = z.toJSONSchema(schema as unknown as z.ZodType, { target: 'draft-2020-12', io }) as Record<string, unknown>;\n } else {\n throw new Error(\n `Schema library \"${std.vendor}\" does not implement StandardJSONSchemaV1 (\\`~standard.jsonSchema\\`). ` +\n `Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`\n );\n }\n if (io === 'output') {\n // SEP-2106: outputSchema may have any JSON Schema root. An explicit `type` (object or\n // not) is returned as-is. A typeless root only gets `type:'object'` defaulted when it is\n // PROVABLY object-shaped — either it carries object keywords at the root, or every\n // member of a root `oneOf`/`anyOf`/`allOf` is itself `type:'object'` (the\n // `z.discriminatedUnion(...)`, `z.union([z.object(...), ...])`, `z.intersection(...)`\n // cases). Those pre-SEP schemas were valid 2025 wire data via the unconditional stamp,\n // so the stamp is kept where it is provably safe. A typeless root that is NOT provably\n // object-shaped (e.g. `z.union([z.string(), z.number()])` → `{anyOf:[…]}`) is returned\n // as-is — stamping there would be self-contradictory. Anything that does not end up\n // `type:'object'` is wrapped as `{type:'object', properties:{result:…}}` by the 2025\n // codec's legacy projection (see `wire/rev2025-11-25/legacyWrap.ts`).\n if (result.type !== undefined) return result;\n return isProvablyObjectShapedRoot(result) ? { type: 'object', ...result } : result;\n }\n if (result.type !== undefined && result.type !== 'object') {\n throw new Error(\n `MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). ` +\n `Wrap your schema in z.object({...}) or equivalent.`\n );\n }\n return { type: 'object', ...result };\n}\n\n/**\n * A typeless JSON Schema root is \"provably object-shaped\" when either it carries object keywords\n * directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a\n * composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively\n * provably object-shaped (e.g. a nested `discriminatedUnion`). `$ref` is not followed. Used to\n * decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory.\n */\nfunction isProvablyObjectShapedRoot(schema: Record<string, unknown>): boolean {\n if ('properties' in schema || 'patternProperties' in schema || 'additionalProperties' in schema || 'required' in schema) {\n return true;\n }\n for (const key of ['oneOf', 'anyOf', 'allOf'] as const) {\n const members = schema[key];\n if (Array.isArray(members) && members.length > 0) {\n return members.every(\n m =>\n m !== null &&\n typeof m === 'object' &&\n ((m as Record<string, unknown>).type === 'object' || isProvablyObjectShapedRoot(m as Record<string, unknown>))\n );\n }\n }\n return false;\n}\n\n// Validation\n\nexport type StandardSchemaValidationResult<T> = { success: true; data: T } | { success: false; error: string };\n\nfunction formatIssue(issue: StandardSchemaV1.Issue): string {\n if (!issue.path?.length) return issue.message;\n const path = issue.path.map(p => String(typeof p === 'object' ? p.key : p)).join('.');\n return `${path}: ${issue.message}`;\n}\n\nexport async function validateStandardSchema<T extends StandardSchemaV1>(\n schema: T,\n data: unknown\n): Promise<StandardSchemaValidationResult<StandardSchemaV1.InferOutput<T>>> {\n const result = await schema['~standard'].validate(data);\n if (result.issues && result.issues.length > 0) {\n return { success: false, error: result.issues.map(i => formatIssue(i)).join(', ') };\n }\n return { success: true, data: (result as StandardSchemaV1.SuccessResult<unknown>).value as StandardSchemaV1.InferOutput<T> };\n}\n\n// Prompt argument extraction\n\nexport function promptArgumentsFromStandardSchema(\n schema: StandardJSONSchemaV1\n): Array<{ name: string; description?: string; required: boolean }> {\n const jsonSchema = standardSchemaToJsonSchema(schema, 'input');\n const properties = (jsonSchema.properties as Record<string, { description?: string }>) || {};\n const required = (jsonSchema.required as string[]) || [];\n\n return Object.entries(properties).map(([name, prop]) => ({\n name,\n description: prop?.description,\n required: required.includes(name)\n }));\n}\n","/**\n * Static era pins for lifecycle messages on the OUTBOUND path (the\n * chicken-and-egg bootstrap): these messages are sent while the instance's\n * negotiated protocol version is still unset, and they self-identify their\n * era by construction — `initialize`/`notifications/initialized` ARE the\n * legacy handshake (`initialize` ⇒ legacy), and `server/discover` exists only\n * on the 2026 era. The pins apply only during that pre-negotiation window\n * (`Protocol._resolveOutboundCodec` consults them when the negotiated version\n * is `undefined`); once a version is negotiated, every send resolves through\n * the instance's era.\n *\n * Scope notes:\n * - OUTBOUND ONLY. Inbound era truth is the instance's negotiated protocol\n * version (connection state); an edge classification, when present, is\n * VALIDATED against that instance era — never used to pick a codec per\n * message — so pinning inbound would have nothing to attach to. An\n * inbound `server/discover` on a legacy-era instance correctly falls to\n * −32601 by registry absence; serving it requires an instance bound to\n * the modern era.\n * - `ping` is deliberately NOT pinned. A bare `{method: 'ping'}` carries no\n * era marker, and pinning it would let a negotiated-modern session emit a\n * 2025-only method onto the modern leg (the exact inverse leak registry\n * membership exists to prevent). `ping` era-gates like any other method:\n * present on the 2025 era, absent from the 2026 era (the modern keepalive\n * story is owned by the negotiation milestones).\n */\nimport type { WireCodec } from './codec';\nimport { codecForVersion, MODERN_WIRE_REVISION } from './codec';\n\nexport function bootstrapOutboundCodec(method: string): WireCodec | undefined {\n switch (method) {\n case 'initialize':\n case 'notifications/initialized': {\n // The legacy handshake, by definition (Q2).\n return codecForVersion(undefined);\n }\n case 'server/discover': {\n // The modern discovery exchange, 2026-era only.\n return codecForVersion(MODERN_WIRE_REVISION);\n }\n default: {\n return undefined;\n }\n }\n}\n","import { SdkError, SdkErrorCode } from '../errors/sdkErrors';\nimport type {\n AuthInfo,\n CancelledNotification,\n ClientCapabilities,\n CreateMessageRequest,\n CreateMessageResult,\n CreateMessageResultWithTools,\n ElicitRequestFormParams,\n ElicitRequestURLParams,\n ElicitResult,\n HandlerResultTypeMap,\n JSONRPCErrorResponse,\n JSONRPCNotification,\n JSONRPCRequest,\n JSONRPCResponse,\n JSONRPCResultResponse,\n LoggingLevel,\n MessageExtraInfo,\n Notification,\n NotificationMethod,\n NotificationTypeMap,\n Progress,\n ProgressNotification,\n Request,\n RequestId,\n RequestMeta,\n RequestMetaEnvelope,\n RequestMethod,\n RequestTypeMap,\n Result,\n ResultTypeMap,\n ServerCapabilities\n} from '../types/index';\nimport {\n CLIENT_CAPABILITIES_META_KEY,\n CLIENT_INFO_META_KEY,\n isJSONRPCErrorResponse,\n isJSONRPCNotification,\n isJSONRPCRequest,\n isJSONRPCResultResponse,\n LOG_LEVEL_META_KEY,\n PROTOCOL_VERSION_META_KEY,\n ProtocolError,\n ProtocolErrorCode,\n SUPPORTED_PROTOCOL_VERSIONS\n} from '../types/index';\nimport type { StandardSchemaV1 } from '../util/standardSchema';\nimport { isStandardSchema, validateStandardSchema } from '../util/standardSchema';\nimport { bootstrapOutboundCodec } from '../wire/bootstrap';\nimport type { LiftedWireMaterial, WireCodec } from '../wire/codec';\nimport { classifiedWireEra, codecForVersion, isSpecNotificationMethod, isSpecRequestMethod, MODERN_WIRE_REVISION } from '../wire/codec';\nimport { manualInputRequiredValue, partitionInputResponses } from './inputRequiredEngine';\nimport type { Transport, TransportSendOptions } from './transport';\n\n/**\n * Callback for progress notifications.\n */\nexport type ProgressCallback = (progress: Progress) => void;\n\n/**\n * Additional initialization options.\n */\nexport type ProtocolOptions = {\n /**\n * Protocol versions supported. The legacy `initialize` handshake offers and\n * falls back to the first 2025-era entry in the list (the client sends it,\n * the server counter-offers it); 2026-era entries are only ever selected via\n * `server/discover`. Passed to transport during {@linkcode Protocol.connect | connect()}.\n *\n * @default {@linkcode SUPPORTED_PROTOCOL_VERSIONS}\n */\n supportedProtocolVersions?: string[];\n\n /**\n * Whether to restrict emitted requests to only those that the remote side has indicated that they can handle, through their advertised capabilities.\n *\n * Note that this DOES NOT affect checking of _local_ side capabilities, as it is considered a logic error to mis-specify those.\n *\n * Currently this defaults to `false`, for backwards compatibility with SDK versions that did not advertise capabilities correctly. In future, this will default to `true`.\n */\n enforceStrictCapabilities?: boolean;\n /**\n * An array of notification method names that should be automatically debounced.\n * Any notifications with a method in this list will be coalesced if they\n * occur in the same tick of the event loop.\n * e.g., `['notifications/tools/list_changed']`\n */\n debouncedNotificationMethods?: string[];\n};\n\n/**\n * The default request timeout, in milliseconds.\n */\nexport const DEFAULT_REQUEST_TIMEOUT_MSEC = 60_000;\n\n/**\n * Options that can be given per request.\n */\nexport type RequestOptions = {\n /**\n * If set, requests progress notifications from the remote end (if supported). When progress notifications are received, this callback will be invoked.\n */\n onprogress?: ProgressCallback;\n\n /**\n * Can be used to cancel an in-flight request. This will cause an `AbortError` to be raised from {@linkcode Protocol.request | request()}.\n */\n signal?: AbortSignal;\n\n /**\n * A timeout (in milliseconds) for this request. If exceeded, an {@linkcode SdkError} with code {@linkcode SdkErrorCode.RequestTimeout} will be raised from {@linkcode Protocol.request | request()}.\n *\n * If not specified, {@linkcode DEFAULT_REQUEST_TIMEOUT_MSEC} will be used as the timeout.\n */\n timeout?: number;\n\n /**\n * If `true`, receiving a progress notification will reset the request timeout.\n * This is useful for long-running operations that send periodic progress updates.\n * Default: `false`\n */\n resetTimeoutOnProgress?: boolean;\n\n /**\n * Maximum total time (in milliseconds) to wait for a response.\n * If exceeded, an {@linkcode SdkError} with code {@linkcode SdkErrorCode.RequestTimeout} will be raised, regardless of progress notifications.\n * If not specified, there is no maximum total timeout.\n *\n * For multi-round-trip requests fulfilled by the auto-fulfilment driver\n * (protocol revision 2026-07-28), the budget bounds the WHOLE flow: every\n * retry leg is given only the time remaining.\n */\n maxTotalTimeout?: number;\n\n /**\n * Manual multi-round-trip mode for this call (protocol revision\n * 2026-07-28): when the response is an `input_required` result, hand it\n * back to the caller instead of auto-fulfilling it (or raising a typed\n * error). The resolved value is the neutral input-required shape\n * (`resultType: 'input_required'`, `inputRequests?`, `requestState?`);\n * wrap the result schema with `withInputRequired()` on the explicit\n * schema path to type both outcomes. The caller is then responsible for\n * gathering the requested input and retrying the original request with\n * `inputResponses` / `requestState` params and a fresh request.\n *\n * Default: `false`.\n */\n allowInputRequired?: boolean;\n} & TransportSendOptions;\n\n/**\n * Flow context handed to {@linkcode Protocol._resolveNonCompleteResult}: the\n * originating request, its options, the wire codec that decoded the response,\n * the timestamp the originating leg was issued at (for whole-flow timeout\n * accounting), and a `retry` closure that re-enters the request funnel with\n * fresh params on a fresh request id.\n */\nexport interface NonCompleteResultFlow<T extends StandardSchemaV1 = StandardSchemaV1> {\n codec: WireCodec;\n request: Request;\n resultSchema: T;\n options: RequestOptions | undefined;\n flowStartedAt: number;\n /** Re-issue the originating request with the given params and per-leg options. */\n retry(params: Record<string, unknown> | undefined, legOptions: RequestOptions): Promise<unknown>;\n}\n\n/**\n * Options that can be given per notification.\n */\nexport type NotificationOptions = {\n /**\n * May be used to indicate to the transport which incoming request to associate this outgoing notification with.\n */\n relatedRequestId?: RequestId;\n};\n\n/**\n * The reserved per-request `_meta` envelope keys (protocol revision\n * 2026-07-28). The protocol layer lifts these out of inbound `_meta` before\n * handlers run and surfaces them at `ctx.mcpReq.envelope` — they are\n * wire-level bookkeeping, not handler material.\n */\nconst RESERVED_ENVELOPE_META_KEYS: readonly string[] = [\n PROTOCOL_VERSION_META_KEY,\n CLIENT_INFO_META_KEY,\n CLIENT_CAPABILITIES_META_KEY,\n LOG_LEVEL_META_KEY\n];\n\n/**\n * Top-level params members carrying multi-round-trip driver material\n * (protocol revision 2026-07-28). The spec reserves these names on\n * client-initiated REQUESTS only — notification params keep them untouched\n * (a vendor notification may legitimately use the same names).\n */\nconst RETRY_PARAMS_KEYS = ['inputResponses', 'requestState'] as const;\n\n/**\n * Lift wire-only material out of an inbound message so handlers see exactly\n * the 2025-era shape, and surface it for the protocol layer (requests: via\n * `ctx.mcpReq`). What counts as wire-only depends on the message kind: the\n * reserved envelope `_meta` keys are reserved on every message, while the\n * multi-round-trip retry fields (`inputResponses`/`requestState`) are\n * reserved on client-initiated requests only — so notifications get only the\n * envelope lift, and their top-level params stay untouched. Messages without\n * wire-only material are returned unchanged (same reference).\n */\nfunction liftWireOnlyMaterial<T extends JSONRPCRequest | JSONRPCNotification>(\n message: T,\n kind: 'request' | 'notification'\n): { message: T; lifted: LiftedWireMaterial } {\n const params = (message as { params?: unknown }).params;\n if (!isPlainObject(params)) return { message, lifted: {} };\n\n const meta = params._meta;\n const envelopeKeys = isPlainObject(meta) ? RESERVED_ENVELOPE_META_KEYS.filter(key => key in meta) : [];\n const retryKeys = kind === 'request' ? RETRY_PARAMS_KEYS.filter(key => key in params) : [];\n if (envelopeKeys.length === 0 && retryKeys.length === 0) return { message, lifted: {} };\n\n const lifted: LiftedWireMaterial = {};\n const nextParams: Record<string, unknown> = { ...params };\n\n if (envelopeKeys.length > 0 && isPlainObject(meta)) {\n const envelope: Record<string, unknown> = {};\n const nextMeta: Record<string, unknown> = { ...meta };\n for (const key of envelopeKeys) {\n envelope[key] = meta[key];\n delete nextMeta[key];\n }\n // Surfaced as received; validation/enforcement is the dispatch-time\n // classifier's job, not the lift's.\n lifted.envelope = envelope as Partial<RequestMetaEnvelope>;\n if (Object.keys(nextMeta).length > 0) {\n nextParams._meta = nextMeta;\n } else {\n delete nextParams._meta;\n }\n }\n\n for (const key of retryKeys) {\n // Driver material reaches the protocol layer un-deleted, verbatim.\n if (key === 'inputResponses') lifted.inputResponses = nextParams[key] as Record<string, unknown>;\n if (key === 'requestState') lifted.requestState = nextParams[key] as string;\n delete nextParams[key];\n }\n\n return { message: { ...message, params: nextParams } as T, lifted };\n}\n\n/**\n * Standard Schema adapter over the era codec's `validateResult` function (the\n * function-only WireCodec contract exposes no schema objects). Used by the\n * spec-method `request()` overload so the request funnel keeps a single\n * `StandardSchemaV1`-shaped validation seam for both spec and explicit-schema\n * paths.\n *\n * Returns `undefined` when the method has no result entry on this era's\n * registry — the caller maps that to the synchronous \"pass a result schema\"\n * TypeError, exactly matching the pre-function-only behavior the\n * typedMapAlignment suite pins (the result map deliberately excludes the\n * `tasks/*` methods, so the spec-method overload refuses them up front).\n */\nfunction codecResultValidator(codec: WireCodec, method: string): StandardSchemaV1 | undefined {\n // Probe for result-registry membership through the function-only\n // contract: a `not-in-era` outcome means no result entry for this method\n // (the probe value is irrelevant — every spec result schema rejects\n // `undefined`, so a method with an entry returns `invalid`, never\n // `not-in-era`).\n const probe = codec.validateResult(method, undefined);\n if (!probe.ok && probe.reason === 'not-in-era') return undefined;\n return {\n '~standard': {\n version: 1,\n vendor: 'mcp-wire-codec',\n validate(value: unknown): StandardSchemaV1.Result<unknown> {\n const outcome = codec.validateResult(method, value);\n if (outcome.ok) return { value: outcome.value };\n return { issues: [{ message: outcome.reason === 'invalid' ? outcome.message : `not-in-era: ${method}` }] };\n }\n }\n };\n}\n\n/**\n * The type of `ctx.mcpReq.requestState`. The type parameter is\n * caller-asserted (no validation, like the two-argument `acceptedContent<T>`)\n * — pair with `createRequestStateCodec<T>` so the claim is backed by the\n * codec's verification.\n */\nexport type RequestStateAccessor = <T = unknown>() => T | undefined;\n\n/**\n * Builds the `ctx.mcpReq.requestState` accessor for a resolved value. The\n * `as T` below is the one place {@linkcode RequestStateAccessor}'s\n * caller-asserted typing is implemented — no implementation can produce an\n * arbitrary `T` from a runtime value honestly.\n */\nexport function requestStateAccessor(value: unknown): RequestStateAccessor {\n return <T>(): T | undefined => value as T | undefined;\n}\n\n/** Shared no-state accessor: the common case allocates nothing per request. */\nconst NO_REQUEST_STATE = requestStateAccessor(undefined);\n\n/**\n * Returns a context whose `requestState` accessor reads the given value —\n * how the server seam hands a verify hook's decoded payload (or the legacy\n * shim's per-round echo) to the handler without mutating the original\n * context.\n */\nexport function withRequestStateValue<ContextT extends BaseContext>(ctx: ContextT, value: unknown): ContextT {\n return {\n ...ctx,\n mcpReq: {\n ...ctx.mcpReq,\n requestState: requestStateAccessor(value)\n }\n };\n}\n\n/**\n * Base context provided to all request handlers.\n */\nexport type BaseContext = {\n /**\n * The session ID from the transport, if available.\n */\n sessionId?: string;\n\n /**\n * Information about the MCP request being handled.\n */\n mcpReq: {\n /**\n * The JSON-RPC ID of the request being handled.\n */\n id: RequestId;\n\n /**\n * The method name of the request (e.g., 'tools/call', 'ping').\n */\n method: string;\n\n /**\n * Metadata from the original request, with the reserved\n * `io.modelcontextprotocol/*` envelope keys already lifted out\n * (readable via `ctx.mcpReq.envelope`).\n */\n _meta?: RequestMeta;\n\n /**\n * The per-request `_meta` envelope (protocol revision 2026-07-28):\n * the reserved `io.modelcontextprotocol/*` keys carried by the\n * request, lifted out of the `_meta` the handler sees. Surfaced as\n * received — `Partial` because only the keys the request actually\n * carried are present (envelope requiredness is enforced per request\n * at dispatch time, not by the lift); only present at all when the\n * request carried envelope keys.\n */\n envelope?: Partial<RequestMetaEnvelope>;\n\n /**\n * Multi-round-trip input responses carried by a retried request\n * (protocol revision 2026-07-28), lifted out of the params the\n * handler sees. Entries are the BARE response objects keyed by the\n * identifiers the server assigned in `inputRequests`; entries that do\n * not look like bare responses (e.g. a `{method, result}` wrapper)\n * are dropped and their keys recorded in `droppedInputResponseKeys`.\n *\n * The values arrive from the client and are NOT validated by the SDK\n * — treat them as untrusted input.\n */\n inputResponses?: Record<string, unknown>;\n\n /**\n * Keys of `inputResponses` entries the SDK dropped because they were\n * not bare response objects (for example the wrapped `{method,\n * result}` shape some peers emit). Surfaced so a handler can re-issue\n * the corresponding input request rather than hard-fail.\n */\n droppedInputResponseKeys?: string[];\n\n /**\n * Reads the multi-round-trip request state for the current round:\n * the value the configured `ServerOptions.requestState.verify` hook\n * resolved with (e.g. `createRequestStateCodec.verify`'s decoded\n * payload — `mint<T>`/`requestState<T>()` are the typed pair), the\n * raw wire string when no hook is configured, or `undefined` when\n * the round carried no state. The type parameter is a compile-time\n * cast only.\n *\n * SECURITY: `requestState` round-trips through the client and MUST\n * be treated as attacker-controlled input. The SDK applies no\n * integrity protection by default — servers whose state influences\n * authorization or business logic MUST integrity-protect it and\n * verify via the `requestState.verify` hook (spec:\n * basic/patterns/mrtr, server requirements 4–5).\n */\n requestState: RequestStateAccessor;\n\n /**\n * An abort signal used to communicate if the request was cancelled from the sender's side.\n */\n signal: AbortSignal;\n\n /**\n * Sends a request that relates to the current request being handled.\n *\n * This is used by certain transports to correctly associate related messages.\n *\n * For spec methods the result type is inferred from the method name.\n * For custom (non-spec) methods, pass a result schema as the second argument.\n */\n send: {\n <M extends RequestMethod>(\n request: { method: M; params?: Record<string, unknown> },\n options?: RequestOptions\n ): Promise<ResultTypeMap[M]>;\n <T extends StandardSchemaV1>(\n request: Request,\n resultSchema: T,\n options?: RequestOptions\n ): Promise<StandardSchemaV1.InferOutput<T>>;\n };\n\n /**\n * Sends a notification that relates to the current request being handled.\n *\n * This is used by certain transports to correctly associate related messages.\n */\n notify: (notification: Notification) => Promise<void>;\n };\n\n /**\n * HTTP transport information, only available when using an HTTP-based transport.\n */\n http?: {\n /**\n * Information about a validated access token, provided to request handlers.\n */\n authInfo?: AuthInfo;\n };\n};\n\n/**\n * Context provided to server-side request handlers, extending {@linkcode BaseContext} with server-specific fields.\n */\nexport type ServerContext = BaseContext & {\n mcpReq: {\n /**\n * Send a log message notification to the client.\n * Respects the client's log level filter set via logging/setLevel.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n * Remains functional during the deprecation window (at least twelve months).\n * Migrate to stderr logging (STDIO servers) or OpenTelemetry.\n */\n log: (level: LoggingLevel, data: unknown, logger?: string) => Promise<void>;\n\n /**\n * Send an elicitation request to the client, requesting user input.\n *\n * @deprecated Throws on a 2026-07-28-era request — return `inputRequired(...)`\n * (multi-round-trip) from the handler instead. The 2025 push-style server-to-client request model is\n * replaced by input_required results in the 2026-07-28 protocol. If your factory serves\n * both eras, this only works on the legacy path.\n */\n elicitInput: (params: ElicitRequestFormParams | ElicitRequestURLParams, options?: RequestOptions) => Promise<ElicitResult>;\n\n /**\n * Request LLM sampling from the client.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n * Throws on a 2026-07-28-era request — return `inputRequired(...)` (multi-round-trip)\n * from the handler instead, or migrate to calling LLM provider APIs directly. The 2025 push-style\n * server-to-client request model is replaced by input_required results in the 2026-07-28\n * protocol. If your factory serves both eras, this only works on the legacy path.\n */\n requestSampling: (\n params: CreateMessageRequest['params'],\n options?: RequestOptions\n ) => Promise<CreateMessageResult | CreateMessageResultWithTools>;\n };\n\n http?: {\n /**\n * The original HTTP request.\n */\n req?: globalThis.Request;\n\n /**\n * Closes the SSE stream for this request, triggering client reconnection.\n * Only available when using a StreamableHTTPServerTransport with eventStore configured.\n */\n closeSSE?: () => void;\n\n /**\n * Closes the standalone GET SSE stream, triggering client reconnection.\n * Only available when using a StreamableHTTPServerTransport with eventStore configured.\n */\n closeStandaloneSSE?: () => void;\n };\n};\n\n/**\n * Context provided to client-side request handlers.\n */\nexport type ClientContext = BaseContext;\n\n/**\n * Information about a request's timeout state\n */\ntype TimeoutInfo = {\n timeoutId: ReturnType<typeof setTimeout>;\n startTime: number;\n timeout: number;\n maxTotalTimeout?: number;\n resetTimeoutOnProgress: boolean;\n onTimeout: () => void;\n};\n\n/*\n * Package-internal write access to Protocol's negotiated-protocol-version state.\n *\n * The negotiated version is a protected field on Protocol that the role classes\n * (Client/Server) assign directly. Tests and the modern-era server entry still\n * need to set it from outside the class hierarchy, so Protocol's static\n * initializer hands this module-scoped closure privileged access and\n * `setNegotiatedProtocolVersion` re-exports it on the core INTERNAL barrel\n * only — deliberately not public API.\n */\nlet writeNegotiatedProtocolVersion: <ContextT extends BaseContext>(instance: Protocol<ContextT>, version: string | undefined) => void;\n\n/**\n * Package-internal write channel for a {@linkcode Protocol} instance's\n * negotiated protocol version, for callers outside the class hierarchy:\n * tests and the (future) modern-era server entry that marks a factory\n * instance modern at binding time. Exported on the core internal barrel\n * only — never public API.\n */\nexport function setNegotiatedProtocolVersion<ContextT extends BaseContext>(\n instance: Protocol<ContextT>,\n version: string | undefined\n): void {\n writeNegotiatedProtocolVersion(instance, version);\n}\n\n/**\n * Implements MCP protocol framing on top of a pluggable transport, including\n * features like request/response linking, notifications, and progress.\n *\n * `Protocol` is abstract; `Client` and `Server` are the concrete role-specific\n * implementations most code should use.\n */\nexport abstract class Protocol<ContextT extends BaseContext> {\n private _transport?: Transport;\n private _requestMessageId = 0;\n private _requestHandlers: Map<string, (request: JSONRPCRequest, ctx: ContextT) => Promise<Result>> = new Map();\n private _requestHandlerAbortControllers: Map<RequestId, AbortController> = new Map();\n private _notificationHandlers: Map<string, (notification: JSONRPCNotification, codec: WireCodec) => Promise<void>> = new Map();\n private _responseHandlers: Map<number, (response: JSONRPCResultResponse | Error) => void> = new Map();\n private _progressHandlers: Map<number, ProgressCallback> = new Map();\n private _timeoutInfo: Map<number, TimeoutInfo> = new Map();\n private _pendingDebouncedNotifications = new Set<string>();\n\n /**\n * The protocol version negotiated for the current connection (`undefined`\n * before negotiation completes), which determines the wire era this\n * instance speaks. Set by the SDK's negotiation and initialize paths\n * (`Client.connect`, `Server._oninitialize`).\n */\n protected _negotiatedProtocolVersion?: string;\n\n static {\n writeNegotiatedProtocolVersion = (instance, version) => {\n instance._negotiatedProtocolVersion = version;\n };\n }\n\n protected _supportedProtocolVersions: string[];\n\n /**\n * Callback for when the connection is closed for any reason.\n *\n * This is invoked when {@linkcode Protocol.close | close()} is called as well.\n */\n onclose?: () => void;\n\n /**\n * Callback for when an error occurs.\n *\n * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band.\n */\n onerror?: (error: Error) => void;\n\n /**\n * A handler to invoke for any request types that do not have their own handler installed.\n */\n fallbackRequestHandler?: (request: JSONRPCRequest, ctx: ContextT) => Promise<Result>;\n\n /**\n * A handler to invoke for any notification types that do not have their own handler installed.\n */\n fallbackNotificationHandler?: (notification: Notification) => Promise<void>;\n\n constructor(private _options?: ProtocolOptions) {\n this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS;\n\n this.setNotificationHandler('notifications/cancelled', notification => {\n this._oncancel(notification);\n });\n\n this.setNotificationHandler('notifications/progress', notification => {\n this._onprogress(notification);\n });\n\n this.setRequestHandler(\n 'ping',\n // Automatic pong by default.\n _request => ({}) as Result\n );\n }\n\n /**\n * Builds the context object for request handlers. Subclasses must override\n * to return the appropriate context type (e.g., ServerContext adds HTTP request info).\n */\n protected abstract buildContext(ctx: BaseContext, transportInfo?: MessageExtraInfo): ContextT;\n\n /**\n * Drop consult for inbound messages whose transport did not classify them\n * at the edge — long-lived channels such as stdio, where a role class may\n * need to decline traffic the negotiated era has no answer for (the\n * client-side inbound-request drop on modern-era connections: the\n * 2026-07-28 era has no server→client request channel, and on stdio the\n * client must never write JSON-RPC responses).\n *\n * Consulted ONLY when the transport supplied no\n * {@linkcode MessageExtraInfo.classification}: edge-classified traffic\n * never reaches the hook. Returning `'drop'` discards the message without\n * writing any response (requests are surfaced via `onerror`). The base\n * implementation returns `undefined`: unclassified traffic keeps today's\n * dispatch path unchanged. Era selection never happens here — era is\n * instance state, owned by the serving entry that constructed and\n * connected the instance.\n */\n protected _shouldDropInbound(_message: JSONRPCRequest | JSONRPCNotification): 'drop' | undefined {\n return undefined;\n }\n\n /**\n * The per-request `_meta` envelope this instance attaches to every outgoing\n * request and notification, when one applies. The base implementation\n * returns `undefined` (no envelope — the 2025-era posture, so legacy-era\n * outbound traffic is byte-identical to a build without this seam).\n * `Client` overrides it on a connection that negotiated a modern (2026-07-28+)\n * era to return the reserved protocol-version / client-info /\n * client-capabilities keys. User-supplied `_meta` keys take precedence over\n * the auto-attached ones.\n */\n protected _outboundMetaEnvelope(): Readonly<Record<string, unknown>> | undefined {\n return undefined;\n }\n\n /**\n * Attach this instance's outbound `_meta` envelope (when one is configured)\n * to a request or notification. A no-op when the seam returns `undefined`\n * — the message returns by reference, so the legacy-era wire stays\n * byte-identical. User-supplied `_meta` keys are spread last so they win\n * over the auto-attached envelope keys.\n */\n private _envelopeOutbound<T extends JSONRPCRequest | JSONRPCNotification>(message: T): T {\n const envelope = this._outboundMetaEnvelope();\n if (envelope === undefined) {\n return message;\n }\n const params = (message.params ?? {}) as { _meta?: Record<string, unknown> };\n return {\n ...message,\n params: { ...params, _meta: { ...envelope, ...params._meta } }\n };\n }\n\n /**\n * Extension point for non-`complete` decoded results in the response\n * funnel: a result the wire codec discriminated into a kind other than\n * `'complete'` or `'invalid'` is handed here for the role class to\n * resolve. The base default surfaces it as a typed\n * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry).\n *\n * Intended consumers (named so the seam stays accountable):\n * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils\n * `'input_required'` results through the registered\n * elicitation/sampling/roots handlers and retries via `flow.retry`;\n * - a future client-side terminal-result handler for\n * `subscriptions/listen`, when the spec defines one.\n *\n * `Server` instances never receive `input_required` responses on their\n * outbound legs and leave the base behavior in place.\n */\n protected _resolveNonCompleteResult<T extends StandardSchemaV1>(\n decoded: ReturnType<WireCodec['decodeResult']> & { kind: 'input_required' },\n flow: NonCompleteResultFlow<T>\n ): Promise<unknown> {\n return Promise.reject(\n new SdkError(SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, {\n resultType: decoded.kind,\n method: flow.request.method\n })\n );\n }\n\n /**\n * Protected accessor for a registered request handler. Used by role\n * classes that dispatch synthesized requests through the same stored\n * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip\n * input request).\n */\n protected _getRequestHandler(method: string): ((request: JSONRPCRequest, ctx: ContextT) => Promise<Result>) | undefined {\n return this._requestHandlers.get(method);\n }\n\n private async _oncancel(notification: CancelledNotification): Promise<void> {\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\n private _setupTimeout(\n messageId: number,\n timeout: number,\n maxTotalTimeout: number | undefined,\n onTimeout: () => void,\n resetTimeoutOnProgress: boolean = false\n ) {\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\n private _resetTimeout(messageId: number): boolean {\n const info = this._timeoutInfo.get(messageId);\n if (!info) return false;\n\n const totalElapsed = Date.now() - info.startTime;\n if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {\n this._timeoutInfo.delete(messageId);\n throw new SdkError(SdkErrorCode.RequestTimeout, 'Maximum total timeout exceeded', {\n maxTotalTimeout: info.maxTotalTimeout,\n totalElapsed\n });\n }\n\n clearTimeout(info.timeoutId);\n info.timeoutId = setTimeout(info.onTimeout, info.timeout);\n return true;\n }\n\n private _cleanupTimeout(messageId: number) {\n const info = this._timeoutInfo.get(messageId);\n if (info) {\n clearTimeout(info.timeoutId);\n this._timeoutInfo.delete(messageId);\n }\n }\n\n /**\n * Attaches to the given transport, starts it, and starts listening for messages.\n *\n * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward.\n */\n async connect(transport: Transport): Promise<void> {\n this._transport = transport;\n const _onclose = this.transport?.onclose;\n this._transport.onclose = () => {\n try {\n _onclose?.();\n } finally {\n this._onclose();\n }\n };\n\n const _onerror = this.transport?.onerror;\n this._transport.onerror = (error: Error) => {\n _onerror?.(error);\n this._onerror(error);\n };\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 } else if (isJSONRPCRequest(message)) {\n this._onrequest(message, extra);\n } else if (isJSONRPCNotification(message)) {\n this._onnotification(message, extra);\n } else {\n this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));\n }\n };\n\n // Pass supported protocol versions to transport for header validation\n transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions);\n\n await this._transport.start();\n }\n\n /**\n * Transport-close hook. Subclass overrides MUST call `super._onclose()`\n * after their own cleanup — base teardown (response-handler settlement,\n * timeout clearing, in-flight request abort) does not run otherwise.\n */\n protected _onclose(): void {\n const responseHandlers = this._responseHandlers;\n this._responseHandlers = new Map();\n this._progressHandlers.clear();\n this._pendingDebouncedNotifications.clear();\n\n for (const info of this._timeoutInfo.values()) {\n clearTimeout(info.timeoutId);\n }\n this._timeoutInfo.clear();\n\n const requestHandlerAbortControllers = this._requestHandlerAbortControllers;\n this._requestHandlerAbortControllers = new Map();\n\n const error = new SdkError(SdkErrorCode.ConnectionClosed, 'Connection closed');\n\n this._transport = undefined;\n\n try {\n this.onclose?.();\n } finally {\n for (const handler of responseHandlers.values()) {\n handler(error);\n }\n\n for (const controller of requestHandlerAbortControllers.values()) {\n controller.abort(error);\n }\n }\n }\n\n private _onerror(error: Error): void {\n this.onerror?.(error);\n }\n\n /**\n * Inbound-notification dispatch. Subclass overrides MUST delegate\n * unmatched traffic to `super._onnotification(rawNotification, extra)` —\n * an override that consumes only what it owns and falls through to base\n * dispatch for everything else.\n */\n protected _onnotification(rawNotification: JSONRPCNotification, extra?: MessageExtraInfo): void {\n // Hide wire-only material from notification handlers too — but ONLY\n // the reserved envelope `_meta` keys (the retry params names are\n // reserved on requests, not notifications). There is no\n // per-notification context, so the lifted envelope keys are dropped,\n // not surfaced; the protocol layer owns them.\n const { message: notification } = liftWireOnlyMaterial(rawNotification, 'notification');\n\n // Era is instance state: the negotiated protocol version selects the\n // codec for everything this connection receives (legacy until\n // negotiated). Classification is never a per-message era switch — an\n // edge classification is validated against the instance era below.\n const codec = this._negotiatedWireCodec();\n\n // Drop consult (only when the transport did not classify; edge-\n // classified traffic never reaches the hook): a role class may decline\n // unclassified inbound traffic the negotiated era has no answer for.\n if (extra?.classification === undefined && this._shouldDropInbound(rawNotification) === 'drop') {\n return;\n }\n\n // Edge→instance handoff check: a classification that disagrees with\n // the instance era means the entry routed another era's traffic onto\n // this instance. That is a routing error — drop the notification and\n // surface it out of band; never serve it on a guessed era.\n if (extra?.classification !== undefined) {\n const classified = classifiedWireEra(extra.classification);\n if (classified !== codec.era) {\n this._onerror(\n new Error(\n `Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`\n )\n );\n return;\n }\n }\n\n // Era gate — deletions are physical: a spec notification that is not\n // in this era's registry is dropped even when a handler is\n // registered (notifications get no error response; silent drop is\n // the protocol-correct outcome, matching today's unknown-method\n // posture). Methods outside the spec universe are consumer-owned\n // extension notifications and stay era-blind.\n if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) {\n return;\n }\n\n const handler = this._notificationHandlers.get(notification.method);\n const fallback = this.fallbackNotificationHandler;\n\n // Ignore notifications not being subscribed to.\n if (handler === undefined && fallback === undefined) {\n return;\n }\n\n // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n Promise.resolve()\n .then(() => (handler === undefined ? fallback!(notification) : handler(notification, codec)))\n .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));\n }\n\n private _onrequest(rawRequest: JSONRPCRequest, extra?: MessageExtraInfo): void {\n // Lift wire-only material before dispatch: handlers (including the\n // fallback handler and the per-method schema parse) see exactly the\n // 2025-era shape; the envelope and retry fields surface via ctx.\n const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, 'request');\n\n // Era is instance state: the negotiated protocol version selects the\n // codec for everything this connection receives (legacy until\n // negotiated). Classification (Q2; produced at the transport/entry\n // edge — this layer only CONSUMES MessageExtraInfo.classification) is\n // never a per-message era switch — it is validated against the\n // instance era below. Hand-wired legacy transports never classify, so\n // their behavior is untouched.\n const codec = this._negotiatedWireCodec();\n\n // Drop consult (only when the transport did not classify; edge-\n // classified traffic never reaches the hook): a role class may decline\n // unclassified inbound traffic the negotiated era has no answer for.\n if (extra?.classification === undefined && this._shouldDropInbound(rawRequest) === 'drop') {\n this._onerror(new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`));\n return;\n }\n\n // Capture the current transport at request time to ensure responses go to the correct client\n const capturedTransport = this._transport;\n\n const sendErrorResponse = (code: number, message: string, data?: unknown) => {\n const errorResponse: JSONRPCErrorResponse = {\n jsonrpc: '2.0',\n id: request.id,\n error: { code, message, ...(data !== undefined && { data }) }\n };\n capturedTransport?.send(errorResponse).catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`)));\n };\n\n // Edge→instance handoff check: a classification that disagrees with\n // the instance era means the entry routed another era's traffic onto\n // this instance. That is a routing error: answer with the typed era\n // error (−32022 Unsupported protocol version) and surface it out of\n // band — never serve the request on a guessed era.\n if (extra?.classification !== undefined) {\n const classified = classifiedWireEra(extra.classification);\n if (classified !== codec.era) {\n this._onerror(\n new Error(\n `Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`\n )\n );\n // `requested` echoes the protocol version the classification\n // actually named when it carried one; the wire-era label is\n // only the fallback for classifications without an exact\n // revision.\n const requested = extra.classification.revision ?? classified;\n sendErrorResponse(ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, {\n // Per spec, `supported` is the full list of protocol\n // versions the receiver supports — not just the version\n // this connection is on — so the peer can pick a mutually\n // supported version from the error alone. (Revisit when\n // instances are bound to the modern era at the entry: a\n // bound instance's configured list may not name the\n // revision it was bound to.)\n supported: this._supportedProtocolVersions,\n requested\n });\n return;\n }\n }\n\n // Era gate — deletions are physical: a spec method that is not in\n // this era's registry is −32601 BY ABSENCE, before any handler\n // lookup, even when a handler is registered (a custom handler cannot\n // shadow a deleted spec method across eras). Methods outside the\n // spec universe are consumer-owned extension methods and stay\n // era-blind.\n if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) {\n sendErrorResponse(ProtocolErrorCode.MethodNotFound, 'Method not found');\n return;\n }\n\n const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler;\n\n if (handler === undefined) {\n sendErrorResponse(ProtocolErrorCode.MethodNotFound, 'Method not found');\n return;\n }\n\n // Envelope enforcement: the 2026 era requires the per-request `_meta`\n // envelope on every request (spec.types.2026-07-28 RequestParams).\n // The lift extracted it above; the era codec validates requiredness.\n // Deliberately AFTER the era gate and the handler-existence check:\n // an unknown method answers −32601 even when the envelope is also\n // missing — method existence outranks parameter validity. (The\n // canonical precedence table for the full inbound validation ladder\n // arrives with the validation-ladder milestone; this site encodes\n // only the −32601-over-−32602 rule.)\n const envelopeError = codec.checkInboundEnvelope(lifted);\n if (envelopeError !== undefined) {\n sendErrorResponse(ProtocolErrorCode.InvalidParams, envelopeError);\n return;\n }\n\n // Related sends resolve through the SAME instance era as every other\n // sender (the per-request/instance asymmetry is deliberately gone):\n // the codec is resolved at send time from the connection state.\n const sendNotification = (notification: Notification, options?: NotificationOptions) =>\n this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, {\n ...options,\n relatedRequestId: request.id\n });\n const sendRequest = <U extends StandardSchemaV1>(r: Request, resultSchema: U, options?: RequestOptions) =>\n this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, {\n ...options,\n relatedRequestId: request.id\n });\n\n const abortController = new AbortController();\n this._requestHandlerAbortControllers.set(request.id, abortController);\n\n // Multi-round-trip retry material: only BARE response objects are\n // surfaced to the handler; entries that look like a wrapped\n // `{method, result}` shape (or are not objects at all) are dropped\n // and their keys recorded so the handler can re-issue the input\n // request instead of hard-failing (D-059 posture).\n const partitionedInputResponses = lifted.inputResponses === undefined ? undefined : partitionInputResponses(lifted.inputResponses);\n\n const baseCtx: BaseContext = {\n sessionId: capturedTransport?.sessionId,\n mcpReq: {\n id: request.id,\n method: request.method,\n _meta: request.params?._meta,\n ...(lifted.envelope !== undefined && { envelope: lifted.envelope }),\n ...(partitionedInputResponses !== undefined && { inputResponses: partitionedInputResponses.accepted }),\n ...(partitionedInputResponses !== undefined &&\n partitionedInputResponses.droppedKeys.length > 0 && {\n droppedInputResponseKeys: partitionedInputResponses.droppedKeys\n }),\n // The accessor surfaces the raw lifted value (captured as the\n // string primitive so the lift record stays collectable); the\n // server seam swaps in the verify hook's decoded payload\n // before the handler runs.\n requestState: lifted.requestState === undefined ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState),\n signal: abortController.signal,\n // BaseContext.mcpReq.send is declared with two overloads (spec-method-keyed and explicit-schema). Arrow\n // literals can't carry overload signatures, so the inferred single-signature type isn't assignable to\n // that overloaded property type. The cast is sound: this impl dispatches both overload paths via the\n // isStandardSchema guard, and sendRequest validates the result against the resolved schema either way.\n send: ((r: Request, schemaOrOptions?: StandardSchemaV1 | RequestOptions, maybeOptions?: RequestOptions) => {\n // Related requests resolve through the instance era at\n // send time, exactly like direct sends: era-gate first,\n // then method-keyed schema resolution.\n const sendCodec = this._resolveOutboundCodec(r.method);\n this._assertOutboundRequestInEra(sendCodec, r.method);\n if (isStandardSchema(schemaOrOptions)) {\n return sendRequest(r, schemaOrOptions, maybeOptions);\n }\n const validate = codecResultValidator(sendCodec, r.method);\n if (validate === undefined) {\n throw new TypeError(\n `'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`\n );\n }\n return sendRequest(r, validate, schemaOrOptions);\n }) as BaseContext['mcpReq']['send'],\n notify: sendNotification\n },\n http: extra?.authInfo ? { authInfo: extra.authInfo } : undefined\n };\n const ctx = this.buildContext(baseCtx, extra);\n\n // Starting with Promise.resolve() puts any synchronous errors into the monad as well.\n Promise.resolve()\n .then(() => handler(request, ctx))\n .then(\n async result => {\n if (abortController.signal.aborted) {\n // Request was cancelled\n return;\n }\n\n // The outbound stamp seam: the era codec maps the neutral\n // handler result to its wire shape. The 2025-era codec is\n // the identity (never-stamp); the 2026-era codec stamps\n // `resultType` and enforces the deleted-field set. A throw\n // here is a NEW failure mode between handler success and\n // the transport send (and the seam grows ttlMs/cacheScope\n // stamping content in M3.2) — it must answer the peer with\n // −32603 rather than stranding the request until timeout.\n let encoded: Result;\n try {\n encoded = codec.encodeResult(request.method, result);\n } catch (error) {\n this._onerror(new Error(`Failed to encode result for ${request.method}: ${error}`));\n sendErrorResponse(ProtocolErrorCode.InternalError, 'Internal error');\n return;\n }\n\n const response: JSONRPCResponse = {\n result: encoded,\n jsonrpc: '2.0',\n id: request.id\n };\n await capturedTransport?.send(response);\n },\n async error => {\n if (abortController.signal.aborted) {\n // Request was cancelled\n return;\n }\n\n // The error half of the encode seam: the era codec selects\n // the wire code for a handler-thrown error, so per-era\n // wire-code policy lives in the codec rather than in any\n // handler. Non-integer codes still fall through to −32603.\n const thrownCode = Number.isSafeInteger(error['code']) ? (error['code'] as number) : ProtocolErrorCode.InternalError;\n const errorResponse: JSONRPCErrorResponse = {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: codec.encodeErrorCode(thrownCode),\n message: error.message ?? 'Internal error',\n ...(error['data'] !== undefined && { data: error['data'] })\n }\n };\n await capturedTransport?.send(errorResponse);\n }\n )\n .catch(error => this._onerror(new Error(`Failed to send response: ${error}`)))\n .finally(() => {\n if (this._requestHandlerAbortControllers.get(request.id) === abortController) {\n this._requestHandlerAbortControllers.delete(request.id);\n }\n });\n }\n\n private _onprogress(notification: ProgressNotification): void {\n const { progressToken, ...params } = notification.params;\n const messageId = Number(progressToken);\n\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\n const responseHandler = this._responseHandlers.get(messageId);\n const timeoutInfo = this._timeoutInfo.get(messageId);\n\n if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {\n try {\n this._resetTimeout(messageId);\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 as Error);\n return;\n }\n }\n\n handler(params);\n }\n\n /**\n * Inbound-response dispatch. Subclass overrides MUST delegate unmatched\n * traffic to `super._onresponse(response)` — an override that consumes\n * only what it owns and falls through to base dispatch for everything\n * else.\n */\n protected _onresponse(response: JSONRPCResponse | JSONRPCErrorResponse): void {\n const messageId = Number(response.id);\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\n this._responseHandlers.delete(messageId);\n this._cleanupTimeout(messageId);\n this._progressHandlers.delete(messageId);\n\n if (isJSONRPCResultResponse(response)) {\n handler(response);\n } else {\n const error = ProtocolError.fromError(response.error.code, response.error.message, response.error.data);\n handler(error);\n }\n }\n\n get transport(): Transport | undefined {\n return this._transport;\n }\n\n /**\n * Closes the connection.\n */\n async close(): Promise<void> {\n await this._transport?.close();\n }\n\n /**\n * A method to check if a capability is supported by the remote side, for the given method to be called.\n *\n * This should be implemented by subclasses.\n */\n protected abstract assertCapabilityForMethod(method: RequestMethod | string): void;\n\n /**\n * A method to check if a notification is supported by the local side, for the given method to be sent.\n *\n * This should be implemented by subclasses.\n */\n protected abstract assertNotificationCapability(method: NotificationMethod | string): void;\n\n /**\n * A method to check if a request handler is supported by the local side, for the given method to be handled.\n *\n * This should be implemented by subclasses.\n */\n protected abstract assertRequestHandlerCapability(method: string): void;\n\n /**\n * Sends a request and waits for a response.\n *\n * For spec methods the result schema is resolved automatically from the method name\n * and the return type is method-keyed. For custom (non-spec) methods, pass a\n * `resultSchema` as the second argument; the response is validated against it and\n * the return type is inferred from the schema.\n *\n * Do not use this method to emit notifications! Use {@linkcode Protocol.notification | notification()} instead.\n */\n request<M extends RequestMethod>(\n request: { method: M; params?: Record<string, unknown> },\n options?: RequestOptions\n ): Promise<ResultTypeMap[M]>;\n request<T extends StandardSchemaV1>(\n request: Request,\n resultSchema: T,\n options?: RequestOptions\n ): Promise<StandardSchemaV1.InferOutput<T>>;\n request(request: Request, schemaOrOptions?: StandardSchemaV1 | RequestOptions, maybeOptions?: RequestOptions): Promise<unknown> {\n const codec = this._resolveOutboundCodec(request.method);\n this._assertOutboundRequestInEra(codec, request.method);\n if (isStandardSchema(schemaOrOptions)) {\n return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions);\n }\n const validate = codecResultValidator(codec, request.method);\n if (validate === undefined) {\n throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`);\n }\n return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions);\n }\n\n /**\n * The wire codec for this instance's negotiated era — the phase-2 truth:\n * everything an established connection sends and receives resolves\n * through it. Legacy until a version has been negotiated.\n */\n private _negotiatedWireCodec(): WireCodec {\n return codecForVersion(this._negotiatedProtocolVersion);\n }\n\n /**\n * Protected accessor for the instance's negotiated wire codec, for role\n * classes (Client/Server/McpServer) routing era-dependent behavior\n * through the codec's function-only surface — `samplingResultVariant`,\n * `outboundEnvelope`, `projectCallToolResult` — instead of branching on\n * the protocol version themselves.\n */\n protected _wireCodec(): WireCodec {\n return this._negotiatedWireCodec();\n }\n\n /**\n * Outbound codec resolution: while the negotiated version is still unset\n * (the negotiation window), lifecycle messages are bootstrap-pinned BY\n * METHOD — they self-identify their era (`initialize` IS the legacy\n * handshake, `server/discover` IS the modern probe). Once a version has\n * been negotiated, the instance era is authoritative for everything — a\n * negotiated session never re-routes a method onto the other era.\n */\n private _resolveOutboundCodec(method: string): WireCodec {\n if (this._negotiatedProtocolVersion === undefined) {\n const pinned = bootstrapOutboundCodec(method);\n if (pinned) return pinned;\n }\n return this._negotiatedWireCodec();\n }\n\n /**\n * Era gate for outbound requests — deletions are physical in BOTH\n * directions: sending a spec method that the resolved era does not define\n * dies locally with a typed error before anything reaches the transport.\n * Methods outside the spec universe are consumer-owned extension methods\n * and stay era-blind.\n */\n private _assertOutboundRequestInEra(codec: WireCodec, method: string): void {\n if (isSpecRequestMethod(method) && !codec.hasRequestMethod(method)) {\n throw new SdkError(\n SdkErrorCode.MethodNotSupportedByProtocolVersion,\n `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`,\n { method, era: codec.era }\n );\n }\n }\n\n /**\n * Sends a request and waits for a response, using the provided schema for\n * validation instead of the era registry's method-keyed entry.\n *\n * This is the internal implementation used by SDK methods whose result\n * schema cannot be expressed as a method-keyed registry entry — the one\n * surviving case is `server.createMessage`, whose result schema depends\n * on the REQUEST params (tools vs no tools) — and by callers passing\n * explicit compatibility schemas. Spec methods are still era-gated here:\n * an explicit schema never smuggles a deleted method onto the wire.\n */\n protected _requestWithSchema<T extends StandardSchemaV1>(\n request: Request,\n resultSchema: T,\n options?: RequestOptions\n ): Promise<StandardSchemaV1.InferOutput<T>> {\n const codec = this._resolveOutboundCodec(request.method);\n this._assertOutboundRequestInEra(codec, request.method);\n return this._requestWithSchemaViaCodec(codec, request, resultSchema, options);\n }\n\n /**\n * The request funnel proper, keyed by the resolved era codec: the codec\n * owns result decoding (raw-first `resultType` discrimination — V-1 —\n * and the era's lift posture) before the schema validation step.\n */\n private _requestWithSchemaViaCodec<T extends StandardSchemaV1>(\n codec: WireCodec,\n request: Request,\n resultSchema: T,\n options?: RequestOptions\n ): Promise<StandardSchemaV1.InferOutput<T>> {\n const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {};\n // Flow start for non-complete result resolution: `maxTotalTimeout`\n // bounds the WHOLE flow, so the budget is measured from the original\n // request, not from when an extension takes over after the first leg.\n const flowStartedAt = Date.now();\n\n let onAbort: (() => void) | undefined;\n let cleanupMessageId: number | undefined;\n\n // Send the request\n return new Promise<StandardSchemaV1.InferOutput<T>>((resolve, reject) => {\n const earlyReject = (error: unknown) => {\n reject(error);\n };\n\n if (!this._transport) {\n earlyReject(new Error('Not connected'));\n return;\n }\n\n if (this._options?.enforceStrictCapabilities === true) {\n try {\n this.assertCapabilityForMethod(request.method);\n } catch (error) {\n earlyReject(error);\n return;\n }\n }\n\n // An already-aborted caller signal must surface the same way an\n // in-flight abort does (`SdkError(RequestTimeout, reason)` via\n // `cancel()` below). Bare `throwIfAborted()` would propagate the\n // raw `signal.reason` instead, so callers that introduce an async\n // hop before `request()` (e.g. a cache freshness check) would see\n // a different rejection type depending on where the abort lands.\n if (options?.signal?.aborted) {\n const reason = options.signal.reason;\n throw reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason));\n }\n\n // Spec basic/patterns/cancellation §Transport-Specific (2026-07-28):\n // on Streamable HTTP, closing the per-request SSE stream IS the\n // cancellation signal — \"no notifications/cancelled message is\n // required or expected\". When the negotiated era is modern AND the\n // transport opens a per-request stream (`hasPerRequestStream`),\n // cancel() aborts that stream via `requestSignal` INSTEAD OF\n // POSTing `notifications/cancelled`. Every other (era × transport)\n // combination — legacy era on any transport, modern era on stdio /\n // in-memory — keeps today's `notifications/cancelled` POST path\n // unchanged.\n const streamCloseCancels = codec.era === MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true;\n const requestAbort = streamCloseCancels ? new AbortController() : undefined;\n\n const messageId = this._requestMessageId++;\n cleanupMessageId = messageId;\n const jsonrpcRequest: JSONRPCRequest = {\n ...request,\n jsonrpc: '2.0',\n id: messageId\n };\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\n // Per-request envelope auto-attach (after the progressToken merge so\n // both share the same `_meta`): a no-op on the legacy era — the\n // envelope seam returns undefined and the request goes out exactly as\n // built above.\n const outbound = this._envelopeOutbound(jsonrpcRequest);\n\n let responseReceived = false;\n\n const cancel = (reason: unknown) => {\n if (responseReceived) {\n return;\n }\n this._progressHandlers.delete(messageId);\n\n if (requestAbort === undefined) {\n this._transport\n ?.send(\n this._envelopeOutbound({\n jsonrpc: '2.0',\n method: 'notifications/cancelled',\n params: {\n requestId: messageId,\n reason: String(reason)\n }\n }),\n { relatedRequestId, resumptionToken, onresumptiontoken }\n )\n .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`)));\n } else {\n // Modern-era per-request-stream transport: aborting the\n // request's underlying stream IS the spec cancel signal.\n // The transport already swallows the resulting AbortError\n // (no spurious `onerror`); a post-abort send() rejection\n // re-hits an already-settled promise below and is a no-op.\n requestAbort.abort();\n }\n\n // Wrap the reason in an SdkError if it isn't already\n const error = reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason));\n reject(error);\n };\n\n this._responseHandlers.set(messageId, response => {\n if (options?.signal?.aborted) {\n return;\n }\n responseReceived = true;\n\n if (response instanceof Error) {\n return reject(response);\n }\n\n // Codec decode hop — the structural V-1 home. The era codec\n // owns the raw-first resultType postures (Q1-SD3):\n // - 2026 era: REQUIRED discriminator; absent → typed error\n // naming the spec violation; input_required → driver seam;\n // unknown kind → invalid, no retry; complete → wire-exact\n // parse then lift.\n // - 2025 era: resultType is foreign vocabulary → strip-on-\n // lift, then today's schema validation decides.\n // Either way a non-complete body can never be masked into a\n // hollow success by a tolerant result schema.\n // Guarded: this callback runs synchronously inside\n // `_onresponse`, so a throw out of the decode hop would\n // otherwise propagate into the transport's onmessage instead\n // of failing this request.\n let decoded: ReturnType<WireCodec['decodeResult']>;\n try {\n decoded = codec.decodeResult(request.method, response.result);\n } catch (error) {\n return reject(error instanceof Error ? error : new Error(String(error)));\n }\n if (decoded.kind === 'invalid') {\n return reject(decoded.error);\n }\n if (decoded.kind === 'input_required') {\n // Manual mode (the primitive any driver layers over):\n // hand the input-required value back to the caller.\n if (options?.allowInputRequired === true) {\n return resolve(manualInputRequiredValue(decoded) as StandardSchemaV1.InferOutput<T>);\n }\n // Non-complete result extension point: the role class may\n // resolve the flow itself (the Client wires the\n // multi-round-trip auto-fulfilment engine here). The base\n // default is the typed UnsupportedResultType error.\n const flow: NonCompleteResultFlow<T> = {\n codec,\n request,\n resultSchema,\n options,\n flowStartedAt,\n retry: (params, legOptions) =>\n this._requestWithSchemaViaCodec(\n codec,\n params === undefined ? { method: request.method } : { method: request.method, params },\n resultSchema,\n legOptions\n )\n };\n return resolve(this._resolveNonCompleteResult(decoded, flow) as Promise<StandardSchemaV1.InferOutput<T>>);\n }\n const result = decoded.result;\n\n validateStandardSchema(resultSchema, result).then(parseResult => {\n if (parseResult.success) {\n resolve(parseResult.data);\n } else {\n reject(new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`));\n }\n }, reject);\n });\n\n onAbort = () => cancel(options?.signal?.reason);\n options?.signal?.addEventListener('abort', onAbort, { once: true });\n\n const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC;\n const timeoutHandler = () => cancel(new SdkError(SdkErrorCode.RequestTimeout, 'Request timed out', { timeout }));\n\n this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false);\n\n this._transport\n .send(outbound, { relatedRequestId, resumptionToken, onresumptiontoken, headers, requestSignal: requestAbort?.signal })\n .catch(error => {\n this._progressHandlers.delete(messageId);\n reject(error);\n });\n }).finally(() => {\n // Per-request cleanup that must run on every exit path. Consolidated\n // here so new exit paths added to the promise body can't forget it.\n // _progressHandlers is NOT cleaned up here: _onresponse deletes it\n // on resolution, and error paths above delete it inline.\n if (onAbort) {\n options?.signal?.removeEventListener('abort', onAbort);\n }\n if (cleanupMessageId !== undefined) {\n this._responseHandlers.delete(cleanupMessageId);\n this._cleanupTimeout(cleanupMessageId);\n }\n });\n }\n\n /**\n * Emits a notification, which is a one-way message that does not expect a response.\n */\n async notification(notification: Notification, options?: NotificationOptions): Promise<void> {\n return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options);\n }\n\n /**\n * The notification funnel proper, keyed by the resolved era codec —\n * direct sends and related notifications (`ctx.mcpReq.notify`) alike\n * resolve through the instance's negotiated era at send time.\n */\n private async _notificationViaCodec(codec: WireCodec, notification: Notification, options?: NotificationOptions): Promise<void> {\n if (!this._transport) {\n throw new SdkError(SdkErrorCode.NotConnected, 'Not connected');\n }\n\n // Era gate — outbound deletions are physical for notifications too: a\n // spec notification the resolved era does not define dies locally.\n if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) {\n throw new SdkError(\n SdkErrorCode.MethodNotSupportedByProtocolVersion,\n `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`,\n { method: notification.method, era: codec.era }\n );\n }\n\n this.assertNotificationCapability(notification.method);\n\n const jsonrpcNotification = this._envelopeOutbound({ jsonrpc: '2.0' as const, ...notification });\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 that could be lost).\n const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId;\n\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\n // Mark this notification type as pending.\n this._pendingDebouncedNotifications.add(notification.method);\n\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\n // SAFETY CHECK: If the connection was closed while this was pending, abort.\n if (!this._transport) {\n return;\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\n // Return immediately.\n return;\n }\n\n await this._transport.send(jsonrpcNotification, options);\n }\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 * For spec methods, pass `(method, handler)`; the request is parsed with the spec\n * schema and the handler receives the typed `Request`. For custom (non-spec)\n * methods, pass `(method, schemas, handler)`; `params` are validated against\n * `schemas.params` and the handler receives the parsed params object directly.\n * Supplying `schemas.result` types the handler's return value.\n *\n * @example Custom request method\n * ```ts source=\"./protocol.examples.ts#Protocol_setRequestHandler_customMethod\"\n * const SearchParams = z.object({ query: z.string(), limit: z.number().optional() });\n * const SearchResult = z.object({ hits: z.array(z.string()) });\n *\n * protocol.setRequestHandler('acme/search', { params: SearchParams, result: SearchResult }, async (params, _ctx) => {\n * return { hits: [`result for ${params.query}`] };\n * });\n * ```\n */\n setRequestHandler<M extends RequestMethod>(\n method: M,\n handler: (request: RequestTypeMap[M], ctx: ContextT) => HandlerResultTypeMap[M] | Promise<HandlerResultTypeMap[M]>\n ): void;\n setRequestHandler<P extends StandardSchemaV1, R extends StandardSchemaV1 | undefined = undefined>(\n method: string,\n schemas: { params: P; result?: R },\n handler: (params: StandardSchemaV1.InferOutput<P>, ctx: ContextT) => InferHandlerResult<R> | Promise<InferHandlerResult<R>>\n ): void;\n setRequestHandler(\n method: string,\n schemasOrHandler: RequestHandlerSchemas | ((request: unknown, ctx: ContextT) => Result | Promise<Result>),\n maybeHandler?: (params: unknown, ctx: ContextT) => Result | Promise<Result>\n ): void {\n this.assertRequestHandlerCapability(method);\n\n let stored: (request: JSONRPCRequest, ctx: ContextT) => Promise<Result>;\n\n if (typeof schemasOrHandler === 'function') {\n if (!isSpecRequestMethod(method)) {\n throw new TypeError(\n `'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`\n );\n }\n // Dispatch-time schema resolution: the request is parsed with the\n // schema of the era serving this connection (the instance era at\n // dispatch time), never with a schema captured at registration\n // time. On the 2026-07-28 era the demoted server→client methods\n // (elicitation/sampling/roots) are not wire request methods —\n // they reach a handler only as embedded input requests dispatched\n // by the multi-round-trip driver, and parse with the era's\n // in-band schema instead.\n stored = (request, ctx) => {\n const dispatchCodec = this._negotiatedWireCodec();\n let outcome = dispatchCodec.validateRequest(method, request);\n if (!outcome.ok && outcome.reason === 'not-in-era') {\n outcome = dispatchCodec.validateInputRequest(method, request);\n }\n if (!outcome.ok) {\n if (outcome.reason === 'not-in-era') {\n // Unreachable: the dispatch era gate rejects\n // era-mismatched spec methods with −32601 before any\n // handler runs.\n throw new ProtocolError(ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`);\n }\n // Preserves the pre-function-only error surface: the Zod\n // parse threw out of the handler and the funnel mapped it\n // to −32603 Internal error (specCorpusDispatch pins this).\n throw new Error(outcome.message);\n }\n return Promise.resolve(schemasOrHandler(outcome.value, ctx));\n };\n } else if (maybeHandler) {\n stored = async (request, ctx) => {\n // Custom handlers receive `_meta` present-minus-reserved: the\n // wire-only lift already removed the reserved envelope keys,\n // and the remaining metadata (progressToken, extension keys)\n // is handler material — consistent with the spec-method path.\n // (Behavior migration: `_meta` used to be deleted here.)\n const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params });\n if (!parsed.success) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`);\n }\n return maybeHandler(parsed.data, ctx);\n };\n } else {\n throw new TypeError('setRequestHandler: handler is required');\n }\n\n this._requestHandlers.set(method, this._wrapHandler(method, stored));\n }\n\n /**\n * Hook for subclasses to wrap a registered request handler with role-specific\n * validation or behavior (e.g. `Server` validates `tools/call` results, `Client`\n * validates `elicitation/create` mode and result). Runs for both the 2-arg and\n * 3-arg registration paths. The default implementation is identity.\n *\n * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set.\n */\n protected _wrapHandler(\n _method: string,\n handler: (request: JSONRPCRequest, ctx: ContextT) => Promise<Result>\n ): (request: JSONRPCRequest, ctx: ContextT) => Promise<Result> {\n return handler;\n }\n\n /**\n * Removes the request handler for the given method.\n */\n removeRequestHandler(method: RequestMethod | string): void {\n this._requestHandlers.delete(method);\n }\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: RequestMethod | string): void {\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 /**\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 * For spec methods, pass `(method, handler)`; the notification is parsed with the\n * spec schema. For custom (non-spec) methods, pass `(method, schemas, handler)`;\n * `params` are validated against `schemas.params` and the handler receives the\n * parsed params object directly. The raw notification is passed as the second\n * argument; `_meta` is recoverable via `notification.params?._meta` (minus the\n * reserved `io.modelcontextprotocol/*` envelope keys, which the protocol layer\n * lifts out before dispatch).\n */\n setNotificationHandler<M extends NotificationMethod>(\n method: M,\n handler: (notification: NotificationTypeMap[M]) => void | Promise<void>\n ): void;\n setNotificationHandler<P extends StandardSchemaV1>(\n method: string,\n schemas: { params: P },\n handler: (params: StandardSchemaV1.InferOutput<P>, notification: Notification) => void | Promise<void>\n ): void;\n setNotificationHandler(\n method: string,\n schemasOrHandler: { params: StandardSchemaV1 } | ((notification: unknown) => void | Promise<void>),\n maybeHandler?: (params: unknown, notification: Notification) => void | Promise<void>\n ): void {\n if (typeof schemasOrHandler === 'function') {\n if (!isSpecNotificationMethod(method)) {\n throw new TypeError(\n `'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`\n );\n }\n // Dispatch-time schema resolution, same as setRequestHandler: the\n // era serving the message picks the schema.\n this._notificationHandlers.set(method, (notification, codec) => {\n const outcome = codec.validateNotification(method, notification);\n if (!outcome.ok) {\n if (outcome.reason === 'not-in-era') {\n // Unreachable: the dispatch era gate drops\n // era-mismatched spec notifications before any\n // handler runs.\n throw new ProtocolError(ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`);\n }\n // Preserves the pre-function-only error surface (parse\n // threw out of the handler).\n throw new Error(outcome.message);\n }\n return Promise.resolve(schemasOrHandler(outcome.value));\n });\n return;\n }\n\n if (!maybeHandler) {\n throw new TypeError('setNotificationHandler: handler is required');\n }\n this._notificationHandlers.set(method, async notification => {\n // `_meta` present-minus-reserved, matching the custom request\n // path (the lift already removed the reserved envelope keys).\n const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params });\n if (!parsed.success) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`);\n }\n await maybeHandler(parsed.data, notification);\n });\n }\n\n /**\n * Removes the notification handler for the given method.\n */\n removeNotificationHandler(method: NotificationMethod | string): void {\n this._notificationHandlers.delete(method);\n }\n}\n\n/**\n * Schema bundle accepted by {@linkcode Protocol.setRequestHandler | setRequestHandler}'s 3-arg form.\n *\n * `params` is required and validates the inbound `request.params`. `result` is optional;\n * when supplied it types the handler's return value (no runtime validation is performed\n * on the result).\n */\nexport interface RequestHandlerSchemas<\n P extends StandardSchemaV1 = StandardSchemaV1,\n R extends StandardSchemaV1 | undefined = StandardSchemaV1 | undefined\n> {\n params: P;\n result?: R;\n}\n\ntype InferHandlerResult<R extends StandardSchemaV1 | undefined> = R extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<R> : Result;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nexport function mergeCapabilities(base: ServerCapabilities, additional: Partial<ServerCapabilities>): ServerCapabilities;\nexport function mergeCapabilities(base: ClientCapabilities, additional: Partial<ClientCapabilities>): ClientCapabilities;\nexport function mergeCapabilities<T extends ServerCapabilities | ClientCapabilities>(base: T, additional: Partial<T>): T {\n const result: T = { ...base };\n for (const key in additional) {\n const k = key as keyof T;\n const addValue = additional[k];\n if (addValue === undefined) continue;\n const baseValue = result[k];\n result[k] =\n isPlainObject(baseValue) && isPlainObject(addValue)\n ? ({ ...(baseValue as Record<string, unknown>), ...(addValue as Record<string, unknown>) } as T[typeof k])\n : (addValue as T[typeof k]);\n }\n return result;\n}\n","/**\n * The multi-round-trip auto-fulfilment ENGINE (protocol revision 2026-07-28):\n * the wiring between the protocol layer's response funnel, the\n * already-registered input handlers, and the pure {@link runInputRequiredDriver}\n * loop. The engine is what the `Client` plugs into the funnel's\n * `_resolveNonCompleteResult` extension point — `Protocol` itself only knows\n * the input-required branch exists.\n *\n * Relocated here so the shared `Protocol` base stays generic: the only\n * MRTR-specific code that remains in `protocol.ts` is the irreducible\n * input-required branch in the response path, the type surface (the\n * `allowInputRequired` request option and the `inputResponses`/`requestState`/\n * `droppedInputResponseKeys` context fields), and the named extension point.\n */\nimport { SdkError, SdkErrorCode } from '../errors/sdkErrors';\nimport type { InputRequiredResult, JSONRPCRequest, RequestMeta, Result } from '../types/types';\nimport type { StandardSchemaV1 } from '../util/standardSchema';\nimport type { WireCodec } from '../wire/codec';\nimport type {\n InputRequiredDriverHooks,\n InputRequiredPayload,\n InputRequiredRetryLegOptions,\n ResolvedInputRequiredDriverConfig\n} from './inputRequiredDriver';\nimport { runInputRequiredDriver } from './inputRequiredDriver';\nimport type { BaseContext, NonCompleteResultFlow, RequestOptions } from './protocol';\nimport { requestStateAccessor } from './protocol';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Splits a retried request's `inputResponses` map into the BARE response\n * entries the spec defines and everything else. The spec's embedded responses\n * are the bare result objects (an `ElicitResult`, `CreateMessageResult`, or\n * `ListRootsResult`); a wrapped `{method, result}` envelope (a shape some\n * peers emit) is never accepted as a response — its key is recorded so the\n * handler can re-issue the corresponding input request.\n */\nexport function partitionInputResponses(inputResponses: unknown): { accepted: Record<string, unknown>; droppedKeys: string[] } {\n const accepted: Record<string, unknown> = {};\n const droppedKeys: string[] = [];\n if (!isPlainObject(inputResponses)) {\n return { accepted, droppedKeys };\n }\n for (const [key, entry] of Object.entries(inputResponses)) {\n // Bare responses never carry `method` or `result` members — both are\n // the signature of the wrapped (JSON-RPC-shaped) form.\n if (!isPlainObject(entry) || 'method' in entry || 'result' in entry) {\n droppedKeys.push(key);\n continue;\n }\n accepted[key] = entry;\n }\n return { accepted, droppedKeys };\n}\n\n/**\n * Related send/notify are unavailable inside an embedded input-request\n * handler: the request is fulfilled locally by the multi-round-trip driver,\n * so there is no live peer request to relate messages to.\n */\nfunction relatedMessagingUnavailable(member: string): never {\n throw new SdkError(\n SdkErrorCode.SendFailed,\n `ctx.mcpReq.${member} is not available while fulfilling an embedded input request: ` +\n `the request is fulfilled locally and has no related peer request`\n );\n}\n\n/**\n * The synthesized {@linkcode BaseContext} for an embedded input request: the\n * id is the `inputRequests` key (correlation only — it is not a JSON-RPC\n * message id), the supplied abort signal chains the originating call's signal\n * through, and related `send`/`notify` are unavailable because there is no\n * live peer request to relate them to.\n */\nexport function synthesizeInputRequestContext(\n key: string,\n method: string,\n params: Record<string, unknown> | undefined,\n signal: AbortSignal,\n sessionId: string | undefined\n): BaseContext {\n return {\n sessionId,\n mcpReq: {\n id: key,\n method,\n _meta: params?.['_meta'] as RequestMeta | undefined,\n // Embedded input requests never carry multi-round-trip state.\n requestState: requestStateAccessor(undefined),\n signal,\n send: (() => relatedMessagingUnavailable('send')) as BaseContext['mcpReq']['send'],\n notify: () => relatedMessagingUnavailable('notify')\n }\n };\n}\n\n/**\n * Hooks the engine needs from the consuming role class (the `Client`): how to\n * look up a registered handler and how to enrich a base context.\n */\nexport interface InputRequiredEngineHost {\n /** The handler registered for the given method, or `undefined`. */\n getRequestHandler(method: string): ((request: JSONRPCRequest, ctx: unknown) => Promise<Result>) | undefined;\n /** Builds the role-specific context from a {@linkcode BaseContext}. */\n buildContext(baseCtx: BaseContext): unknown;\n /** The transport's session identifier, when there is one. */\n sessionId: string | undefined;\n}\n\n/**\n * Dispatches one embedded (de-JSON-RPC'd) input request to the locally\n * registered handler for its method and resolves with the bare response.\n *\n * The handler runs through the same stored handler chain as a wire request\n * (including role-specific validation installed by `_wrapHandler`), with a\n * synthesized context (see {@link synthesizeInputRequestContext}).\n */\nexport async function dispatchInputRequest(\n host: InputRequiredEngineHost,\n codec: WireCodec,\n key: string,\n entry: unknown,\n signal: AbortSignal\n): Promise<unknown> {\n if (!isPlainObject(entry) || typeof entry['method'] !== 'string') {\n throw new SdkError(\n SdkErrorCode.InvalidResult,\n `Invalid input request '${key}': each inputRequests entry must be an embedded request object with a method`,\n { key }\n );\n }\n const method = entry['method'];\n if (!codec.hasInputRequestMethod(method)) {\n throw new SdkError(\n SdkErrorCode.InvalidResult,\n `Invalid input request '${key}': '${method}' is not an embedded request the ${codec.era} revision defines ` +\n `(expected elicitation/create, sampling/createMessage, or roots/list)`,\n { key, method }\n );\n }\n const handler = host.getRequestHandler(method);\n if (handler === undefined) {\n throw new SdkError(\n SdkErrorCode.CapabilityNotSupported,\n `Cannot fulfil input request '${key}': no handler is registered for '${method}' on this client. ` +\n `Declare the corresponding capability and register a handler, or handle input_required results manually.`,\n { key, method }\n );\n }\n\n const params = isPlainObject(entry['params']) ? (entry['params'] as Record<string, unknown>) : undefined;\n const synthesizedRequest: JSONRPCRequest = {\n jsonrpc: '2.0',\n id: key,\n method,\n ...(params !== undefined && { params })\n };\n const ctx = host.buildContext(synthesizeInputRequestContext(key, method, params, signal, host.sessionId));\n return await handler(synthesizedRequest, ctx);\n}\n\n/**\n * Builds the per-retry-leg {@linkcode RequestOptions} from the originating\n * call's options.\n *\n * Only the fields that are correct to apply to every leg carry over (a\n * deliberate whitelist): the per-leg `timeout`, the (shrinking) total budget\n * `maxTotalTimeout`, the caller's `onprogress`/`resetTimeoutOnProgress`, and\n * the caller's abort `signal`. Everything else — in particular\n * `relatedRequestId`, `resumptionToken`, and `onresumptiontoken` — is scoped\n * to the originating wire leg and is NOT inherited by retries.\n */\nexport function buildRetryLegRequestOptions(options: RequestOptions | undefined, legOptions: InputRequiredRetryLegOptions): RequestOptions {\n return {\n ...(options?.signal !== undefined && { signal: options.signal }),\n ...(options?.onprogress !== undefined && { onprogress: options.onprogress }),\n ...(options?.resetTimeoutOnProgress !== undefined && { resetTimeoutOnProgress: options.resetTimeoutOnProgress }),\n // Per-request HTTP headers (SEP-2243 `Mcp-Param-*`) carry over: the\n // retry's `arguments` are byte-identical to the originating leg (the\n // driver only adds `inputResponses`/`requestState`), so the param\n // headers built for the first leg remain correct for every retry leg.\n ...(options?.headers !== undefined && { headers: options.headers }),\n ...(legOptions.timeout !== undefined && { timeout: legOptions.timeout }),\n ...(legOptions.maxTotalTimeout !== undefined && { maxTotalTimeout: legOptions.maxTotalTimeout }),\n // The driver re-enters the funnel with the manual primitive: a further\n // input_required answer is handed back to the loop instead of\n // recursing into another driver run (the round cap is global to the\n // flow).\n allowInputRequired: true\n };\n}\n\n/**\n * Runs the auto-fulfilment flow for one originating request whose response\n * came back as `input_required`: builds the driver hooks (embedded-request\n * dispatch + retry through the funnel) and hands them to\n * {@link runInputRequiredDriver}. Resolves with the final complete result\n * (already validated by the retry leg) or rejects with a typed error.\n */\nexport function runInputRequiredFlow<T extends StandardSchemaV1>(\n host: InputRequiredEngineHost,\n config: ResolvedInputRequiredDriverConfig,\n decoded: { inputRequests: Record<string, unknown>; requestState?: string },\n flow: NonCompleteResultFlow<T>\n): Promise<unknown> {\n const { codec, request, options, flowStartedAt } = flow;\n const firstPayload: InputRequiredPayload = {\n inputRequests: decoded.inputRequests,\n ...(decoded.requestState !== undefined && { requestState: decoded.requestState })\n };\n const hooks: InputRequiredDriverHooks = {\n dispatchInputRequest: (key, entry, signal) => dispatchInputRequest(host, codec, key, entry, signal),\n retry: (params, legOptions) => flow.retry(params, buildRetryLegRequestOptions(options, legOptions))\n };\n return runInputRequiredDriver({\n config,\n method: request.method,\n originalParams: request.params,\n firstPayload,\n flowStartedAt,\n signal: options?.signal,\n requestOptions: {\n ...(options?.timeout !== undefined && { timeout: options.timeout }),\n ...(options?.maxTotalTimeout !== undefined && { maxTotalTimeout: options.maxTotalTimeout }),\n ...(options?.onprogress !== undefined && { onprogress: options.onprogress })\n },\n hooks\n });\n}\n\n/**\n * Builds the manual-mode {@linkcode InputRequiredResult} value from the\n * codec's decoded payload — what an `allowInputRequired: true` caller\n * receives instead of the auto-fulfilled complete result.\n */\nexport function manualInputRequiredValue(decoded: { inputRequests: Record<string, unknown>; requestState?: string }): InputRequiredResult {\n return {\n resultType: 'input_required',\n inputRequests: decoded.inputRequests as InputRequiredResult['inputRequests'],\n ...(decoded.requestState !== undefined && { requestState: decoded.requestState })\n };\n}\n","import type { BaseMetadata } from '../types/index';\n\n/**\n * Utilities for working with {@linkcode BaseMetadata} objects.\n */\n\n/**\n * Gets the display name for an object with {@linkcode BaseMetadata}.\n * For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name`\n * For other objects: `title` → `name`\n * This implements the spec requirement: \"if no title is provided, name should be used for display purposes\"\n */\nexport function getDisplayName(metadata: BaseMetadata | (BaseMetadata & { annotations?: { title?: string } })): string {\n // First check for title (not undefined and not empty string)\n if (metadata.title !== undefined && metadata.title !== '') {\n return metadata.title;\n }\n\n // Then check for annotations.title (only present in Tool objects)\n if ('annotations' in metadata && metadata.annotations?.title) {\n return metadata.annotations.title;\n }\n\n // Finally fall back to name\n return metadata.name;\n}\n","import type { JSONRPCMessage } from '../types/index';\nimport { JSONRPCMessageSchema } from '../types/index';\n\nexport const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024;\n\n/**\n * Buffers a continuous stdio stream into discrete JSON-RPC messages.\n */\nexport class ReadBuffer {\n private _buffer?: Buffer;\n private _maxBufferSize: number;\n\n constructor(options?: { maxBufferSize?: number }) {\n this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE;\n }\n\n append(chunk: Buffer): void {\n const newSize = (this._buffer?.length ?? 0) + chunk.length;\n if (newSize > this._maxBufferSize) {\n this.clear();\n throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);\n }\n this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;\n }\n\n readMessage(): JSONRPCMessage | null {\n while (this._buffer) {\n const index = this._buffer.indexOf('\\n');\n if (index === -1) {\n return null;\n }\n\n const line = this._buffer.toString('utf8', 0, index).replace(/\\r$/, '');\n this._buffer = this._buffer.subarray(index + 1);\n\n try {\n return deserializeMessage(line);\n } catch (error) {\n // Skip non-JSON lines (e.g., debug output from hot-reload tools like\n // tsx or nodemon that write to stdout). Schema validation errors still\n // throw so malformed-but-valid-JSON messages surface via onerror.\n if (error instanceof SyntaxError) {\n continue;\n }\n throw error;\n }\n }\n return null;\n }\n\n clear(): void {\n this._buffer = undefined;\n }\n}\n\nexport function deserializeMessage(line: string): JSONRPCMessage {\n return JSONRPCMessageSchema.parse(JSON.parse(line));\n}\n\nexport function serializeMessage(message: JSONRPCMessage): string {\n return JSON.stringify(message) + '\\n';\n}\n","/**\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 * @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names}\n */\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/**\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: string): {\n isValid: boolean;\n warnings: string[];\n} {\n const warnings: string[] = [];\n\n // Check length\n if (name.length === 0) {\n return {\n isValid: false,\n warnings: ['Tool name cannot be empty']\n };\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\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\n if (name.includes(',')) {\n warnings.push('Tool name contains commas, which may cause parsing issues');\n }\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\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\n // Check for invalid characters\n if (!TOOL_NAME_REGEX.test(name)) {\n const invalidChars = [...name]\n .filter(char => !/[A-Za-z0-9._-]/.test(char))\n .filter((char, index, arr) => arr.indexOf(char) === index); // Remove duplicates\n\n warnings.push(\n `Tool name contains invalid characters: ${invalidChars.map(c => `\"${c}\"`).join(', ')}`,\n 'Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)'\n );\n\n return {\n isValid: false,\n warnings\n };\n }\n\n return {\n isValid: true,\n warnings\n };\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: string, warnings: string[]): void {\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(\n 'See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.'\n );\n }\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: string): boolean {\n const result = validateToolName(name);\n\n // Always issue warnings for any validation issues (both invalid names and warnings)\n issueToolNameWarning(name, result.warnings);\n\n return result.isValid;\n}\n","import type { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types/index';\n\nexport type FetchLike = (url: string | URL, init?: RequestInit) => Promise<Response>;\n\n/**\n * Normalizes `HeadersInit` to a plain `Record<string, string>` for manipulation.\n * Handles `Headers` objects, arrays of tuples, and plain objects.\n */\nexport function normalizeHeaders(headers: RequestInit['headers'] | undefined): Record<string, string> {\n if (!headers) return {};\n\n if (headers instanceof Headers) {\n return Object.fromEntries(headers.entries());\n }\n\n if (Array.isArray(headers)) {\n return Object.fromEntries(headers);\n }\n\n return { ...(headers as Record<string, string>) };\n}\n\n/**\n * Creates a fetch function that includes base `RequestInit` options.\n * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init.\n *\n * @param baseFetch - The base fetch function to wrap (defaults to global `fetch`)\n * @param baseInit - The base `RequestInit` to merge with each request\n * @returns A wrapped fetch function that merges base options with call-specific options\n */\nexport function createFetchWithInit(baseFetch: FetchLike = fetch, baseInit?: RequestInit): FetchLike {\n if (!baseInit) {\n return baseFetch;\n }\n\n // Return a wrapped fetch that merges base RequestInit with call-specific init\n return async (url: string | URL, init?: RequestInit): Promise<Response> => {\n const mergedInit: RequestInit = {\n ...baseInit,\n ...init,\n // Headers need special handling - merge instead of replace\n headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers\n };\n return baseFetch(url, mergedInit);\n };\n}\n\n/**\n * Options for sending a JSON-RPC message.\n */\nexport type TransportSendOptions = {\n /**\n * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with.\n */\n relatedRequestId?: RequestId | undefined;\n\n /**\n * The resumption token used to continue long-running requests that were interrupted.\n *\n * This allows clients to reconnect and continue from where they left off, if supported by the transport.\n */\n resumptionToken?: string | undefined;\n\n /**\n * A callback that is invoked when the resumption token changes, if supported by the transport.\n *\n * This allows clients to persist the latest token for potential reconnection.\n */\n onresumptiontoken?: ((token: string) => void) | undefined;\n\n /**\n * An abort signal for THIS outbound message's underlying request, when the\n * transport sends one outbound message per underlying request (the\n * Streamable HTTP transport's POST-per-request model). Aborting it cancels\n * the underlying request (and its SSE response stream) without closing the\n * transport. Transports that share a single channel (stdio, in-memory)\n * ignore it.\n */\n requestSignal?: AbortSignal | undefined;\n\n /**\n * Fired by transports that open a per-request stream (the Streamable HTTP\n * transport's POST-per-request SSE response) when that stream ends or\n * errors for any reason OTHER than a deliberate `requestSignal` abort —\n * i.e. the server closed the stream, the network dropped it, or\n * reconnection was exhausted. Transports that share a single channel\n * (stdio, in-memory) ignore it.\n */\n onRequestStreamEnd?: (() => void) | undefined;\n\n /**\n * Additional HTTP headers to send with THIS outbound message, when the\n * transport sends one outbound message per underlying HTTP request (the\n * Streamable HTTP transport's POST-per-request model). Transports that\n * share a single channel (stdio, in-memory) ignore it.\n *\n * The Client uses this to attach SEP-2243 `Mcp-Param-{Name}` headers to a\n * `tools/call` request on a 2026-07-28 connection. Values are sent\n * verbatim — encode anything that is not a safe RFC 9110 field value\n * before passing it here.\n */\n headers?: Readonly<Record<string, string>> | undefined;\n};\n/**\n * Describes the minimal contract for an MCP transport that a client or server can communicate over.\n */\nexport interface Transport {\n /**\n * Starts processing messages on the transport, including any connection steps that might need to be taken.\n *\n * This method should only be called after callbacks are installed, or else messages may be lost.\n *\n * NOTE: This method should not be called explicitly when using {@linkcode @modelcontextprotocol/client!client/client.Client | Client} or {@linkcode @modelcontextprotocol/server!server/server.Server | Server} classes, as they will implicitly call {@linkcode Transport.start | start()}.\n */\n start(): Promise<void>;\n\n /**\n * Sends a JSON-RPC message (request or response).\n *\n * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with.\n */\n send(message: JSONRPCMessage, options?: TransportSendOptions): Promise<void>;\n\n /**\n * Closes the connection.\n */\n close(): Promise<void>;\n\n /**\n * `true` when this transport opens one underlying request per outbound\n * JSON-RPC request (the Streamable HTTP POST-per-request model) and\n * therefore honors {@linkcode TransportSendOptions.requestSignal}. The\n * 2026-07-28 spec makes closing that per-request stream the cancellation\n * signal — the protocol layer aborts `requestSignal` instead of POSTing\n * `notifications/cancelled` when this flag is set on a 2026-era\n * connection. Transports that share a single channel (stdio, in-memory)\n * leave it `undefined`.\n */\n readonly hasPerRequestStream?: boolean;\n\n /**\n * Callback for when the connection is closed for any reason.\n *\n * This should be invoked when {@linkcode Transport.close | close()} is called as well.\n */\n onclose?: (() => void) | undefined;\n\n /**\n * Callback for when an error occurs.\n *\n * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band.\n */\n onerror?: ((error: Error) => void) | undefined;\n\n /**\n * Callback for when a message (request or response) is received over the connection.\n *\n * Includes the {@linkcode MessageExtraInfo.request | request} and {@linkcode MessageExtraInfo.authInfo | authInfo} if the transport is authenticated.\n *\n * The {@linkcode MessageExtraInfo.request | request} can be used to get the original request information (headers, etc.)\n */\n onmessage?: (<T extends JSONRPCMessage>(message: T, extra?: MessageExtraInfo) => void) | undefined;\n\n /**\n * The session ID generated for this connection.\n */\n sessionId?: string | undefined;\n\n /**\n * Sets the protocol version used for the connection (called when the initialize response is received).\n */\n setProtocolVersion?: ((version: string) => void) | undefined;\n\n /**\n * Sets the supported protocol versions for header validation (called during connect).\n * This allows the server to pass its supported versions to the transport.\n */\n setSupportedProtocolVersions?: ((versions: string[]) => void) | undefined;\n}\n","// Claude-authored implementation of RFC 6570 URI Templates\n\nexport type Variables = Record<string, string | string[]>;\n\nconst MAX_TEMPLATE_LENGTH = 1_000_000; // 1MB\nconst MAX_VARIABLE_LENGTH = 1_000_000; // 1MB\nconst MAX_TEMPLATE_EXPRESSIONS = 10_000;\nconst MAX_REGEX_LENGTH = 1_000_000; // 1MB\n\nexport class UriTemplate {\n /**\n * Returns true if the given string contains any URI template expressions.\n * A template expression is a sequence of characters enclosed in curly braces,\n * like `{foo}` or `{?bar}`.\n */\n static isTemplate(str: string): boolean {\n // Look for any sequence of characters between curly braces\n // that isn't just whitespace\n return /\\{[^}\\s]+\\}/.test(str);\n }\n\n private static validateLength(str: string, max: number, context: string): void {\n if (str.length > max) {\n throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`);\n }\n }\n private readonly template: string;\n private readonly parts: Array<string | { name: string; operator: string; names: string[]; exploded: boolean }>;\n\n get variableNames(): string[] {\n return this.parts.flatMap(part => (typeof part === 'string' ? [] : part.names));\n }\n\n constructor(template: string) {\n UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, 'Template');\n this.template = template;\n this.parts = this.parse(template);\n }\n\n toString(): string {\n return this.template;\n }\n\n private parse(template: string): Array<string | { name: string; operator: string; names: string[]; exploded: boolean }> {\n const parts: Array<string | { name: string; operator: string; names: string[]; exploded: boolean }> = [];\n let currentText = '';\n let i = 0;\n let expressionCount = 0;\n\n while (i < template.length) {\n if (template[i] === '{') {\n if (currentText) {\n parts.push(currentText);\n currentText = '';\n }\n const end = template.indexOf('}', i);\n if (end === -1) throw new Error('Unclosed template expression');\n\n expressionCount++;\n if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) {\n throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`);\n }\n\n const expr = template.slice(i + 1, end);\n const operator = this.getOperator(expr);\n const exploded = expr.includes('*');\n const names = this.getNames(expr);\n const name = names[0]!;\n\n // Validate variable name length\n for (const name of names) {\n UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name');\n }\n\n parts.push({ name, operator, names, exploded });\n i = end + 1;\n } else {\n currentText += template[i];\n i++;\n }\n }\n\n if (currentText) {\n parts.push(currentText);\n }\n\n return parts;\n }\n\n private getOperator(expr: string): string {\n const operators = ['+', '#', '.', '/', '?', '&'];\n return operators.find(op => expr.startsWith(op)) || '';\n }\n\n private getNames(expr: string): string[] {\n const operator = this.getOperator(expr);\n return expr\n .slice(operator.length)\n .split(',')\n .map(name => name.replace('*', '').trim())\n .filter(name => name.length > 0);\n }\n\n private encodeValue(value: string, operator: string): string {\n UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, 'Variable value');\n if (operator === '+' || operator === '#') {\n return encodeURI(value);\n }\n return encodeURIComponent(value);\n }\n\n private expandPart(\n part: {\n name: string;\n operator: string;\n names: string[];\n exploded: boolean;\n },\n variables: Variables\n ): string {\n if (part.operator === '?' || part.operator === '&') {\n const pairs = part.names\n .map(name => {\n const value = variables[name];\n if (value === undefined) return '';\n const encoded = Array.isArray(value)\n ? value.map(v => this.encodeValue(v, part.operator)).join(',')\n : this.encodeValue(value.toString(), part.operator);\n return `${name}=${encoded}`;\n })\n .filter(pair => pair.length > 0);\n\n if (pairs.length === 0) return '';\n const separator = part.operator === '?' ? '?' : '&';\n return separator + pairs.join('&');\n }\n\n if (part.names.length > 1) {\n const values = part.names.map(name => variables[name]).filter(v => v !== undefined);\n if (values.length === 0) return '';\n return values.map(v => (Array.isArray(v) ? v[0] : v)).join(',');\n }\n\n const value = variables[part.name];\n if (value === undefined) return '';\n\n const values = Array.isArray(value) ? value : [value];\n const encoded = values.map(v => this.encodeValue(v, part.operator));\n\n switch (part.operator) {\n case '': {\n return encoded.join(',');\n }\n case '+': {\n return encoded.join(',');\n }\n case '#': {\n return '#' + encoded.join(',');\n }\n case '.': {\n return '.' + encoded.join('.');\n }\n case '/': {\n return '/' + encoded.join('/');\n }\n default: {\n return encoded.join(',');\n }\n }\n }\n\n expand(variables: Variables): string {\n let result = '';\n let hasQueryParam = false;\n\n for (const part of this.parts) {\n if (typeof part === 'string') {\n result += part;\n continue;\n }\n\n const expanded = this.expandPart(part, variables);\n if (!expanded) continue;\n\n // Convert ? to & if we already have a query parameter\n result += (part.operator === '?' || part.operator === '&') && hasQueryParam ? expanded.replace('?', '&') : expanded;\n\n if (part.operator === '?' || part.operator === '&') {\n hasQueryParam = true;\n }\n }\n\n return result;\n }\n\n private escapeRegExp(str: string): string {\n return str.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\n }\n\n private partToRegExp(part: {\n name: string;\n operator: string;\n names: string[];\n exploded: boolean;\n }): Array<{ pattern: string; name: string }> {\n const patterns: Array<{ pattern: string; name: string }> = [];\n\n // Validate variable name length for matching\n for (const name of part.names) {\n UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name');\n }\n\n if (part.operator === '?' || part.operator === '&') {\n for (let i = 0; i < part.names.length; i++) {\n const name = part.names[i]!;\n const prefix = i === 0 ? '\\\\' + part.operator : '&';\n patterns.push({\n pattern: prefix + this.escapeRegExp(name) + '=([^&]+)',\n name\n });\n }\n return patterns;\n }\n\n let pattern: string;\n const name = part.name;\n\n switch (part.operator) {\n case '': {\n pattern = part.exploded ? '([^/,]+(?:,[^/,]+)*)' : '([^/,]+)';\n break;\n }\n case '+':\n case '#': {\n pattern = '(.+)';\n break;\n }\n case '.': {\n pattern = String.raw`\\.([^/,]+)`;\n break;\n }\n case '/': {\n pattern = '/' + (part.exploded ? '([^/,]+(?:,[^/,]+)*)' : '([^/,]+)');\n break;\n }\n default: {\n pattern = '([^/]+)';\n }\n }\n\n patterns.push({ pattern, name });\n return patterns;\n }\n\n match(uri: string): Variables | null {\n UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, 'URI');\n let pattern = '^';\n const names: Array<{ name: string; exploded: boolean }> = [];\n\n for (const part of this.parts) {\n if (typeof part === 'string') {\n pattern += this.escapeRegExp(part);\n } else {\n const patterns = this.partToRegExp(part);\n for (const { pattern: partPattern, name } of patterns) {\n pattern += partPattern;\n names.push({ name, exploded: part.exploded });\n }\n }\n }\n\n pattern += '$';\n UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, 'Generated regex pattern');\n const regex = new RegExp(pattern);\n const match = uri.match(regex);\n\n if (!match) return null;\n\n const result: Variables = {};\n for (const [i, name_] of names.entries()) {\n const { name, exploded } = name_!;\n const value = match[i + 1]!;\n const cleanName = name.replace('*', '');\n\n result[cleanName] = exploded && value.includes(',') ? value.split(',') : value;\n }\n\n return result;\n }\n}\n","import { SdkError, SdkErrorCode } from '../errors/sdkErrors';\nimport type { Transport } from '../shared/transport';\nimport type { AuthInfo, JSONRPCMessage, RequestId } from '../types/index';\n\ninterface QueuedMessage {\n message: JSONRPCMessage;\n extra?: { authInfo?: AuthInfo };\n}\n\n/**\n * In-memory transport for creating clients and servers that talk to each other within the same process.\n *\n * Intended for testing and development. For production in-process connections, use\n * `StreamableHTTPClientTransport` against a local server URL.\n */\nexport class InMemoryTransport implements Transport {\n private _otherTransport?: InMemoryTransport;\n private _messageQueue: QueuedMessage[] = [];\n private _closed = false;\n\n onclose?: () => void;\n onerror?: (error: Error) => void;\n onmessage?: (message: JSONRPCMessage, extra?: { authInfo?: AuthInfo }) => void;\n sessionId?: string;\n\n /**\n * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and one to a {@linkcode @modelcontextprotocol/server!server/server.Server | Server}.\n */\n static createLinkedPair(): [InMemoryTransport, InMemoryTransport] {\n const clientTransport = new InMemoryTransport();\n const serverTransport = new InMemoryTransport();\n clientTransport._otherTransport = serverTransport;\n serverTransport._otherTransport = clientTransport;\n return [clientTransport, serverTransport];\n }\n\n async start(): Promise<void> {\n // Process any messages that were queued before start was called\n while (this._messageQueue.length > 0) {\n const queuedMessage = this._messageQueue.shift()!;\n this.onmessage?.(queuedMessage.message, queuedMessage.extra);\n }\n }\n\n async close(): Promise<void> {\n if (this._closed) return;\n this._closed = true;\n\n const other = this._otherTransport;\n this._otherTransport = undefined;\n try {\n await other?.close();\n } finally {\n this.onclose?.();\n }\n }\n\n /**\n * Sends a message with optional auth info.\n * This is useful for testing authentication scenarios.\n */\n async send(message: JSONRPCMessage, options?: { relatedRequestId?: RequestId; authInfo?: AuthInfo }): Promise<void> {\n if (!this._otherTransport) {\n throw new SdkError(SdkErrorCode.NotConnected, 'Not connected');\n }\n\n if (this._otherTransport.onmessage) {\n this._otherTransport.onmessage(message, { authInfo: options?.authInfo });\n } else {\n this._otherTransport._messageQueue.push({ message, extra: { authInfo: options?.authInfo } });\n }\n }\n}\n","/**\n * Internal Zod schema utilities for protocol handling.\n * These are used internally by the SDK for protocol message validation.\n */\n\nimport * as z from 'zod/v4';\n\n/**\n * Base type for any Zod schema.\n */\nexport type AnySchema = z.core.$ZodType;\n\n/**\n * A Zod schema for objects specifically.\n */\nexport type AnyObjectSchema = z.core.$ZodObject;\n\n/**\n * Extracts the output type from a Zod schema.\n */\nexport type SchemaOutput<T extends AnySchema> = z.output<T>;\n\n/**\n * Parses data against a Zod schema (synchronous).\n * Returns a discriminated union with success/error.\n */\nexport function parseSchema<T extends AnySchema>(\n schema: T,\n data: unknown\n): { success: true; data: z.output<T> } | { success: false; error: z.core.$ZodError } {\n return z.safeParse(schema, data);\n}\n","/**\n * Zod-specific helpers for the v1-compat raw-shape shorthand on\n * `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so\n * that file stays library-agnostic per the Standard Schema spec.\n */\n\nimport * as z from 'zod/v4';\n\nimport type { StandardSchemaWithJSON } from './standardSchema';\nimport { isStandardSchema } from './standardSchema';\n\nfunction isZodV4Schema(v: unknown): v is z.ZodType {\n // `_zod` is the v4 internal namespace property. Zod v3 schemas have `_def`\n // and (since 3.24) `~standard.vendor === 'zod'`, but never `_zod`. We require\n // v4 because the wrap path below uses v4's `z.object()`, which cannot consume\n // v3 field schemas.\n return typeof v === 'object' && v !== null && '_zod' in v;\n}\n\nfunction looksLikeZodV3(v: unknown): boolean {\n // v3 schemas have `_def.typeName` (e.g. 'ZodString') and no `_zod`.\n return (\n typeof v === 'object' &&\n v !== null &&\n !('_zod' in v) &&\n '_def' in v &&\n typeof (v as { _def?: { typeName?: unknown } })._def?.typeName === 'string'\n );\n}\n\n/**\n * Detects a \"raw shape\" — a plain object whose values are Zod field schemas,\n * e.g. `{ name: z.string() }`. Powers the auto-wrap in\n * {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only\n * Zod values are supported.\n *\n * @internal\n */\nexport function isZodRawShape(obj: unknown): obj is Record<string, z.ZodType> {\n if (typeof obj !== 'object' || obj === null) return false;\n if (isStandardSchema(obj)) return false;\n // Require a plain object literal: rejects arrays, Date, Map, RegExp, class instances, etc.\n // Object.create(null) is also accepted.\n const proto = Object.getPrototypeOf(obj);\n if (proto !== Object.prototype && proto !== null) return false;\n // [].every() is true, so an empty plain object is a valid raw shape (matches v1).\n return Object.values(obj).every(v => isZodV4Schema(v));\n}\n\n/**\n * Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape\n * `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}.\n * Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a\n * uniform schema type; already-wrapped schemas pass through unchanged.\n *\n * @internal\n */\nexport function normalizeRawShapeSchema(\n schema: StandardSchemaWithJSON | Record<string, z.ZodType> | undefined\n): StandardSchemaWithJSON | undefined {\n if (schema === undefined) return undefined;\n if (isZodRawShape(schema)) {\n return z.object(schema) as StandardSchemaWithJSON;\n }\n if (typeof schema === 'object' && schema !== null && !isStandardSchema(schema) && Object.values(schema).some(v => looksLikeZodV3(v))) {\n throw new TypeError(\n 'Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself.'\n );\n }\n if (!isStandardSchema(schema)) {\n throw new TypeError(\n 'inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() }).'\n );\n }\n // Any StandardSchema passes through; standardSchemaToJsonSchema owns the per-vendor\n // handling for schemas without `~standard.jsonSchema` (zod 4.0-4.1 fallback, zod 3\n // and non-zod errors). Gating on `~standard.jsonSchema` here would unreachably\n // front-run that fallback.\n return schema;\n}\n","import type { StandardSchemaV1, StandardSchemaWithJSON } from '../util/standardSchema';\nimport type { JsonSchemaType, jsonSchemaValidator } from './types';\n\n/**\n * Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be\n * passed to `registerTool` / `registerPrompt`. Use this when you already have JSON\n * Schema (e.g. from TypeBox, or hand-written) and want to register it without going\n * through a Standard Schema library.\n *\n * The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript\n * types attached). Cast at the call site, or use the generic `fromJsonSchema<MyType>(...)`.\n *\n * @param schema - A JSON Schema object describing the expected shape\n * @param validator - A validator provider. When importing `fromJsonSchema` from\n * `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate\n * default is provided automatically (AJV on Node.js, CfWorker on edge runtimes).\n *\n * @example\n * ```ts source=\"./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage\"\n * const inputSchema = fromJsonSchema<{ name: string }>(\n * { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },\n * validator\n * );\n * // Use with server.registerTool('greet', { inputSchema }, handler)\n * ```\n */\nexport function fromJsonSchema<T = unknown>(schema: JsonSchemaType, validator: jsonSchemaValidator): StandardSchemaWithJSON<T, T> {\n const check = validator.getValidator<T>(schema);\n return {\n '~standard': {\n version: 1,\n vendor: 'mcp',\n jsonSchema: {\n input: () => schema as Record<string, unknown>,\n output: () => schema as Record<string, unknown>\n },\n validate: (data: unknown): StandardSchemaV1.Result<T> => {\n const result = check(data);\n return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] };\n }\n }\n };\n}\n","import type { ServerCapabilities, SubscriptionFilter } from '@modelcontextprotocol/core-internal';\n\n/**\n * A change event a server publishes for delivery on open `subscriptions/listen`\n * streams. Each variant maps onto exactly one notification method:\n *\n * - `tools_list_changed` → `notifications/tools/list_changed`\n * - `prompts_list_changed` → `notifications/prompts/list_changed`\n * - `resources_list_changed` → `notifications/resources/list_changed`\n * - `resource_updated` → `notifications/resources/updated` (carries the URI)\n *\n * The bus carries the EVENT, not the wire shape — the entry's listen router\n * owns subscription-id stamping and per-stream filtering.\n */\nexport type ServerEvent =\n | { kind: 'tools_list_changed' }\n | { kind: 'prompts_list_changed' }\n | { kind: 'resources_list_changed' }\n | { kind: 'resource_updated'; uri: string };\n\n/**\n * The server-side change-event seam for `subscriptions/listen`.\n *\n * The serving entry (`createMcpHandler`) owns the per-stream listen router:\n * each open `subscriptions/listen` stream registers a listener via\n * `subscribe()`, and consumer code (typically via `handler.notify.*` sugar)\n * publishes change events via `publish()`. In-process servers can use the\n * default {@linkcode InMemoryServerEventBus}; multi-process deployments\n * implement this interface over their own pub/sub.\n *\n * The SDK owns wire semantics (ack-first, filtering, subscription-id\n * stamping, teardown); a `ServerEventBus` only sources the events. It MUST\n * NOT echo back to the listener that published an event when called from\n * inside that listener (no surprise here — the default delivers\n * synchronously and listeners never publish).\n */\nexport interface ServerEventBus {\n /**\n * Publish a change event to every registered listener.\n */\n publish(event: ServerEvent): void;\n /**\n * Register a listener; returns an idempotent unsubscribe function.\n */\n subscribe(listener: (event: ServerEvent) => void): () => void;\n}\n\n/**\n * A `ServerEventBus` backed by an in-process listener set.\n *\n * `publish()` delivers synchronously to the live listener set (a listener\n * unsubscribing itself mid-dispatch is safe; the entry's listen-router\n * listeners never unsubscribe peers). A throwing listener does not stop\n * delivery to the others.\n */\nexport class InMemoryServerEventBus implements ServerEventBus {\n private readonly _listeners = new Set<(event: ServerEvent) => void>();\n\n /**\n * @param onerror - Optional callback for errors thrown by listeners\n * during dispatch.\n */\n constructor(private readonly onerror?: (error: Error) => void) {}\n\n publish(event: ServerEvent): void {\n for (const listener of this._listeners) {\n try {\n listener(event);\n } catch (error) {\n this.onerror?.(error instanceof Error ? error : new Error(String(error)));\n }\n }\n }\n\n subscribe(listener: (event: ServerEvent) => void): () => void {\n this._listeners.add(listener);\n let live = true;\n return () => {\n if (!live) return;\n live = false;\n this._listeners.delete(listener);\n };\n }\n\n /** The number of currently registered listeners (test/introspection only — the routers track capacity via their own open-subscription set). */\n get listenerCount(): number {\n return this._listeners.size;\n }\n}\n\n/**\n * Typed publish-side facade over `bus.publish` returned by `createMcpHandler`:\n * each method publishes the corresponding {@linkcode ServerEvent}. Prefer this\n * over calling `bus.publish` directly — the names match the wire methods.\n */\nexport interface ServerNotifier {\n /** Publish `notifications/tools/list_changed` to every open subscription that opted in. */\n toolsChanged(): void;\n /** Publish `notifications/prompts/list_changed` to every open subscription that opted in. */\n promptsChanged(): void;\n /** Publish `notifications/resources/list_changed` to every open subscription that opted in. */\n resourcesChanged(): void;\n /** Publish `notifications/resources/updated` for `uri` to every open subscription that opted in to that URI. */\n resourceUpdated(uri: string): void;\n}\n\n/** Build a {@linkcode ServerNotifier} over a bus. */\nexport function createServerNotifier(bus: ServerEventBus): ServerNotifier {\n return {\n toolsChanged: () => bus.publish({ kind: 'tools_list_changed' }),\n promptsChanged: () => bus.publish({ kind: 'prompts_list_changed' }),\n resourcesChanged: () => bus.publish({ kind: 'resources_list_changed' }),\n resourceUpdated: (uri: string) => bus.publish({ kind: 'resource_updated', uri })\n };\n}\n\n/**\n * Whether a `subscriptions/listen` filter accepts a given change event.\n *\n * Pure: no I/O, no mutation. The filter governs ONLY the four\n * subscription-gated change types — non-gated notifications never reach the\n * bus and are not modeled here.\n *\n * `resource_updated` matches only when `resourceSubscriptions` is present and\n * contains the event's URI exactly (per the spec: \"for these resource URIs\").\n */\nexport function listenFilterAccepts(filter: SubscriptionFilter, event: ServerEvent): boolean {\n switch (event.kind) {\n case 'tools_list_changed': {\n return filter.toolsListChanged === true;\n }\n case 'prompts_list_changed': {\n return filter.promptsListChanged === true;\n }\n case 'resources_list_changed': {\n return filter.resourcesListChanged === true;\n }\n case 'resource_updated': {\n return filter.resourceSubscriptions !== undefined && filter.resourceSubscriptions.includes(event.uri);\n }\n }\n}\n\n/**\n * The honored subset of a requested filter: keeps only the fields the client\n * explicitly opted in to (drops `false` and absent fields), narrowed against\n * the server's declared capabilities when supplied. The serving entry sends\n * this back in `notifications/subscriptions/acknowledged` so the ack reflects\n * what the server can actually deliver.\n *\n * - `toolsListChanged` is honored only when `capabilities.tools.listChanged`\n * is advertised; likewise `promptsListChanged` / `resourcesListChanged`.\n * - `resourceSubscriptions` is honored only when\n * `capabilities.resources.subscribe` is advertised.\n *\n * `capabilities` is optional on this pure helper for test convenience only —\n * both wired routers REQUIRE capabilities at the call site (the HTTP router's\n * `serve()` takes a required parameter; `StdioListenRouter.serve()` throws\n * before `setServerCapabilities()` was called), so the fail-open\n * `undefined → honor everything` branch is never reachable on a wired entry.\n */\nexport function honoredSubset(requested: SubscriptionFilter, capabilities?: ServerCapabilities): SubscriptionFilter {\n const honored: SubscriptionFilter = {};\n const allow = (bit: unknown): boolean => capabilities === undefined || bit === true;\n if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true;\n if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true;\n if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true;\n if (\n requested.resourceSubscriptions !== undefined &&\n requested.resourceSubscriptions.length > 0 &&\n allow(capabilities?.resources?.subscribe)\n ) {\n honored.resourceSubscriptions = [...requested.resourceSubscriptions];\n }\n return honored;\n}\n\n/** Map a {@linkcode ServerEvent} onto its wire notification `{method, params}`. */\nexport function serverEventToNotification(event: ServerEvent): { method: string; params?: { uri: string } } {\n switch (event.kind) {\n case 'tools_list_changed': {\n return { method: 'notifications/tools/list_changed' };\n }\n case 'prompts_list_changed': {\n return { method: 'notifications/prompts/list_changed' };\n }\n case 'resources_list_changed': {\n return { method: 'notifications/resources/list_changed' };\n }\n case 'resource_updated': {\n return { method: 'notifications/resources/updated', params: { uri: event.uri } };\n }\n }\n}\n","/**\n * The entry-handled `subscriptions/listen` router for the HTTP serving entry.\n *\n * `createMcpHandler` recognizes a modern-classified `subscriptions/listen`\n * request and routes it here: the entry owns ack-first, per-stream filtering,\n * subscription-id stamping, keepalive, capacity guarding, and teardown. The\n * consumer's factory IS constructed for listen, to read the instance's\n * declared `ServerCapabilities` only — the probe instance is never connected\n * and is closed immediately after the capabilities read. Token verification\n * and any per-request authorization still belong at the middleware layer\n * mounted in front of `createMcpHandler` (the entry's documented authz\n * posture).\n *\n * Per the spec at protocol revision 2026-07-28:\n * - The acknowledged notification is the FIRST message on the stream and\n * carries the honored subset of the requested filter.\n * - Every notification on the stream (including the ack) carries the listen\n * request's JSON-RPC id under `_meta['io.modelcontextprotocol/subscriptionId']`.\n * - The server MUST NOT deliver a notification type the client did not request.\n * - Server-side graceful close (`closeAll()`) emits the empty\n * `subscriptions/listen` JSON-RPC result (the `SubscriptionsListenResult` —\n * `_meta` carries the subscription id) before closing the stream; an abrupt\n * transport close carries no response and the client treats it as a\n * disconnect.\n */\nimport type { JSONRPCRequest, RequestId, ServerCapabilities, SubscriptionFilter } from '@modelcontextprotocol/core-internal';\nimport { codecForVersion, MODERN_WIRE_REVISION, SUBSCRIPTION_ID_META_KEY } from '@modelcontextprotocol/core-internal';\n\nimport type { ServerEventBus } from './serverEventBus';\nimport { honoredSubset, listenFilterAccepts, serverEventToNotification } from './serverEventBus';\n\n/** Default SSE comment-frame keepalive interval for listen streams. */\nexport const DEFAULT_LISTEN_KEEPALIVE_MS = 15_000;\n\n/** Default capacity guard: refuse a new subscription when this many are already open. */\nexport const DEFAULT_MAX_SUBSCRIPTIONS = 1024;\n\n/** Options for {@linkcode createListenRouter}. */\nexport interface ListenRouterOptions {\n /** The event bus listen streams subscribe to. */\n bus: ServerEventBus;\n /** Reject a new listen with `-32603` when this many subscriptions are already open (default 1024). */\n maxSubscriptions?: number;\n /** SSE comment-frame keepalive interval; `0` disables keepalive (default 15000). */\n keepAliveMs?: number;\n /** Out-of-band error reporting (never alters the response). */\n onerror?: (error: Error) => void;\n}\n\n/**\n * A wire-shape notification body (method + loose params).\n * @internal\n */\nexport interface NotificationBody {\n method: string;\n params: { _meta?: Record<string, unknown>; [key: string]: unknown };\n}\n\nfunction jsonRpcError(id: RequestId | null, code: number, message: string): Response {\n return Response.json({ jsonrpc: '2.0', error: { code, message }, id }, { status: 200 });\n}\n\n/** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */\nfunction stampSubscriptionId(\n notification: { method: string; params?: { _meta?: Record<string, unknown>; [key: string]: unknown } },\n subscriptionId: RequestId\n): NotificationBody {\n return {\n method: notification.method,\n params: {\n ...notification.params,\n _meta: { ...notification.params?._meta, [SUBSCRIPTION_ID_META_KEY]: subscriptionId }\n }\n };\n}\n\n/**\n * Read the requested filter off a `subscriptions/listen` request body.\n * Returns the validated filter, or `undefined` when `params.notifications`\n * is absent or fails the schema (the caller answers `-32602` — the spec\n * marks `notifications` REQUIRED on the listen request).\n */\nexport function parseListenFilter(message: JSONRPCRequest): SubscriptionFilter | undefined {\n // `subscriptions/listen` is 2026-only vocabulary; route through the era\n // codec's request validator (the wire layer owns the filter schema).\n const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest('subscriptions/listen', message);\n return outcome.ok ? outcome.value.params?.notifications : undefined;\n}\n\n/**\n * The HTTP listen router: holds the set of open subscriptions and serves\n * each listen request as an SSE response.\n */\nexport interface ListenRouter {\n /**\n * Serve one `subscriptions/listen` request and return the SSE `Response`\n * (or, on capacity / params rejection, the in-band JSON-RPC error\n * `Response`). The ack notification is the first SSE frame.\n *\n * `capabilities` is required: the acknowledged filter is always narrowed\n * against what the serving instance advertises (honoring a filter without\n * capabilities would fail open and deliver unadvertised types).\n */\n serve(message: JSONRPCRequest, signal: AbortSignal | undefined, capabilities: ServerCapabilities): Response;\n /**\n * Gracefully close every open subscription stream: emits the empty\n * `subscriptions/listen` JSON-RPC result (the spec's graceful-close\n * signal) as the final SSE frame, then closes the stream.\n */\n closeAll(): void;\n /** The number of currently open subscription streams (for tests / introspection). */\n readonly openCount: number;\n}\n\nexport function createListenRouter(options: ListenRouterOptions): ListenRouter {\n const { bus, onerror } = options;\n const maxSubscriptions = options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS;\n const keepAliveMs = options.keepAliveMs ?? DEFAULT_LISTEN_KEEPALIVE_MS;\n\n const open = new Set<(graceful: boolean) => void>();\n\n function serve(message: JSONRPCRequest, signal: AbortSignal | undefined, capabilities: ServerCapabilities): Response {\n // Capacity guard, pre-ack: in-band -32603 on HTTP 200.\n if (open.size >= maxSubscriptions) {\n onerror?.(new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`));\n return jsonRpcError(message.id, -32_603, 'Subscription limit reached');\n }\n const filter = parseListenFilter(message);\n if (filter === undefined) {\n return jsonRpcError(message.id, -32_602, \"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter\");\n }\n const honored = honoredSubset(filter, capabilities);\n // The spec carries the listen request's JSON-RPC id verbatim as the\n // subscription id; demux is per-connection (each HTTP listen has its\n // own SSE stream) so client-chosen ids cannot route across requests.\n const subscriptionId = message.id;\n\n const encoder = new TextEncoder();\n let controller!: ReadableStreamDefaultController<Uint8Array>;\n let closed = false;\n let unsubscribe: (() => void) | undefined;\n let keepAliveTimer: ReturnType<typeof setInterval> | undefined;\n let abortCleanup: (() => void) | undefined;\n\n const writeFrame = (frame: string) => {\n if (closed) return;\n try {\n controller.enqueue(encoder.encode(frame));\n } catch (error) {\n onerror?.(error instanceof Error ? error : new Error(String(error)));\n }\n };\n const writeNotification = (method: string, params: { _meta?: Record<string, unknown>; [key: string]: unknown }) => {\n writeFrame(`event: message\\ndata: ${JSON.stringify({ jsonrpc: '2.0', method, params })}\\n\\n`);\n };\n\n const teardown = (graceful: boolean) => {\n if (closed) return;\n if (graceful) {\n // Server-side graceful close: emit the empty\n // `subscriptions/listen` JSON-RPC result before closing the\n // stream so the client distinguishes graceful end from a\n // transport drop. Written before `closed = true` so writeFrame\n // still enqueues.\n writeFrame(\n `event: message\\ndata: ${JSON.stringify({\n jsonrpc: '2.0',\n id: subscriptionId,\n result: { resultType: 'complete', _meta: { [SUBSCRIPTION_ID_META_KEY]: subscriptionId } }\n })}\\n\\n`\n );\n }\n closed = true;\n unsubscribe?.();\n if (keepAliveTimer !== undefined) clearInterval(keepAliveTimer);\n abortCleanup?.();\n open.delete(teardown);\n try {\n controller.close();\n } catch {\n // Already closed/cancelled by the consumer.\n }\n };\n\n const readable = new ReadableStream<Uint8Array>({\n start(streamController) {\n controller = streamController;\n\n // Ack-first MUST: the acknowledged notification is the first\n // frame on the stream, stamped with the subscription id.\n const ack = stampSubscriptionId(\n { method: 'notifications/subscriptions/acknowledged', params: { notifications: honored } },\n subscriptionId\n );\n writeNotification(ack.method, ack.params);\n\n // Only after the ack frame is enqueued does delivery activate.\n unsubscribe = bus.subscribe(event => {\n if (closed || !listenFilterAccepts(honored, event)) return;\n const note = stampSubscriptionId(serverEventToNotification(event), subscriptionId);\n writeNotification(note.method, note.params);\n });\n\n if (keepAliveMs > 0) {\n keepAliveTimer = setInterval(() => writeFrame(': keepalive\\n\\n'), keepAliveMs);\n // Do not hold the event loop open on idle subscriptions. Node's\n // setInterval returns a Timeout with .unref(); browsers/Workers\n // return a number — the cast is an environment shim, not a\n // workaround for SDK typing.\n (keepAliveTimer as { unref?: () => void }).unref?.();\n }\n\n open.add(teardown);\n },\n cancel() {\n // The client closed the SSE stream — the spec's HTTP cancel\n // signal. Not a server-side graceful close, so no listen\n // result is written (and the consumer is gone anyway).\n teardown(false);\n }\n });\n\n if (signal !== undefined) {\n if (signal.aborted) {\n teardown(false);\n } else {\n const onAbort = () => teardown(false);\n signal.addEventListener('abort', onAbort, { once: true });\n abortCleanup = () => signal.removeEventListener('abort', onAbort);\n }\n }\n\n return new Response(readable, {\n status: 200,\n headers: {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive',\n 'X-Accel-Buffering': 'no'\n }\n });\n }\n\n return {\n serve,\n closeAll() {\n for (const teardown of open) teardown(true);\n },\n get openCount() {\n return open.size;\n }\n };\n}\n\n/* ------------------------------------------------------------------------ *\n * Stdio listen router\n * ------------------------------------------------------------------------ */\n\nconst CHANGE_NOTIFICATION_METHODS: ReadonlySet<string> = new Set([\n 'notifications/tools/list_changed',\n 'notifications/prompts/list_changed',\n 'notifications/resources/list_changed',\n 'notifications/resources/updated'\n]);\n\n/**\n * Per-connection listen state for the stdio entry. One instance is held by\n * `serveStdio` for the connection lifetime; it routes inbound\n * `subscriptions/listen` / `notifications/cancelled` and rewrites outbound\n * change notifications onto the active subscriptions. No bus — the long-lived\n * pinned instance's existing `send*ListChanged()` calls feed straight into\n * `routeOutbound()`.\n */\nexport class StdioListenRouter {\n /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */\n private readonly _subs = new Map<RequestId, SubscriptionFilter>();\n /**\n * The serving instance's declared capabilities. Filled in by the entry\n * once the modern instance is constructed (the router is created before\n * the instance exists), so the acknowledged filter is narrowed against\n * what the server can actually deliver.\n */\n private _serverCapabilities: ServerCapabilities | undefined;\n\n constructor(\n private readonly _maxSubscriptions: number = DEFAULT_MAX_SUBSCRIPTIONS,\n serverCapabilities?: ServerCapabilities\n ) {\n this._serverCapabilities = serverCapabilities;\n }\n\n /**\n * Record the serving instance's declared capabilities once it has been\n * constructed. Called by `serveStdio`'s connect path; subsequent\n * `serve()` calls narrow the honored filter against these.\n */\n setServerCapabilities(capabilities: ServerCapabilities): void {\n this._serverCapabilities = capabilities;\n }\n\n /** Whether `id` is an active listen subscription on this connection. */\n has(id: RequestId): boolean {\n return this._subs.has(id);\n }\n\n /**\n * Serve one inbound `subscriptions/listen` request: registers the\n * subscription and returns the stamped acknowledged notification (or, on\n * capacity / params rejection, the in-band JSON-RPC error response).\n *\n * @throws when called before {@linkcode setServerCapabilities} (or the\n * constructor) has supplied the serving instance's capabilities. Honoring a\n * filter without knowing the server's advertised capabilities would fail\n * open (deliver unadvertised types); the entry guarantees capabilities are\n * set before any listen request is routed here.\n */\n serve(message: JSONRPCRequest): NotificationBody | { jsonrpc: '2.0'; id: RequestId; error: { code: number; message: string } } {\n if (this._serverCapabilities === undefined) {\n throw new Error(\n 'StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities'\n );\n }\n if (this._subs.size >= this._maxSubscriptions) {\n return { jsonrpc: '2.0', id: message.id, error: { code: -32_603, message: 'Subscription limit reached' } };\n }\n const filter = parseListenFilter(message);\n if (filter === undefined) {\n return {\n jsonrpc: '2.0',\n id: message.id,\n error: { code: -32_602, message: \"Invalid params: 'notifications' is required and must be a valid SubscriptionFilter\" }\n };\n }\n const honored = honoredSubset(filter, this._serverCapabilities);\n this._subs.set(message.id, honored);\n return stampSubscriptionId({ method: 'notifications/subscriptions/acknowledged', params: { notifications: honored } }, message.id);\n }\n\n /**\n * Tear down one subscription (inbound `notifications/cancelled`). Returns\n * `true` when a subscription was removed. After this call NOTHING further\n * is delivered for that subscription id (the post-cancel hardening).\n */\n cancel(id: RequestId): boolean {\n return this._subs.delete(id);\n }\n\n /**\n * Route an outbound notification through the active subscriptions.\n *\n * - For a subscription-gated change notification, returns one stamped copy\n * per subscription that opted in to it (an empty array means it is\n * dropped — the modern era never delivers an un-requested change type).\n * - For any other outbound message, returns `'passthrough'` (the entry\n * forwards it as-is).\n */\n routeOutbound(message: { method: string; params?: { [key: string]: unknown } }): NotificationBody[] | 'passthrough' {\n if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) {\n return 'passthrough';\n }\n const uriParam: unknown = message.params?.['uri'];\n const uri = typeof uriParam === 'string' ? uriParam : undefined;\n const event = notificationToServerEvent(message.method, uri);\n const out: NotificationBody[] = [];\n for (const [subscriptionId, filter] of this._subs) {\n if (listenFilterAccepts(filter, event)) {\n out.push(stampSubscriptionId({ method: message.method, params: message.params ?? {} }, subscriptionId));\n }\n }\n return out;\n }\n\n /**\n * Server-side graceful teardown of every active subscription: returns the\n * empty `subscriptions/listen` JSON-RPC result for each subscription id —\n * the spec's graceful-close signal — for the entry to emit before closing\n * the wire. Clears the set so nothing further is delivered.\n */\n teardownAll(): {\n jsonrpc: '2.0';\n id: RequestId;\n result: { resultType: 'complete'; _meta: { [SUBSCRIPTION_ID_META_KEY]: RequestId } };\n }[] {\n const out: {\n jsonrpc: '2.0';\n id: RequestId;\n result: { resultType: 'complete'; _meta: { [SUBSCRIPTION_ID_META_KEY]: RequestId } };\n }[] = [];\n for (const id of this._subs.keys()) {\n out.push({ jsonrpc: '2.0', id, result: { resultType: 'complete', _meta: { [SUBSCRIPTION_ID_META_KEY]: id } } });\n }\n this._subs.clear();\n return out;\n }\n}\n\nfunction notificationToServerEvent(method: string, uri: string | undefined): import('./serverEventBus').ServerEvent {\n switch (method) {\n case 'notifications/tools/list_changed': {\n return { kind: 'tools_list_changed' };\n }\n case 'notifications/prompts/list_changed': {\n return { kind: 'prompts_list_changed' };\n }\n case 'notifications/resources/list_changed': {\n return { kind: 'resources_list_changed' };\n }\n default: {\n return { kind: 'resource_updated', uri: uri ?? '' };\n }\n }\n}\n","/**\n * The legacy `input_required` shim: serves write-once handlers on 2025-era\n * sessions. `Server` holds one instance and delegates to it from the\n * multi-round-trip seam when a handler returns an input-required result on a\n * 2025-era request: each embedded request goes out as a real server→client\n * request (`elicitation/create` / `sampling/createMessage` / `roots/list`,\n * stamped with the originating request id for stream association), and the\n * handler is re-entered with the collected `inputResponses` until it returns\n * a final result or the round cap is exhausted.\n *\n * Semantics mirror the modern client driver so a handler cannot tell which\n * era fulfilled it: per-round REPLACED `inputResponses`, byte-exact\n * `requestState` echo (re-verified by the configured hook each round), paced\n * requestState-only rounds. The loop lives inside the originating request's\n * lifetime — nothing is parked, cancellation chains through every leg.\n * Failures surface per family: tools/call → `isError` tool results,\n * prompts/resources → JSON-RPC errors; malformed results fail loudly as\n * server bugs. Package-internal — not exported from the index.\n */\nimport type {\n ClientCapabilities,\n CreateMessageRequest,\n ElicitRequestFormParams,\n ElicitRequestURLParams,\n JSONRPCRequest,\n RequestOptions,\n Result,\n ServerContext\n} from '@modelcontextprotocol/core-internal';\nimport {\n inputRequiredRoundsExceededMessage,\n isInputRequiredResult,\n linkedRoundAbort,\n missingClientCapabilities,\n ProtocolError,\n ProtocolErrorCode,\n REQUEST_STATE_ONLY_LEG_PACING_MS,\n requestStateAccessor,\n requiredClientCapabilitiesForInputRequest,\n sleep,\n withRequestStateValue\n} from '@modelcontextprotocol/core-internal';\n\n/**\n * Default handler re-entries per originating request — tighter than the\n * client driver's 10 because the shim holds a live wire request open.\n */\nconst DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8;\n\n/** Default per-leg timeout: legs are human-paced, so the 60s protocol default is wrong. */\nconst DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 600_000;\n\n/** The `ServerOptions.inputRequired` bag with defaults applied. */\nexport interface ResolvedLegacyShimOptions {\n maxRounds: number;\n roundTimeoutMs: number;\n legacyShim: boolean;\n}\n\n/** Resolves and validates `ServerOptions.inputRequired`, failing loudly at construction time. */\nexport function resolveLegacyShimOptions(\n options: { maxRounds?: number; roundTimeoutMs?: number; legacyShim?: boolean } | undefined\n): ResolvedLegacyShimOptions {\n if (options?.maxRounds !== undefined && (!Number.isInteger(options.maxRounds) || options.maxRounds < 1)) {\n throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`);\n }\n if (options?.roundTimeoutMs !== undefined && (!Number.isFinite(options.roundTimeoutMs) || options.roundTimeoutMs <= 0)) {\n throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`);\n }\n return {\n maxRounds: options?.maxRounds ?? DEFAULT_LEGACY_SHIM_MAX_ROUNDS,\n roundTimeoutMs: options?.roundTimeoutMs ?? DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS,\n legacyShim: options?.legacyShim ?? true\n };\n}\n\n/** The embedded input-request kinds the 2026-07-28 revision defines. */\nexport type EmbeddedInputRequestMethod = 'elicitation/create' | 'sampling/createMessage' | 'roots/list';\n\n/** A coerced `inputRequests` entry: the kind-narrowed embedded request. */\nexport interface CoercedEmbeddedInputRequest {\n method: EmbeddedInputRequestMethod;\n params?: Record<string, unknown>;\n}\n\n/**\n * Validates one `inputRequests` entry: malformed or unknown kinds are server\n * bugs and fail loudly on both eras. Shared by the modern seam's capability\n * check and the shim's gate.\n */\nexport function coerceEmbeddedInputRequest(\n method: string,\n key: string,\n entry: unknown\n): { embedded: CoercedEmbeddedInputRequest; required: ClientCapabilities } {\n if (entry === null || typeof entry !== 'object' || typeof (entry as { method?: unknown }).method !== 'string') {\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an ` +\n `embedded elicitation/create, sampling/createMessage, or roots/list request`\n );\n }\n const embedded = entry as { method: string; params?: Record<string, unknown> };\n const required = requiredClientCapabilitiesForInputRequest(embedded);\n if (required === undefined) {\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an ` +\n `embedded request the 2026-07-28 revision defines`\n );\n }\n return { embedded: embedded as CoercedEmbeddedInputRequest, required };\n}\n\n/**\n * The 2025-11-25 URL-mode wire shape requires an `elicitationId`; the 2026\n * in-band shape has none, so URL legs mint one (CSPRNG-backed, with a\n * getRandomValues fallback for runtimes without `randomUUID`).\n */\nfunction syntheticElicitationId(): string {\n const webCrypto = globalThis.crypto;\n if (webCrypto?.randomUUID !== undefined) {\n return webCrypto.randomUUID();\n }\n const bytes = new Uint8Array(16);\n webCrypto.getRandomValues(bytes);\n bytes[6] = (bytes[6]! & 0x0f) | 0x40;\n bytes[8] = (bytes[8]! & 0x3f) | 0x80;\n const hex = [...bytes].map(byte => byte.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/** Per-family surfacing: tools/call → isError result (the 2025 idiom); prompts/resources → JSON-RPC error. */\nfunction legacyShimFailure(method: string, message: string): Result {\n if (method === 'tools/call') {\n return { content: [{ type: 'text', text: message }], isError: true };\n }\n throw new ProtocolError(ProtocolErrorCode.InternalError, message);\n}\n\n/**\n * Everything the shim needs from `Server`: the knobs, the per-request\n * resolved capability view (initialize state on sessionful legacy; empty on\n * per-request stateless instances), the requestState verify runner\n * (deny-on-error → the frozen `-32602`), and the 2025-era senders. The\n * shim's own gate is authoritative; elicitation accepted content passes\n * through UNVALIDATED for parity with the modern client driver.\n */\nexport interface LegacyInputRequiredShimHost {\n readonly maxRounds: number;\n readonly roundTimeoutMs: number;\n resolvedClientCapabilities(ctx: ServerContext): ClientCapabilities | undefined;\n verifyRequestState(state: string, ctx: ServerContext, method: string): Promise<unknown>;\n sendElicitation(params: ElicitRequestFormParams | ElicitRequestURLParams, options: RequestOptions): Promise<unknown>;\n sendSampling(params: CreateMessageRequest['params'], options: RequestOptions): Promise<unknown>;\n listRoots(params: Record<string, unknown> | undefined, options: RequestOptions): Promise<unknown>;\n}\n\n/** The fulfilment loop — see the module doc for the contract. */\nexport class LegacyInputRequiredShim {\n constructor(private readonly _host: LegacyInputRequiredShimHost) {}\n\n async fulfill(\n method: string,\n handler: (request: JSONRPCRequest, ctx: ServerContext) => Promise<Result>,\n request: JSONRPCRequest,\n ctx: ServerContext,\n firstResult: Result\n ): Promise<Result> {\n const { maxRounds, roundTimeoutMs } = this._host;\n const outerSignal = ctx.mcpReq.signal;\n let current = firstResult;\n let round = 0;\n\n // eslint-disable-next-line no-constant-condition\n while (true) {\n round += 1;\n if (round > maxRounds) {\n return legacyShimFailure(method, inputRequiredRoundsExceededMessage(method, maxRounds));\n }\n\n // At-least-one re-check per round (server bug → loud, as on modern).\n const inputRequests = current.inputRequests as Record<string, unknown> | null | undefined;\n const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0;\n const requestState = typeof current.requestState === 'string' ? current.requestState : undefined;\n if (!hasInputRequests && requestState === undefined) {\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `Handler for ${method} returned an input-required result with neither inputRequests nor requestState ` +\n `(every InputRequiredResult must include at least one of the two)`\n );\n }\n\n let responses: Record<string, unknown> | undefined;\n if (hasInputRequests) {\n // The shim's own capability pre-check (never gated on\n // enforceStrictCapabilities). The whole round gates before\n // any wire traffic, so a refusal has no side effects.\n const declared = this._host.resolvedClientCapabilities(ctx);\n const coerced: [string, CoercedEmbeddedInputRequest][] = [];\n for (const [key, entry] of Object.entries(inputRequests!)) {\n const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry);\n // Request-carrying kinds need params; absent = server bug.\n if (embedded.method !== 'roots/list' && embedded.params === undefined) {\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`\n );\n }\n const missing = missingClientCapabilities(required, declared);\n if (missing !== undefined) {\n return legacyShimFailure(\n method,\n `Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not ` +\n `declare the required capability${declared === undefined ? ' (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)' : ''}`\n );\n }\n coerced.push([key, embedded]);\n }\n\n // Fulfil concurrently (driver parity); first failure aborts siblings.\n const roundAbort = linkedRoundAbort(outerSignal);\n try {\n const legOptions: RequestOptions = {\n relatedRequestId: ctx.mcpReq.id,\n timeout: roundTimeoutMs,\n resetTimeoutOnProgress: true,\n // The no-op handler stamps a progressToken on the leg —\n // without one, resetTimeoutOnProgress could never fire.\n onprogress: () => {},\n signal: roundAbort.signal\n };\n const fulfilled = await Promise.all(\n coerced.map(async ([key, embedded]) => {\n try {\n return [key, await this._dispatchLeg(embedded, legOptions)] as const;\n } catch (error) {\n roundAbort.abort(error);\n throw error;\n }\n })\n );\n responses = Object.fromEntries(fulfilled);\n } catch (error) {\n if (outerSignal.aborted) {\n // Cancelled requests are never answered — propagate.\n throw error;\n }\n return legacyShimFailure(\n method,\n `Fulfilling input required by '${method}' failed: ${error instanceof Error ? error.message : String(error)}`\n );\n } finally {\n roundAbort.dispose();\n }\n } else {\n // requestState-only round: paced so the loop never hot-spins\n // (driver parity); counted in the same round cap.\n await sleep(REQUEST_STATE_ONLY_LEG_PACING_MS, outerSignal);\n }\n\n // Byte-exact requestState echo: build the round's context first,\n // verify against it (the order and view a modern wire retry\n // gets), then swap in the decoded payload. Deny-on-error → -32602.\n let ctxNext: ServerContext = {\n ...ctx,\n mcpReq: {\n ...ctx.mcpReq,\n // REPLACE semantics: this round's responses only — multi-step\n // flows thread earlier answers through requestState.\n inputResponses: responses,\n droppedInputResponseKeys: undefined,\n requestState: requestStateAccessor(requestState)\n }\n };\n if (requestState !== undefined) {\n const decoded = await this._host.verifyRequestState(requestState, ctxNext, method);\n if (decoded !== undefined) {\n ctxNext = withRequestStateValue(ctxNext, decoded);\n }\n }\n\n // Re-entry hits the same stored handler a wire retry would\n // (for McpServer: the full funnel).\n const next = await handler(request, ctxNext);\n if (!isInputRequiredResult(next)) {\n return next;\n }\n current = next;\n }\n }\n\n /** Routes one embedded request through the host's existing 2025-era senders (gate already ran). */\n private async _dispatchLeg(embedded: CoercedEmbeddedInputRequest, options: RequestOptions): Promise<unknown> {\n switch (embedded.method) {\n case 'elicitation/create': {\n let params = embedded.params as ElicitRequestFormParams | ElicitRequestURLParams;\n if (params.mode === 'url' && (params as ElicitRequestURLParams).elicitationId === undefined) {\n params = { ...(params as ElicitRequestURLParams), elicitationId: syntheticElicitationId() };\n }\n return await this._host.sendElicitation(params, options);\n }\n case 'sampling/createMessage': {\n return await this._host.sendSampling(embedded.params as CreateMessageRequest['params'], options);\n }\n case 'roots/list': {\n return await this._host.listRoots(embedded.params, options);\n }\n }\n }\n}\n","import type {\n BaseContext,\n CacheableResultMethod,\n CacheHint,\n CallToolResult,\n ClientCapabilities,\n CreateMessageRequest,\n CreateMessageRequestParamsBase,\n CreateMessageRequestParamsWithTools,\n CreateMessageResult,\n CreateMessageResultWithTools,\n DiscoverResult,\n ElicitRequestFormParams,\n ElicitRequestURLParams,\n ElicitResult,\n EmptyResult,\n Implementation,\n InitializeRequest,\n InitializeResult,\n JSONRPCRequest,\n JsonSchemaType,\n jsonSchemaValidator,\n ListRootsRequest,\n ListRootsResult,\n LoggingLevel,\n LoggingMessageNotification,\n MessageExtraInfo,\n NotificationMethod,\n NotificationOptions,\n ProtocolOptions,\n RequestMethod,\n RequestOptions,\n ResourceUpdatedNotification,\n Result,\n ServerCapabilities,\n ServerContext,\n ToolResultContent,\n ToolUseContent\n} from '@modelcontextprotocol/core-internal';\nimport {\n assertValidCacheHint,\n attachCacheHintFallback,\n CLIENT_CAPABILITIES_META_KEY,\n codecForVersion,\n isInputRequiredResult,\n isModernProtocolVersion,\n LATEST_PROTOCOL_VERSION,\n legacyProtocolVersions,\n LOG_LEVEL_META_KEY,\n LoggingLevelSchema,\n mergeCapabilities,\n missingClientCapabilities,\n MissingRequiredClientCapabilityError,\n modernProtocolVersions,\n parseSchema,\n Protocol,\n ProtocolError,\n ProtocolErrorCode,\n SdkError,\n SdkErrorCode,\n withRequestStateValue\n} from '@modelcontextprotocol/core-internal';\nimport { DefaultJsonSchemaValidator } from '@modelcontextprotocol/server/_shims';\n\nimport { coerceEmbeddedInputRequest, LegacyInputRequiredShim, resolveLegacyShimOptions } from './legacyInputRequiredShim';\n\n/**\n * The request methods whose 2026-07-28 result vocabulary includes\n * `input_required` (the multi round-trip methods). Returning an\n * input-required result from any other handler is a server bug.\n */\nconst INPUT_REQUIRED_CAPABLE_METHODS: ReadonlySet<string> = new Set(['tools/call', 'prompts/get', 'resources/read']);\n\nexport type ServerOptions = ProtocolOptions & {\n /**\n * Capabilities to advertise as being supported by this server.\n *\n * Note: per the MCP spec, a server that declares a capability MUST respond to that\n * capability's requests (e.g. `tools/list` for `tools`) — potentially with an empty\n * result — rather than with a \"Method not found\" error. {@linkcode server/mcp.McpServer | McpServer}\n * handles this automatically for capabilities declared here; when using the low-level\n * {@linkcode Server} directly, you are responsible for registering a request handler for\n * every capability you declare.\n */\n capabilities?: ServerCapabilities;\n\n /**\n * Optional instructions describing how to use the server and its features.\n */\n instructions?: string;\n\n /**\n * JSON Schema validator for elicitation response validation.\n *\n * The validator is used to validate user input returned from elicitation\n * requests against the requested schema.\n *\n * @default Runtime-selected validator (AJV-backed on Node.js, `@cfworker/json-schema`-backed on browser/workerd runtimes)\n */\n jsonSchemaValidator?: jsonSchemaValidator;\n\n /**\n * Cache hints for the cacheable results of the 2026-07-28 protocol\n * revision (`ttlMs` / `cacheScope`), keyed by operation. The cacheable\n * operations are `tools/list`, `prompts/list`, `resources/list`,\n * `resources/templates/list`, `resources/read` and `server/discover`. The\n * hint is used when the result for that operation does not provide its own\n * cache fields — most useful for the list results and `server/discover`,\n * which the SDK builds itself. A hint registered with an individual\n * resource (`registerResource(..., { cacheHint })`) takes precedence for\n * that resource's `resources/read` results, field by field: a field the\n * per-resource hint leaves unset still falls back to the per-operation\n * hint configured here.\n *\n * Absent hints (or omitting this option entirely) keep today's behavior:\n * cacheable 2026-07-28 results are emitted with `ttlMs: 0` and\n * `cacheScope: 'private'`. Responses to 2025-era requests are never\n * affected. Invalid values throw a `RangeError` at construction time.\n */\n cacheHints?: Partial<Record<CacheableResultMethod, CacheHint>>;\n\n /**\n * Multi-round-trip serving knobs. On 2026-era requests the client\n * fulfils `input_required` returns; on 2025-era connections the SDK's\n * legacy shim fulfils them server-side (real server→client requests +\n * handler re-entry), so handlers are written once and serve both eras.\n */\n inputRequired?: {\n /**\n * Handler re-entries per originating request before the shim fails\n * (tools/call: `isError` result; prompts/resources: JSON-RPC error).\n * @default 8\n */\n maxRounds?: number;\n\n /**\n * Per-leg timeout (ms) for the shim's embedded server→client\n * requests, sent with `resetTimeoutOnProgress: true`. Human-paced —\n * deliberately far above the 60s protocol default.\n * @default 600_000\n */\n roundTimeoutMs?: number;\n\n /**\n * `false` disables the shim: an `input_required` return on a\n * 2025-era request fails loudly (the pre-shim behavior).\n * @default true\n */\n legacyShim?: boolean;\n };\n\n /**\n * Multi-round-trip `requestState` integrity hook (protocol revision\n * 2026-07-28).\n */\n requestState?: {\n /**\n * Called on every multi-round-trip request round whose echoed\n * `requestState` is a string (i.e. whenever\n * `ctx.mcpReq.requestState()` would return one), BEFORE the handler\n * runs — including the legacy shim's in-process rounds. Throw or\n * reject to refuse the request: the seam answers with a wire-level\n * `-32602` Invalid Params error whose message is frozen to\n * `\"Invalid or expired requestState\"` and whose `data.reason` is\n * `'invalid_request_state'` — the thrown reason is surfaced via the\n * server's `onerror` callback only and never reaches the wire.\n *\n * This is the place to put HMAC or AEAD verification of\n * `requestState`. The spec MUST for integrity-protecting state that\n * influences authorization, resource access, or business logic is on\n * the server author (basic/patterns/mrtr, server requirements 4–5);\n * the SDK provides NO default verification —\n * {@linkcode server/requestStateCodec.createRequestStateCodec | createRequestStateCodec}\n * is the SDK-provided HMAC helper whose `verify` drops in here\n * directly. Leaving this option unconfigured keeps the passthrough\n * behavior — `ctx.mcpReq.requestState()` returns the raw wire string,\n * which MUST be treated as attacker-controlled input.\n *\n * The resolved value is LOAD-BEARING: when the hook resolves with a\n * non-`undefined` value — as\n * {@linkcode server/requestStateCodec.RequestStateCodec | RequestStateCodec}`.verify`\n * does (the decoded payload) — the seam hands THAT value to the\n * handler via the typed `ctx.mcpReq.requestState<T>()` accessor, so a\n * codec-using handler reads its verified state with no second decode\n * call. A verifier that is not also the decoder should resolve\n * `undefined` (return nothing) to keep the accessor on the raw wire\n * string — resolving an incidental value (e.g. a boolean\n * verification flag) would replace what the handler reads.\n */\n verify?: (state: string, ctx: ServerContext) => unknown | Promise<unknown>;\n };\n};\n\n/*\n * Package-internal hooks for the 2026-07-28 serving entries (the per-request\n * HTTP entry `createMcpHandler` and the connection-pinned stdio entry\n * `serveStdio`).\n *\n * The connection-scoped client-identity fields and the modern-only handler set are\n * private to `Server`; the serving entries in this package need to write/install\n * them on the fresh instance they get from a consumer factory. The static initializer\n * below hands these module-scoped closures privileged access; the exported wrappers\n * are imported by sibling modules in this package only and are deliberately NOT\n * re-exported from the package index (they are not public API).\n */\nlet writeClientIdentity: (server: Server, identity: PerRequestClientIdentity) => void;\nlet installDiscoverHandler: (server: Server, servedModernVersions: readonly string[]) => void;\n\n/** Connection-scoped client-identity fields backfilled per request from a validated `_meta` envelope. */\nexport interface PerRequestClientIdentity {\n /** The client's name/version information, when the envelope carried it. */\n clientInfo?: Implementation;\n /** The client's declared capabilities, when the envelope carried them. */\n clientCapabilities?: ClientCapabilities;\n}\n\n/**\n * Package-internal: backfills the connection-scoped client-identity fields of a\n * per-request server instance from the request's validated `_meta` envelope, so the\n * (deprecated) {@linkcode Server.getClientCapabilities} / {@linkcode Server.getClientVersion}\n * accessors keep answering on instances that never see an `initialize` handshake.\n * Not public API.\n */\nexport function seedClientIdentityFromEnvelope(server: Server, identity: PerRequestClientIdentity): void {\n writeClientIdentity(server, identity);\n}\n\n/**\n * Package-internal: installs the modern-only `server/discover` handler on an instance\n * the HTTP entry has marked as serving the 2026-07-28 era, and makes sure the modern\n * revisions the entry serves appear in the instance's supported-versions list (so the\n * discover advertisement and version-mismatch errors name them). Idempotent.\n * Hand-constructed instances are unaffected: nothing else calls this, so they keep\n * answering `-32601` unless their own supported-versions list opts into a modern\n * revision. Not public API.\n */\nexport function installModernOnlyHandlers(server: Server, servedModernVersions: readonly string[]): void {\n installDiscoverHandler(server, servedModernVersions);\n}\n\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 * @deprecated Use {@linkcode server/mcp.McpServer | McpServer} instead for the high-level API. Only use `Server` for advanced use cases.\n */\nexport class Server extends Protocol<ServerContext> {\n private _clientCapabilities?: ClientCapabilities;\n private _clientVersion?: Implementation;\n\n static {\n writeClientIdentity = (server, identity) => {\n if (identity.clientCapabilities !== undefined) {\n server._clientCapabilities = identity.clientCapabilities;\n }\n if (identity.clientInfo !== undefined) {\n server._clientVersion = identity.clientInfo;\n }\n };\n installDiscoverHandler = (server, servedModernVersions) => {\n const missing = servedModernVersions.filter(version => !server._supportedProtocolVersions.includes(version));\n if (missing.length > 0) {\n // Never mutate the existing array in place: the default supported-versions\n // list is a shared module constant.\n server._supportedProtocolVersions = [...server._supportedProtocolVersions, ...missing];\n }\n server.setRequestHandler('server/discover', () => server._ondiscover());\n };\n }\n private _capabilities: ServerCapabilities;\n private _instructions?: string;\n private _jsonSchemaValidator: jsonSchemaValidator;\n private _cacheHints?: ServerOptions['cacheHints'];\n private _requestStateVerify?: (state: string, ctx: ServerContext) => unknown | Promise<unknown>;\n private _inputRequiredServing: { maxRounds: number; roundTimeoutMs: number; legacyShim: boolean };\n private _legacyShim?: LegacyInputRequiredShim;\n\n /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */\n private _legacyInputRequiredShim(): LegacyInputRequiredShim {\n return (this._legacyShim ??= new LegacyInputRequiredShim({\n maxRounds: this._inputRequiredServing.maxRounds,\n roundTimeoutMs: this._inputRequiredServing.roundTimeoutMs,\n resolvedClientCapabilities: ctx => this._inputRequestCapabilityView(ctx),\n verifyRequestState: (state, ctx, method) => this._verifyRequestState(state, ctx, method),\n sendElicitation: (params, options) => this._sendElicitationLeg(params, options, { validateAcceptedContent: false }),\n sendSampling: (params, options) => this.createMessage(params, options),\n listRoots: (params, options) => this.listRoots(params, options)\n }));\n }\n\n /**\n * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification).\n */\n oninitialized?: () => void;\n\n /**\n * Initializes this server with the given name and version information.\n */\n constructor(\n private _serverInfo: Implementation,\n options?: ServerOptions\n ) {\n super(options);\n this._capabilities = options?.capabilities ? { ...options.capabilities } : {};\n this._instructions = options?.instructions;\n this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new DefaultJsonSchemaValidator();\n this._requestStateVerify = options?.requestState?.verify;\n\n this._inputRequiredServing = resolveLegacyShimOptions(options?.inputRequired);\n\n // Configured cache hints fail loudly at construction time (before any\n // handler registration consults them).\n if (options?.cacheHints !== undefined) {\n for (const [operation, hint] of Object.entries(options.cacheHints)) {\n if (hint !== undefined) {\n assertValidCacheHint(hint, `cacheHints['${operation}']`);\n }\n }\n this._cacheHints = options.cacheHints;\n }\n\n this.setRequestHandler('initialize', request => this._oninitialize(request));\n this.setNotificationHandler('notifications/initialized', () => this.oninitialized?.());\n\n // server/discover is installed only when the supported-versions list\n // carries a modern revision: a legacy-only server keeps answering -32601.\n // A hand-constructed instance is never era-bound, so the handler stays\n // unreachable behind the era gate until a serving entry (createMcpHandler,\n // serveStdio) marks the instance as serving the 2026-07-28 era.\n if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) {\n this.setRequestHandler('server/discover', () => this._ondiscover());\n }\n\n if (this._capabilities.logging) {\n this._registerLoggingHandler();\n }\n }\n\n /**\n * Registers the built-in `logging/setLevel` request handler.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n * Remains functional during the deprecation window (at least twelve months).\n * Migrate to stderr logging (STDIO servers) or OpenTelemetry.\n */\n private _registerLoggingHandler(): void {\n this.setRequestHandler('logging/setLevel', async (request, ctx) => {\n const transportSessionId: string | undefined =\n ctx.sessionId || (ctx.http?.req?.headers.get('mcp-session-id') as string) || undefined;\n const { level } = request.params;\n const parseResult = parseSchema(LoggingLevelSchema, level);\n if (parseResult.success) {\n this._loggingLevels.set(transportSessionId, parseResult.data);\n }\n return {};\n });\n }\n\n protected override buildContext(ctx: BaseContext, transportInfo?: MessageExtraInfo): ServerContext {\n // Only create http when there's actual HTTP transport info or auth info\n const hasHttpInfo = ctx.http || transportInfo?.request || transportInfo?.closeSSEStream || transportInfo?.closeStandaloneSSEStream;\n return {\n ...ctx,\n mcpReq: {\n ...ctx.mcpReq,\n // Deprecated as of protocol version 2026-07-28 (SEP-2577): `log` and\n // `requestSampling` remain functional during the deprecation window\n // (at least twelve months). See ServerContext for migration guidance.\n log: (level, data, logger) => {\n if (!this._capabilities.logging) {\n return Promise.resolve();\n }\n // Level filter: on a 2026-era request the client declares its\n // threshold per request via the `_meta.logLevel` envelope key\n // (the modern equivalent of `logging/setLevel`, which is not a\n // request method on that revision). The spec at 2026-07-28\n // says an absent key means the server MUST NOT send\n // `notifications/message` for the request — so an absent key\n // suppresses, it does not mean \"send everything\". On\n // 2025-era connections the session-scoped level set via\n // `logging/setLevel` applies exactly as before (an absent\n // session level there continues to mean no filter).\n let threshold: LoggingLevel | undefined;\n if (this._servedModernEra()) {\n threshold = ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY] as LoggingLevel | undefined;\n if (threshold === undefined) {\n return Promise.resolve();\n }\n } else {\n threshold = this._loggingLevels.get(ctx.sessionId) ?? this._loggingLevels.get(undefined);\n }\n if (threshold !== undefined && this.LOG_LEVEL_SEVERITY.get(level)! < this.LOG_LEVEL_SEVERITY.get(threshold)!) {\n return Promise.resolve();\n }\n // Emit request-related (like progress and `ctx.mcpReq.notify`)\n // so the notification rides the in-flight exchange. Without the\n // related-request stamp, per-request hosting (`createMcpHandler`,\n // either era) silently drops the message because it has no\n // session-wide stream to deliver it on.\n return ctx.mcpReq.notify({ method: 'notifications/message', params: { level, data, logger } });\n },\n elicitInput: (params, options) => this.elicitInput(params, options),\n requestSampling: (params, options) => this.createMessage(params, options)\n },\n http: hasHttpInfo\n ? {\n ...ctx.http,\n req: transportInfo?.request,\n closeSSE: transportInfo?.closeSSEStream,\n closeStandaloneSSE: transportInfo?.closeStandaloneSSEStream\n }\n : undefined\n };\n }\n\n // Map log levels by session id\n private _loggingLevels = new Map<string | undefined, LoggingLevel>();\n\n // Map LogLevelSchema to severity index\n private readonly LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index]));\n\n // Is a message with the given level ignored in the log level set for the given session id?\n private isMessageIgnored = (level: LoggingLevel, sessionId?: string): boolean => {\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\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 public registerCapabilities(capabilities: ServerCapabilities): void {\n if (this.transport) {\n throw new SdkError(SdkErrorCode.AlreadyConnected, 'Cannot register capabilities after connecting to transport');\n }\n const hadLogging = !!this._capabilities.logging;\n this._capabilities = mergeCapabilities(this._capabilities, capabilities);\n if (!hadLogging && this._capabilities.logging) {\n this._registerLoggingHandler();\n }\n }\n\n /**\n * Enforces server-side validation for `tools/call` results regardless of how the\n * handler was registered, attaches the configured per-operation cache hint\n * (when one exists) so the 2026-07-28 encode seam can fill `ttlMs`/`cacheScope`\n * for results that do not provide their own, and owns the multi-round-trip\n * seam: on the methods whose 2026-07-28 result vocabulary includes\n * `input_required` (`tools/call`, `prompts/get`, `resources/read`) an\n * input-required return skips result-schema validation and is checked\n * against the served era, the at-least-one rule, and the request's own\n * declared client capabilities; on every other method an input-required\n * return is a server bug and fails loudly. The hint rides a symbol-keyed\n * property that is never serialized, so 2025-era responses are unaffected.\n */\n protected override _wrapHandler(\n method: string,\n handler: (request: JSONRPCRequest, ctx: ServerContext) => Promise<Result>\n ): (request: JSONRPCRequest, ctx: ServerContext) => Promise<Result> {\n if (method !== 'tools/call') {\n const cacheHint = (this._cacheHints as Record<string, CacheHint | undefined> | undefined)?.[method];\n const isInputRequiredCapable = INPUT_REQUIRED_CAPABLE_METHODS.has(method);\n if (cacheHint === undefined && !isInputRequiredCapable) {\n // Server-bug guard: an input-required return from a method\n // whose result vocabulary does not include it is never\n // mis-typed onto the wire.\n return async (request, ctx) => {\n const result = await handler(request, ctx);\n if (isInputRequiredResult(result)) {\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and ` +\n `resources/read support input_required (protocol revision 2026-07-28)`\n );\n }\n return result;\n };\n }\n return async (request, ctx) => {\n const result = isInputRequiredCapable\n ? await this._invokeInputRequiredCapableHandler(method, handler, request, ctx)\n : await handler(request, ctx);\n if (isInputRequiredResult(result)) {\n if (!isInputRequiredCapable) {\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and ` +\n `resources/read support input_required (protocol revision 2026-07-28)`\n );\n }\n // Never cache-stamped (the encode contract skips\n // non-complete results); the hint is not attached.\n return result;\n }\n return cacheHint === undefined ? result : attachCacheHintFallback(result, cacheHint);\n };\n }\n return async (request, ctx) => {\n // Era-exact validation via the function-only WireCodec contract:\n // resolved from the instance era at dispatch time (the era gate\n // guarantees tools/call exists on the serving era, so the\n // `not-in-era` arm is an internal error). The era registry entry\n // IS the plain CallToolResult schema (the result map is aligned\n // to the typed map — no widened unions), so no narrower surface\n // is needed.\n const codec = codecForVersion(this._negotiatedProtocolVersion);\n const validatedRequest = codec.validateRequest('tools/call', request);\n if (!validatedRequest.ok) {\n throw new ProtocolError(\n validatedRequest.reason === 'not-in-era' ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams,\n validatedRequest.reason === 'not-in-era'\n ? 'No wire schema for tools/call in the resolved era'\n : `Invalid tools/call request: ${validatedRequest.message}`\n );\n }\n\n const result = await this._invokeInputRequiredCapableHandler('tools/call', handler, request, ctx);\n if (isInputRequiredResult(result)) {\n // Already checked by the seam; the CallToolResult schema does\n // not apply to it (no widening — InputRequiredResult travels\n // alongside).\n return result;\n }\n\n const validationResult = codec.validateResult('tools/call', result);\n if (!validationResult.ok) {\n throw new ProtocolError(\n validationResult.reason === 'not-in-era' ? ProtocolErrorCode.InternalError : ProtocolErrorCode.InvalidParams,\n validationResult.reason === 'not-in-era'\n ? 'No wire schema for tools/call in the resolved era'\n : `Invalid tools/call result: ${validationResult.message}`\n );\n }\n\n return validationResult.value;\n };\n }\n\n /**\n * Whether this instance is bound to a 2026-07-28-or-later protocol\n * revision. Era is instance state — a serving entry (`createMcpHandler`,\n * `serveStdio`) marks the instance modern at construction; a 2025-era\n * `initialize` handshake binds it legacy. The multi-round-trip seam reads\n * this directly: there is no per-request era consult.\n */\n private _servedModernEra(): boolean {\n return this._negotiatedProtocolVersion !== undefined && isModernProtocolVersion(this._negotiatedProtocolVersion);\n }\n\n /**\n * Invokes a handler for one of the multi-round-trip methods and applies\n * the input-required seam:\n *\n * - a `UrlElicitationRequiredError` (or any 2025-style server→client\n * request idiom) escaping the handler on a request served on the\n * 2026-07-28 era fails LOUDLY with a clear steer to\n * `inputRequired.elicitUrl(...)` — the `-32042` error never reaches the\n * 2026-07-28 wire and the throw is not silently converted. Requests\n * served on the 2025 era keep today's `-32042` behavior byte-exact (the\n * error is rethrown unchanged).\n * - an input-required RETURN toward a 2026-07-28 request must satisfy\n * the at-least-one rule, and every embedded request must be covered by\n * the capabilities declared on the request's envelope (violations\n * answer the typed `-32021` error). Toward a 2025-era request the\n * return is fulfilled by the default-on legacy shim, whose own gate\n * consults the initialize-declared capabilities and surfaces\n * violations per family; `inputRequired.legacyShim: false` restores\n * the pre-shim loud failure.\n */\n private async _invokeInputRequiredCapableHandler(\n method: string,\n handler: (request: JSONRPCRequest, ctx: ServerContext) => Promise<Result>,\n request: JSONRPCRequest,\n ctx: ServerContext\n ): Promise<Result> {\n const servedModern = this._servedModernEra();\n\n // The configured requestState.verify hook runs above the handler (and\n // therefore above the McpServer tools/call funnel), so a rejection\n // reaches the wire as a real JSON-RPC error rather than an `isError`\n // tool result. The wire message is FROZEN — the thrown reason is\n // surfaced via `onerror` only. A non-string `requestState` value (the\n // wire field is `string | undefined`) is treated as invalid regardless\n // of whether a hook is configured, so a malformed value cannot bypass\n // verification.\n const rawRequestState: unknown = ctx.mcpReq.requestState();\n if (rawRequestState !== undefined && typeof rawRequestState !== 'string') {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Invalid or expired requestState', {\n reason: 'invalid_request_state'\n });\n }\n let ctxForHandler = ctx;\n if (typeof rawRequestState === 'string') {\n const decoded = await this._verifyRequestState(rawRequestState, ctx, method);\n if (decoded !== undefined) {\n ctxForHandler = withRequestStateValue(ctx, decoded);\n }\n }\n\n let result: Result;\n try {\n result = await handler(request, ctxForHandler);\n } catch (error) {\n if (error instanceof ProtocolError && error.code === ProtocolErrorCode.UrlElicitationRequired) {\n if (!servedModern) {\n // 2025-era behavior is frozen: the error reaches the wire\n // exactly as it does today.\n throw error;\n }\n // 2026-era requests do not carry the -32042 surface. A\n // 2025-style throw fails loudly with a clear steer rather than\n // being converted: the handler should return\n // inputRequired.elicitUrl(...) instead.\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ` +\n `${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) ` +\n `from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not ` +\n `available on this revision.`\n );\n }\n throw error;\n }\n\n if (!isInputRequiredResult(result)) {\n return result;\n }\n\n if (!servedModern) {\n if (!this._inputRequiredServing.legacyShim) {\n // The escape hatch (`inputRequired.legacyShim: false`)\n // restores the pre-shim posture: the 2025-era wire has no\n // input_required vocabulary, so fail loudly rather than\n // putting a mis-typed result on the wire.\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `Handler for ${method} returned an input-required result, but this request is served on protocol revision ` +\n `${this._negotiatedProtocolVersion ?? LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`\n );\n }\n // Write-once handlers served to deployed 2025 clients.\n return await this._legacyInputRequiredShim().fulfill(method, handler, request, ctxForHandler, result);\n }\n\n // F7 at-least-one re-check (hand-built results are legal; the rule is\n // re-checked at the seam).\n const inputRequests = result.inputRequests as Record<string, unknown> | null | undefined;\n const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0;\n const hasRequestState = typeof result.requestState === 'string';\n if (!hasInputRequests && !hasRequestState) {\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `Handler for ${method} returned an input-required result with neither inputRequests nor requestState ` +\n `(every InputRequiredResult must include at least one of the two)`\n );\n }\n\n // Per-embedded-request capability check against the request's own\n // envelope declaration (-32021 on violation).\n if (hasInputRequests) {\n const declared = this._inputRequestCapabilityView(ctx);\n for (const [key, entry] of Object.entries(inputRequests)) {\n const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry);\n const missing = missingClientCapabilities(required, declared);\n if (missing !== undefined) {\n throw new MissingRequiredClientCapabilityError(\n { requiredCapabilities: missing },\n `Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare ` +\n `the required capability`\n );\n }\n }\n }\n\n return result;\n }\n\n /**\n * Runs the configured `requestState.verify` hook and returns its\n * resolved value (`undefined` when unconfigured or the hook returns\n * nothing). Deny-on-error: any hook failure answers the frozen `-32602`;\n * the reason goes to `onerror` only.\n */\n private async _verifyRequestState(state: string, ctx: ServerContext, method: string): Promise<unknown> {\n if (this._requestStateVerify === undefined) {\n return undefined;\n }\n try {\n return await this._requestStateVerify(state, ctx);\n } catch (error) {\n this.onerror?.(\n new Error(`requestState verification rejected ${method}: ${error instanceof Error ? error.message : String(error)}`)\n );\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Invalid or expired requestState', {\n reason: 'invalid_request_state'\n });\n }\n }\n\n /**\n * The per-request resolved client-capabilities view: the request's own\n * `_meta` envelope on the 2026 era; the `initialize`-declared state on a\n * 2025-era connection. Per-request instances that never saw an\n * initialize (stateless legacy) hold nothing, so gates refuse there.\n */\n private _inputRequestCapabilityView(ctx: ServerContext): ClientCapabilities | undefined {\n return this._servedModernEra()\n ? (ctx.mcpReq.envelope?.[CLIENT_CAPABILITIES_META_KEY] as ClientCapabilities | undefined)\n : this._clientCapabilities;\n }\n\n /**\n * Guard for the push-style server→client request APIs ({@linkcode createMessage},\n * {@linkcode elicitInput}, {@linkcode listRoots}, {@linkcode ping}) on a\n * modern-era instance: the 2026-07-28 revision has no server→client request\n * channel, so the call fails before any wire traffic with a typed error\n * whose message steers to `inputRequired(...)`. The base era gate would\n * also reject it; this guard runs first to carry the steer.\n */\n private _assertPushApiInServedEra(method: string): void {\n if (this._servedModernEra()) {\n throw new SdkError(\n SdkErrorCode.MethodNotSupportedByProtocolVersion,\n `Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: ` +\n `'${method}' cannot be sent while serving a request on that revision. ` +\n `Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded ` +\n `requests and retries the original request (multi round-trip requests).`,\n { method, era: '2026-07-28' }\n );\n }\n }\n\n protected assertCapabilityForMethod(method: RequestMethod | string): void {\n switch (method) {\n case 'sampling/createMessage': {\n if (!this._clientCapabilities?.sampling) {\n throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support sampling (required for ${method})`);\n }\n break;\n }\n\n case 'elicitation/create': {\n if (!this._clientCapabilities?.elicitation) {\n throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation (required for ${method})`);\n }\n break;\n }\n\n case 'roots/list': {\n if (!this._clientCapabilities?.roots) {\n throw new SdkError(\n SdkErrorCode.CapabilityNotSupported,\n `Client does not support listing roots (required for ${method})`\n );\n }\n break;\n }\n\n case 'ping': {\n // No specific capability required for ping\n break;\n }\n }\n }\n\n protected assertNotificationCapability(method: NotificationMethod | string): void {\n switch (method) {\n case 'notifications/message': {\n if (!this._capabilities.logging) {\n throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`);\n }\n break;\n }\n\n case 'notifications/resources/updated':\n case 'notifications/resources/list_changed': {\n if (!this._capabilities.resources) {\n throw new SdkError(\n SdkErrorCode.CapabilityNotSupported,\n `Server does not support notifying about resources (required for ${method})`\n );\n }\n break;\n }\n\n case 'notifications/tools/list_changed': {\n if (!this._capabilities.tools) {\n throw new SdkError(\n SdkErrorCode.CapabilityNotSupported,\n `Server does not support notifying of tool list changes (required for ${method})`\n );\n }\n break;\n }\n\n case 'notifications/prompts/list_changed': {\n if (!this._capabilities.prompts) {\n throw new SdkError(\n SdkErrorCode.CapabilityNotSupported,\n `Server does not support notifying of prompt list changes (required for ${method})`\n );\n }\n break;\n }\n\n case 'notifications/elicitation/complete': {\n if (!this._clientCapabilities?.elicitation?.url) {\n throw new SdkError(\n SdkErrorCode.CapabilityNotSupported,\n `Client does not support URL elicitation (required for ${method})`\n );\n }\n break;\n }\n\n case 'notifications/cancelled': {\n // Cancellation notifications are always allowed\n break;\n }\n\n case 'notifications/progress': {\n // Progress notifications are always allowed\n break;\n }\n }\n }\n\n protected assertRequestHandlerCapability(method: string): void {\n switch (method) {\n case 'completion/complete': {\n if (!this._capabilities.completions) {\n throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`);\n }\n break;\n }\n\n case 'logging/setLevel': {\n if (!this._capabilities.logging) {\n throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`);\n }\n break;\n }\n\n case 'prompts/get':\n case 'prompts/list': {\n if (!this._capabilities.prompts) {\n throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`);\n }\n break;\n }\n\n case 'resources/list':\n case 'resources/templates/list':\n case 'resources/read': {\n if (!this._capabilities.resources) {\n throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`);\n }\n break;\n }\n\n case 'tools/call':\n case 'tools/list': {\n if (!this._capabilities.tools) {\n throw new SdkError(SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`);\n }\n break;\n }\n\n case 'ping':\n case 'initialize': {\n // No specific capability required for these methods\n break;\n }\n }\n }\n\n private async _oninitialize(request: InitializeRequest): Promise<InitializeResult> {\n const requestedVersion = request.params.protocolVersion;\n\n this._clientCapabilities = request.params.capabilities;\n this._clientVersion = request.params.clientInfo;\n\n // A 2026-07-28-or-later revision is NEVER negotiated via the legacy\n // `initialize` handshake — only ever selected through `server/discover` —\n // so the accept check and counter-offer consult only the legacy subset.\n const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions);\n const protocolVersion = legacyVersions.includes(requestedVersion)\n ? requestedVersion\n : (legacyVersions[0] ?? LATEST_PROTOCOL_VERSION);\n\n // The negotiated version is the instance's connection state — it IS\n // the wire-era selection for everything this instance sends and\n // receives from here on (legacy handshake ⇒ a legacy-era version).\n this._negotiatedProtocolVersion = protocolVersion;\n this.transport?.setProtocolVersion?.(protocolVersion);\n\n return {\n protocolVersion,\n capabilities: this.getCapabilities(),\n serverInfo: this._serverInfo,\n ...(this._instructions && { instructions: this._instructions })\n };\n }\n\n /**\n * Answers `server/discover` (protocol revision 2026-07-28). `supportedVersions`\n * lists only modern revisions (2025-era versions are negotiated via `initialize`);\n * the advertised capabilities exclude the listChanged/subscribe-class capabilities\n * (see {@linkcode discoverAdvertisedCapabilities}).\n */\n private _ondiscover(): DiscoverResult {\n return {\n supportedVersions: modernProtocolVersions(this._supportedProtocolVersions),\n capabilities: discoverAdvertisedCapabilities(this.getCapabilities()),\n serverInfo: this._serverInfo,\n ...(this._instructions && { instructions: this._instructions })\n };\n }\n\n /**\n * After initialization has completed, this will be populated with the client's reported capabilities.\n *\n * @deprecated Read client identity from the per-request handler context instead: on\n * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's\n * declared capabilities, while on 2025-era connections this accessor keeps returning the\n * `initialize`-scoped value. The accessor remains functional — instances serving the\n * 2026-07-28 era are backfilled per request from the validated envelope.\n */\n getClientCapabilities(): ClientCapabilities | undefined {\n return this._clientCapabilities;\n }\n\n /**\n * After initialization has completed, this will be populated with information about the client's name and version.\n *\n * @deprecated Read client identity from the per-request handler context instead: on\n * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's\n * name and version, while on 2025-era connections this accessor keeps returning the\n * `initialize`-scoped value. The accessor remains functional — instances serving the\n * 2026-07-28 era are backfilled per request from the validated envelope.\n */\n getClientVersion(): Implementation | undefined {\n return this._clientVersion;\n }\n\n /**\n * After initialization has completed, this will be populated with the protocol version negotiated\n * with the client (the version the server responded with during the initialize handshake), or\n * `undefined` before initialization.\n *\n * @deprecated Read the protocol revision from the per-request handler context instead: on\n * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` names the revision the\n * request was sent for, while on 2025-era connections this accessor keeps returning the\n * `initialize`-negotiated version. The accessor remains functional — instances serving the\n * 2026-07-28 era report that revision.\n */\n getNegotiatedProtocolVersion(): string | undefined {\n return this._negotiatedProtocolVersion;\n }\n\n /**\n * Project a `tools/call` result through this instance's negotiated wire\n * codec — the era-agnostic SEP-2106 §4.3 TextContent auto-append, plus on\n * the 2025 era the `{result:…}` wrap when `structuredContent` is a\n * non-object value or the advertised `outputSchema` had a non-object root.\n * Identity for object-shaped `structuredContent` on the 2026 era.\n *\n * `McpServer`'s built-in `tools/call` handler routes through this method.\n * Low-level `setRequestHandler('tools/call', …)` authors call it\n * themselves so the projection lives in one place (the codec) and the\n * server-side handler stays era-blind.\n *\n * This is the only codec function exposed on `Server` — the full\n * `WireCodec` is intentionally not part of the public surface.\n */\n public projectCallToolResult(\n result: CallToolResult,\n advertisedOutputSchema: Readonly<Record<string, unknown>> | undefined\n ): CallToolResult {\n return this._wireCodec().projectCallToolResult(result, advertisedOutputSchema);\n }\n\n /**\n * Returns the current server capabilities.\n */\n public getCapabilities(): ServerCapabilities {\n return this._capabilities;\n }\n\n /**\n * Sends a `ping` request to the connected client.\n *\n * @deprecated The 2026-07-28 protocol removed ping; it throws on a 2026-07-28-era instance.\n * If your factory serves both eras, this only works on the legacy path.\n */\n async ping(): Promise<EmptyResult> {\n this._assertPushApiInServedEra('ping');\n return this.request({ method: 'ping' });\n }\n\n /**\n * Request LLM sampling from the client (without tools).\n * Returns single content block for backwards compatibility.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead,\n * or migrate to calling LLM provider APIs directly. The 2025 push-style server-to-client\n * request model is replaced by input_required results in the 2026-07-28 protocol. If your\n * factory serves both eras, this only works on the legacy path.\n */\n async createMessage(params: CreateMessageRequestParamsBase, options?: RequestOptions): Promise<CreateMessageResult>;\n\n /**\n * Request LLM sampling from the client with tool support.\n * Returns content that may be a single block or array (for parallel tool calls).\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead,\n * or migrate to calling LLM provider APIs directly. The 2025 push-style server-to-client\n * request model is replaced by input_required results in the 2026-07-28 protocol. If your\n * factory serves both eras, this only works on the legacy path.\n */\n async createMessage(params: CreateMessageRequestParamsWithTools, options?: RequestOptions): Promise<CreateMessageResultWithTools>;\n\n /**\n * Request LLM sampling from the client.\n * When tools may or may not be present, returns the union type.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead,\n * or migrate to calling LLM provider APIs directly. The 2025 push-style server-to-client\n * request model is replaced by input_required results in the 2026-07-28 protocol. If your\n * factory serves both eras, this only works on the legacy path.\n */\n async createMessage(\n params: CreateMessageRequest['params'],\n options?: RequestOptions\n ): Promise<CreateMessageResult | CreateMessageResultWithTools>;\n\n // Implementation\n async createMessage(\n params: CreateMessageRequest['params'],\n options?: RequestOptions\n ): Promise<CreateMessageResult | CreateMessageResultWithTools> {\n this._assertPushApiInServedEra('sampling/createMessage');\n // Capability check - only required when tools/toolChoice are provided\n if ((params.tools || params.toolChoice) && !this._clientCapabilities?.sampling?.tools) {\n throw new SdkError(SdkErrorCode.CapabilityNotSupported, '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.at(-1)!;\n const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content];\n const hasToolResults = lastContent.some(c => c.type === 'tool_result');\n\n const previousMessage = params.messages.length > 1 ? params.messages.at(-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\n if (hasToolResults) {\n if (lastContent.some(c => c.type !== 'tool_result')) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n 'The last message must contain only tool_result content if any is present'\n );\n }\n if (!hasPreviousToolUse) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n 'tool_result blocks are not matching any tool_use from the previous message'\n );\n }\n }\n if (hasPreviousToolUse) {\n const toolUseIds = new Set(previousContent.filter(c => c.type === 'tool_use').map(c => (c as ToolUseContent).id));\n const toolResultIds = new Set(\n lastContent.filter(c => c.type === 'tool_result').map(c => (c as ToolResultContent).toolUseId)\n );\n if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every(id => toolResultIds.has(id))) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n 'ids of tool_result blocks and tool_use blocks from previous message do not match'\n );\n }\n }\n }\n\n // The result schema depends on the REQUEST params (tools vs no tools),\n // which a method-keyed registry entry cannot express — the era codec's\n // `samplingResultVariant` owns the with-tools/plain pair. The funnel's\n // registry-result path runs first (era-gated: sampling/createMessage\n // is not a wire request on the 2026 era, so a modern-era instance\n // fails with the typed era error before anything reaches the\n // transport), then the variant validator narrows the wide result.\n const hasTools = Boolean(params.tools || params.toolChoice);\n const wide = await this.request({ method: 'sampling/createMessage', params }, options);\n const outcome = this._wireCodec().samplingResultVariant(hasTools, wide);\n if (!outcome.ok) {\n // `not-in-era` is unreachable on the path that gets here (the era\n // gate above filters out 2026 instances); `invalid` is a peer bug.\n throw new SdkError(\n SdkErrorCode.InvalidResult,\n `Invalid sampling/createMessage result: ${outcome.reason === 'invalid' ? outcome.message : outcome.reason}`\n );\n }\n return outcome.value;\n }\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 * @deprecated Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip)\n * instead. The 2025 push-style server-to-client request model is replaced by input_required\n * results in the 2026-07-28 protocol. If your factory serves both eras, this only works on the\n * legacy path.\n */\n async elicitInput(params: ElicitRequestFormParams | ElicitRequestURLParams, options?: RequestOptions): Promise<ElicitResult> {\n this._assertPushApiInServedEra('elicitation/create');\n const mode = (params.mode ?? 'form') as 'form' | 'url';\n\n switch (mode) {\n case 'url': {\n if (!this._clientCapabilities?.elicitation?.url) {\n throw new SdkError(SdkErrorCode.CapabilityNotSupported, 'Client does not support url elicitation.');\n }\n break;\n }\n case 'form': {\n if (!this._clientCapabilities?.elicitation?.form) {\n throw new SdkError(SdkErrorCode.CapabilityNotSupported, 'Client does not support form elicitation.');\n }\n break;\n }\n }\n\n return this._sendElicitationLeg(params, options);\n }\n\n /**\n * The capability-check-free core of {@linkcode elicitInput}. The shim\n * uses it because its gate differs from the public checks: a bare\n * `elicitation: {}` counts as form support (the pre-mode rule), and\n * accepted content passes through unvalidated for parity with the\n * modern client driver (handlers validate via the schema-aware\n * `acceptedContent` overload and can re-ask).\n */\n private async _sendElicitationLeg(\n params: ElicitRequestFormParams | ElicitRequestURLParams,\n options?: RequestOptions,\n behavior?: { validateAcceptedContent: boolean }\n ): Promise<ElicitResult> {\n const mode = (params.mode ?? 'form') as 'form' | 'url';\n const validateAcceptedContent = behavior?.validateAcceptedContent ?? true;\n\n switch (mode) {\n case 'url': {\n const urlParams = params as ElicitRequestURLParams;\n // Method-keyed request(): the era registry's plain\n // ElicitResult schema is exactly the narrow surface.\n return this.request({ method: 'elicitation/create', params: urlParams }, options);\n }\n case 'form': {\n const formParams: ElicitRequestFormParams =\n params.mode === 'form' ? (params as ElicitRequestFormParams) : { ...(params as ElicitRequestFormParams), mode: 'form' };\n\n const result = await this.request({ method: 'elicitation/create', params: formParams }, options);\n\n if (validateAcceptedContent && result.action === 'accept' && result.content && formParams.requestedSchema) {\n try {\n const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema as JsonSchemaType);\n const validationResult = validator(result.content);\n\n if (!validationResult.valid) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`\n );\n }\n } catch (error) {\n if (error instanceof ProtocolError) {\n throw error;\n }\n throw new ProtocolError(\n ProtocolErrorCode.InternalError,\n `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n }\n return result;\n }\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 * The notification (and the `elicitationId` it references) exists only on protocol revision\n * 2025-11-25 — the 2026-07-28 draft removed both. On a connection negotiated at 2026-07-28 the\n * returned callback rejects with a typed local error before anything reaches the transport\n * (the method is not part of that revision's wire registry).\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: string, options?: NotificationOptions): () => Promise<void> {\n if (!this._clientCapabilities?.elicitation?.url) {\n throw new SdkError(\n SdkErrorCode.CapabilityNotSupported,\n 'Client does not support URL elicitation (required for notifications/elicitation/complete)'\n );\n }\n\n return () =>\n this.notification(\n {\n method: 'notifications/elicitation/complete',\n params: {\n elicitationId\n }\n },\n options\n );\n }\n\n /**\n * Requests the list of roots from the client.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead,\n * or migrate to passing paths via tool parameters, resource URIs, or configuration. The 2025\n * push-style server-to-client request model is replaced by input_required results in the\n * 2026-07-28 protocol. If your factory serves both eras, this only works on the legacy path.\n */\n async listRoots(params?: ListRootsRequest['params'], options?: RequestOptions): Promise<ListRootsResult> {\n this._assertPushApiInServedEra('roots/list');\n return this.request({ method: 'roots/list', params }, options);\n }\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 {@linkcode LoggingMessageNotification}\n * @param params\n * @param sessionId Optional for stateless transports and backward compatibility.\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n * Remains functional during the deprecation window (at least twelve months).\n * Migrate to stderr logging (STDIO servers) or OpenTelemetry.\n */\n async sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string) {\n if (this._capabilities.logging && !this.isMessageIgnored(params.level, sessionId)) {\n return this.notification({ method: 'notifications/message', params });\n }\n }\n\n async sendResourceUpdated(params: ResourceUpdatedNotification['params']) {\n return this.notification({\n method: 'notifications/resources/updated',\n params\n });\n }\n\n async sendResourceListChanged() {\n return this.notification({\n method: 'notifications/resources/list_changed'\n });\n }\n\n async sendToolListChanged() {\n return this.notification({ method: 'notifications/tools/list_changed' });\n }\n\n async sendPromptListChanged() {\n return this.notification({ method: 'notifications/prompts/list_changed' });\n }\n}\n\n/**\n * The capability set a server advertises on `server/discover`. Pure — never\n * mutates the input; the legacy `initialize` advertisement is untouched.\n *\n * The serving entries serve `subscriptions/listen` themselves, so the\n * `listChanged` and `resources.subscribe` capability bits are advertised\n * as-is: a modern-era client uses them to decide which notification types to\n * request on its listen filter.\n */\nexport function discoverAdvertisedCapabilities(capabilities: ServerCapabilities): ServerCapabilities {\n return { ...capabilities };\n}\n","import type {\n BaseMetadata,\n CacheHint,\n CallToolResult,\n CompleteRequestPrompt,\n CompleteRequestResourceTemplate,\n CompleteResult,\n GetPromptResult,\n Icon,\n Implementation,\n InputRequiredResult,\n ListPromptsResult,\n ListResourcesResult,\n ListToolsResult,\n LoggingMessageNotification,\n Prompt,\n PromptReference,\n ReadResourceResult,\n Resource,\n ResourceTemplateReference,\n Result,\n ServerContext,\n StandardSchemaWithJSON,\n Tool,\n ToolAnnotations,\n ToolExecution,\n Transport,\n Variables\n} from '@modelcontextprotocol/core-internal';\nimport {\n assertCompleteRequestPrompt,\n assertCompleteRequestResourceTemplate,\n assertValidCacheHint,\n attachCacheHintFallback,\n isInputRequiredResult,\n normalizeRawShapeSchema,\n promptArgumentsFromStandardSchema,\n ProtocolError,\n ProtocolErrorCode,\n ResourceNotFoundError,\n scanXMcpHeaderDeclarations,\n standardSchemaToJsonSchema,\n UriTemplate,\n validateAndWarnToolName,\n validateStandardSchema\n} from '@modelcontextprotocol/core-internal';\nimport type * as z from 'zod/v4';\n\nimport { getCompleter, isCompletable } from './completable';\nimport type { ServerOptions } from './server';\nimport { Server } from './server';\n\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 * {@linkcode Server} instance available via the {@linkcode McpServer.server | server} property.\n *\n * @example\n * ```ts source=\"./mcp.examples.ts#McpServer_basicUsage\"\n * const server = new McpServer({\n * name: 'my-server',\n * version: '1.0.0'\n * });\n * ```\n */\nexport class McpServer {\n /**\n * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications.\n */\n public readonly server: Server;\n\n private _registeredResources: { [uri: string]: RegisteredResource } = {};\n private _registeredResourceTemplates: {\n [name: string]: RegisteredResourceTemplate;\n } = {};\n private _registeredTools: { [name: string]: RegisteredTool } = {};\n private _registeredPrompts: { [name: string]: RegisteredPrompt } = {};\n /**\n * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243\n * registration-time scan and the pre-dispatch validation step share one\n * conversion instead of paying it twice per request under the\n * per-request-factory `createMcpHandler` model.\n */\n private _toolInputSchemaJson: { [name: string]: Record<string, unknown> } = {};\n\n /**\n * The JSON-serialized `inputSchema` of a registered tool, or `undefined`\n * when no such tool is registered. Used by the HTTP entry's pre-dispatch\n * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema\n * `tools/list` would emit, before dispatch reaches the handler).\n *\n * @internal\n */\n toolInputSchemaJson(name: string): Record<string, unknown> | undefined {\n const tool = this._registeredTools[name];\n if (tool === undefined || !tool.enabled) return undefined;\n if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name];\n if (tool.inputSchema === undefined) return EMPTY_OBJECT_JSON_SCHEMA;\n // Lazy path: the memo slot is unset because `registerTool`'s eager\n // conversion threw (and was swallowed per its \"warn, never throw\"\n // contract) or `update({paramsSchema})`/rename invalidated it. The\n // pre-dispatch SEP-2243 caller must not turn that into a 500 for a\n // `tools/call` whose body-authoritative dispatch would otherwise\n // succeed — return `undefined` so validation is skipped and the\n // conversion failure stays where it always surfaced (`tools/list`).\n // A successful re-derive is memoized so the per-request-factory\n // `createMcpHandler` model does not re-convert on every call.\n try {\n const json = standardSchemaToJsonSchema(tool.inputSchema, 'input');\n this._toolInputSchemaJson[name] = json;\n return json;\n } catch {\n return undefined;\n }\n }\n\n constructor(serverInfo: Implementation, options?: ServerOptions) {\n this.server = new Server(serverInfo, options);\n\n // Per the MCP spec, a server that declares a primitive capability MUST respond to its\n // list method (potentially with an empty result) rather than \"Method not found\" — even\n // if nothing has been registered yet. Handlers are normally installed lazily on first\n // registration, so eagerly install them here for any capability declared up front.\n // (Users of the low-level `Server` class remain responsible for their own handlers.)\n if (options?.capabilities?.tools) {\n this.setToolRequestHandlers();\n }\n if (options?.capabilities?.resources) {\n this.setResourceRequestHandlers();\n }\n if (options?.capabilities?.prompts) {\n this.setPromptRequestHandlers();\n }\n }\n\n /**\n * Attaches to the given transport, starts it, and starts listening for messages.\n *\n * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward.\n *\n * @example\n * ```ts source=\"./mcp.examples.ts#McpServer_connect_stdio\"\n * const server = new McpServer({ name: 'my-server', version: '1.0.0' });\n * const transport = new StdioServerTransport();\n * await server.connect(transport);\n * ```\n */\n async connect(transport: Transport): Promise<void> {\n return await this.server.connect(transport);\n }\n\n /**\n * Closes the connection.\n */\n async close(): Promise<void> {\n await this.server.close();\n }\n\n private _toolHandlersInitialized = false;\n\n private setToolRequestHandlers() {\n if (this._toolHandlersInitialized) {\n return;\n }\n\n this.server.assertCanSetRequestHandler('tools/list');\n this.server.assertCanSetRequestHandler('tools/call');\n\n this.server.registerCapabilities({\n tools: {\n listChanged: this.server.getCapabilities().tools?.listChanged ?? true\n }\n });\n\n // Note: tools are listed in registration (insertion) order, which keeps the ordering\n // deterministic across requests when the underlying tool set has not changed, as\n // recommended by the spec.\n this.server.setRequestHandler(\n 'tools/list',\n (): ListToolsResult => ({\n tools: Object.entries(this._registeredTools)\n .filter(([, tool]) => tool.enabled)\n .map(([name, tool]): Tool => {\n const toolDefinition: Tool = {\n name,\n title: tool.title,\n description: tool.description,\n inputSchema: tool.inputSchema\n ? (standardSchemaToJsonSchema(tool.inputSchema, 'input') as Tool['inputSchema'])\n : EMPTY_OBJECT_JSON_SCHEMA,\n annotations: tool.annotations,\n icons: tool.icons,\n execution: tool.execution,\n _meta: tool._meta\n };\n\n if (tool.outputSchema) {\n // SEP-2106 legacy interop (non-object outputSchema roots wrapped in\n // `{type:'object',properties:{result:<natural>},required:['result']}` toward\n // 2025-era clients) lives in the 2025 wire codec's `encodeResult('tools/list', …)`\n // — this handler is era-blind and emits the natural converted schema.\n toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, 'output') as Tool['outputSchema'];\n }\n\n return toolDefinition;\n })\n })\n );\n\n this.server.setRequestHandler('tools/call', async (request, ctx): Promise<CallToolResult | InputRequiredResult> => {\n const tool = this._registeredTools[request.params.name];\n if (!tool) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`);\n }\n if (!tool.enabled) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);\n }\n\n try {\n const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);\n const result = await this.executeToolHandler(tool, args, ctx);\n await this.validateToolOutput(tool, result, request.params.name);\n if (isInputRequiredResult(result)) return result;\n // SEP-2106 result-side projection (the era-agnostic TextContent auto-append; the\n // `{result:…}` wrap on the 2025 era) lives behind the wire codec's\n // `projectCallToolResult`. The codec receives the SAME advertised JSON Schema\n // `tools/list` emits (and that the codec's `encodeResult('tools/list', …)` may have\n // wrapped) so the listing and the call cannot diverge.\n return this.server.projectCallToolResult(result, tool.outputSchemaJson);\n } catch (error) {\n if (error instanceof ProtocolError && error.code === ProtocolErrorCode.UrlElicitationRequired) {\n throw error; // Return the error to the caller without wrapping in CallToolResult\n }\n return this.createToolError(error instanceof Error ? error.message : String(error));\n }\n });\n\n this._toolHandlersInitialized = true;\n }\n\n /**\n * Creates a tool error result.\n *\n * @param errorMessage - The error message.\n * @returns The tool error result.\n */\n private createToolError(errorMessage: string): CallToolResult {\n return {\n content: [\n {\n type: 'text',\n text: errorMessage\n }\n ],\n isError: true\n };\n }\n\n /**\n * Validates tool input arguments against the tool's input schema.\n */\n private async validateToolInput<\n ToolType extends RegisteredTool,\n Args extends ToolType['inputSchema'] extends infer InputSchema\n ? InputSchema extends StandardSchemaWithJSON\n ? StandardSchemaWithJSON.InferOutput<InputSchema>\n : undefined\n : undefined\n >(tool: ToolType, args: Args, toolName: string): Promise<Args> {\n if (!tool.inputSchema) {\n return undefined as Args;\n }\n\n const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {});\n if (!parseResult.success) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`\n );\n }\n\n return parseResult.data as unknown as Args;\n }\n\n /**\n * Validates tool output against the tool's output schema.\n */\n private async validateToolOutput(tool: RegisteredTool, result: CallToolResult | InputRequiredResult, toolName: string): Promise<void> {\n if (!tool.outputSchema) {\n return;\n }\n\n // An input-required result is not the tool's final output: structured\n // content is only required (and validated) on the completing result.\n if (isInputRequiredResult(result)) {\n return;\n }\n\n if (result.isError) {\n return;\n }\n\n // SEP-2106: `structuredContent` may legally be any JSON value including `null`, `0`,\n // `false`, `\"\"`. The presence check is therefore `=== undefined` (not falsy); when present,\n // the value is ALWAYS validated against the output schema — a falsy value against an\n // object-typed schema fails validation, so this is not a guard weakening.\n if (result.structuredContent === undefined) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`\n );\n }\n\n // if the tool has an output schema, validate structured content\n const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent);\n if (!parseResult.success) {\n throw new ProtocolError(\n ProtocolErrorCode.InvalidParams,\n `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`\n );\n }\n }\n\n /**\n * Executes a tool handler.\n */\n private async executeToolHandler(\n tool: RegisteredTool,\n args: unknown,\n ctx: ServerContext\n ): Promise<CallToolResult | InputRequiredResult> {\n // Executor encapsulates handler invocation with proper types\n return tool.executor(args, ctx);\n }\n\n private _completionHandlerInitialized = false;\n\n private setCompletionRequestHandler() {\n if (this._completionHandlerInitialized) {\n return;\n }\n\n this.server.assertCanSetRequestHandler('completion/complete');\n\n this.server.registerCapabilities({\n completions: {}\n });\n\n this.server.setRequestHandler('completion/complete', async (request): Promise<CompleteResult> => {\n switch (request.params.ref.type) {\n case 'ref/prompt': {\n assertCompleteRequestPrompt(request);\n return this.handlePromptCompletion(request, request.params.ref);\n }\n\n case 'ref/resource': {\n assertCompleteRequestResourceTemplate(request);\n return this.handleResourceCompletion(request, request.params.ref);\n }\n\n default: {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);\n }\n }\n });\n\n this._completionHandlerInitialized = true;\n }\n\n private async handlePromptCompletion(request: CompleteRequestPrompt, ref: PromptReference): Promise<CompleteResult> {\n const prompt = this._registeredPrompts[ref.name];\n if (!prompt) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`);\n }\n\n if (!prompt.enabled) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);\n }\n\n if (!prompt.argsSchema) {\n return EMPTY_COMPLETION_RESULT;\n }\n\n const promptShape = getSchemaShape(prompt.argsSchema);\n const field = unwrapOptionalSchema(promptShape?.[request.params.argument.name]);\n if (!isCompletable(field)) {\n return EMPTY_COMPLETION_RESULT;\n }\n\n const completer = getCompleter(field);\n if (!completer) {\n return EMPTY_COMPLETION_RESULT;\n }\n\n const suggestions = await completer(request.params.argument.value, request.params.context);\n return createCompletionResult(suggestions);\n }\n\n private async handleResourceCompletion(\n request: CompleteRequestResourceTemplate,\n ref: ResourceTemplateReference\n ): Promise<CompleteResult> {\n const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri);\n\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\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);\n }\n\n const completer = template.resourceTemplate.completeCallback(request.params.argument.name);\n if (!completer) {\n return EMPTY_COMPLETION_RESULT;\n }\n\n const suggestions = await completer(request.params.argument.value, request.params.context);\n return createCompletionResult(suggestions);\n }\n\n private _resourceHandlersInitialized = false;\n\n private setResourceRequestHandlers() {\n if (this._resourceHandlersInitialized) {\n return;\n }\n\n this.server.assertCanSetRequestHandler('resources/list');\n this.server.assertCanSetRequestHandler('resources/templates/list');\n this.server.assertCanSetRequestHandler('resources/read');\n\n this.server.registerCapabilities({\n resources: {\n listChanged: this.server.getCapabilities().resources?.listChanged ?? true\n }\n });\n\n this.server.setRequestHandler('resources/list', async (_request, ctx) => {\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\n const templateResources: Resource[] = [];\n for (const template of Object.values(this._registeredResourceTemplates)) {\n if (!template.resourceTemplate.listCallback) {\n continue;\n }\n\n const result = await template.resourceTemplate.listCallback(ctx);\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\n return { resources: [...resources, ...templateResources] };\n });\n\n this.server.setRequestHandler('resources/templates/list', async () => {\n const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({\n name,\n uriTemplate: template.resourceTemplate.uriTemplate.toString(),\n ...template.metadata\n }));\n\n return { resourceTemplates };\n });\n\n this.server.setRequestHandler('resources/read', async (request, ctx) => {\n const uri = new URL(request.params.uri);\n\n // First check for exact resource match\n const resource = this._registeredResources[uri.toString()];\n if (resource) {\n if (!resource.enabled) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`);\n }\n // A per-resource cache hint is the most specific configured\n // author for this result's 2026-07-28 cache fields; it rides a\n // never-serialized carrier and is resolved at the encode seam.\n return attachCacheHintFallback(await resource.readCallback(uri, ctx), resource.cacheHint);\n }\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 attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint);\n }\n }\n\n // Domain layer throws one neutral resource-not-found error; the\n // era-aware encode seam (WireCodec.encodeErrorCode) selects the\n // wire code (−32602 on every era).\n throw new ResourceNotFoundError(request.params.uri);\n });\n\n this._resourceHandlersInitialized = true;\n }\n\n private _promptHandlersInitialized = false;\n\n private setPromptRequestHandlers() {\n if (this._promptHandlersInitialized) {\n return;\n }\n\n this.server.assertCanSetRequestHandler('prompts/list');\n this.server.assertCanSetRequestHandler('prompts/get');\n\n this.server.registerCapabilities({\n prompts: {\n listChanged: this.server.getCapabilities().prompts?.listChanged ?? true\n }\n });\n\n this.server.setRequestHandler(\n 'prompts/list',\n (): ListPromptsResult => ({\n prompts: Object.entries(this._registeredPrompts)\n .filter(([, prompt]) => prompt.enabled)\n .map(([name, prompt]): Prompt => {\n return {\n name,\n title: prompt.title,\n description: prompt.description,\n arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : undefined,\n icons: prompt.icons,\n _meta: prompt._meta\n };\n })\n })\n );\n\n this.server.setRequestHandler('prompts/get', async (request, ctx): Promise<GetPromptResult | InputRequiredResult> => {\n const prompt = this._registeredPrompts[request.params.name];\n if (!prompt) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);\n }\n\n if (!prompt.enabled) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);\n }\n\n // Handler encapsulates parsing and callback invocation with proper types\n return prompt.handler(request.params.arguments, ctx);\n });\n\n this._promptHandlersInitialized = true;\n }\n\n /**\n * Registers a resource with a config object and callback.\n * For static resources, use a URI string. For dynamic resources, use a {@linkcode ResourceTemplate}.\n *\n * @example\n * ```ts source=\"./mcp.examples.ts#McpServer_registerResource_static\"\n * server.registerResource(\n * 'config',\n * 'config://app',\n * {\n * title: 'Application Config',\n * mimeType: 'text/plain'\n * },\n * async uri => ({\n * contents: [{ uri: uri.href, text: 'App configuration here' }]\n * })\n * );\n * ```\n */\n registerResource(\n name: string,\n uriOrTemplate: string,\n config: ResourceMetadata & { cacheHint?: CacheHint },\n readCallback: ReadResourceCallback\n ): RegisteredResource;\n registerResource(\n name: string,\n uriOrTemplate: ResourceTemplate,\n config: ResourceMetadata & { cacheHint?: CacheHint },\n readCallback: ReadResourceTemplateCallback\n ): RegisteredResourceTemplate;\n registerResource(\n name: string,\n uriOrTemplate: string | ResourceTemplate,\n config: ResourceMetadata & { cacheHint?: CacheHint },\n readCallback: ReadResourceCallback | ReadResourceTemplateCallback\n ): RegisteredResource | RegisteredResourceTemplate {\n // The cache hint configures the encode-time cache fields of this\n // resource's `resources/read` results (2026-07-28); it is not resource\n // metadata and never appears on `resources/list` entries.\n const cacheHint = config.cacheHint;\n let metadata: ResourceMetadata = config;\n if (cacheHint !== undefined) {\n assertValidCacheHint(cacheHint, `resource ${name}`);\n const rest = { ...config };\n delete rest.cacheHint;\n metadata = rest;\n }\n\n if (typeof uriOrTemplate === 'string') {\n if (this._registeredResources[uriOrTemplate]) {\n throw new Error(`Resource ${uriOrTemplate} is already registered`);\n }\n\n const registeredResource = this._createRegisteredResource(\n name,\n (config as BaseMetadata).title,\n uriOrTemplate,\n metadata,\n readCallback as ReadResourceCallback\n );\n if (cacheHint !== undefined) {\n registeredResource.cacheHint = cacheHint;\n }\n\n this.setResourceRequestHandlers();\n this.sendResourceListChanged();\n return registeredResource;\n } else {\n if (this._registeredResourceTemplates[name]) {\n throw new Error(`Resource template ${name} is already registered`);\n }\n\n const registeredResourceTemplate = this._createRegisteredResourceTemplate(\n name,\n (config as BaseMetadata).title,\n uriOrTemplate,\n metadata,\n readCallback as ReadResourceTemplateCallback\n );\n if (cacheHint !== undefined) {\n registeredResourceTemplate.cacheHint = cacheHint;\n }\n\n this.setResourceRequestHandlers();\n this.sendResourceListChanged();\n return registeredResourceTemplate;\n }\n }\n\n private _createRegisteredResource(\n name: string,\n title: string | undefined,\n uri: string,\n metadata: ResourceMetadata | undefined,\n readCallback: ReadResourceCallback\n ): RegisteredResource {\n const registeredResource: 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 (updates.uri !== undefined && updates.uri !== uri) {\n delete this._registeredResources[uri];\n if (updates.uri) this._registeredResources[updates.uri] = registeredResource;\n }\n if (updates.name !== undefined) registeredResource.name = updates.name;\n if (updates.title !== undefined) registeredResource.title = updates.title;\n if (updates.metadata !== undefined) registeredResource.metadata = updates.metadata;\n if (updates.callback !== undefined) registeredResource.readCallback = updates.callback;\n if (updates.enabled !== undefined) registeredResource.enabled = updates.enabled;\n this.sendResourceListChanged();\n }\n };\n this._registeredResources[uri] = registeredResource;\n return registeredResource;\n }\n\n private _createRegisteredResourceTemplate(\n name: string,\n title: string | undefined,\n template: ResourceTemplate,\n metadata: ResourceMetadata | undefined,\n readCallback: ReadResourceTemplateCallback\n ): RegisteredResourceTemplate {\n const registeredResourceTemplate: 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 (updates.name !== undefined && updates.name !== name) {\n delete this._registeredResourceTemplates[name];\n if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;\n }\n if (updates.title !== undefined) registeredResourceTemplate.title = updates.title;\n if (updates.template !== undefined) registeredResourceTemplate.resourceTemplate = updates.template;\n if (updates.metadata !== undefined) registeredResourceTemplate.metadata = updates.metadata;\n if (updates.callback !== undefined) registeredResourceTemplate.readCallback = updates.callback;\n if (updates.enabled !== undefined) registeredResourceTemplate.enabled = updates.enabled;\n this.sendResourceListChanged();\n }\n };\n this._registeredResourceTemplates[name] = registeredResourceTemplate;\n\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\n return registeredResourceTemplate;\n }\n\n private _createRegisteredPrompt(\n name: string,\n title: string | undefined,\n description: string | undefined,\n argsSchema: StandardSchemaWithJSON | undefined,\n callback: PromptCallback<StandardSchemaWithJSON | undefined>,\n icons: Icon[] | undefined,\n _meta: Record<string, unknown> | undefined\n ): RegisteredPrompt {\n // Track current schema and callback for handler regeneration\n let currentArgsSchema = argsSchema;\n let currentCallback = callback;\n\n const registeredPrompt: RegisteredPrompt = {\n title,\n description,\n argsSchema,\n icons,\n _meta,\n handler: createPromptHandler(name, argsSchema, 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 (updates.name !== undefined && updates.name !== name) {\n delete this._registeredPrompts[name];\n if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt;\n }\n if (updates.title !== undefined) registeredPrompt.title = updates.title;\n if (updates.description !== undefined) registeredPrompt.description = updates.description;\n if (updates.icons !== undefined) registeredPrompt.icons = updates.icons;\n if (updates._meta !== undefined) registeredPrompt._meta = updates._meta;\n\n // Track if we need to regenerate the handler\n let needsHandlerRegen = false;\n if (updates.argsSchema !== undefined) {\n registeredPrompt.argsSchema = updates.argsSchema;\n currentArgsSchema = updates.argsSchema;\n needsHandlerRegen = true;\n }\n if (updates.callback !== undefined) {\n currentCallback = updates.callback as PromptCallback<StandardSchemaWithJSON | undefined>;\n needsHandlerRegen = true;\n }\n if (needsHandlerRegen) {\n registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback);\n }\n\n if (updates.enabled !== undefined) registeredPrompt.enabled = updates.enabled;\n this.sendPromptListChanged();\n }\n };\n this._registeredPrompts[name] = registeredPrompt;\n\n // If any argument uses a Completable schema, enable completions capability\n if (argsSchema) {\n const shape = getSchemaShape(argsSchema);\n if (shape) {\n const hasCompletable = Object.values(shape).some(field => {\n const inner = unwrapOptionalSchema(field);\n return isCompletable(inner);\n });\n if (hasCompletable) {\n this.setCompletionRequestHandler();\n }\n }\n }\n\n return registeredPrompt;\n }\n\n private _createRegisteredTool(\n name: string,\n title: string | undefined,\n description: string | undefined,\n inputSchema: StandardSchemaWithJSON | undefined,\n outputSchema: StandardSchemaWithJSON | undefined,\n annotations: ToolAnnotations | undefined,\n icons: Icon[] | undefined,\n execution: ToolExecution | undefined,\n _meta: Record<string, unknown> | undefined,\n handler: AnyToolHandler<StandardSchemaWithJSON | undefined>\n ): RegisteredTool {\n // Validate tool name according to SEP specification\n validateAndWarnToolName(name);\n\n // SEP-2243 registration-time declaration-validity check (additive: warn,\n // never throw — clients enforce by exclusion, servers by header\n // validation; a malformed declaration here should not block local\n // development against a stdio client that ignores it). The conversion\n // is memoized so the pre-dispatch validation step in `createMcpHandler`\n // (and `toolInputSchemaJson()`) does not repeat it for the same tool.\n // `standardSchemaToJsonSchema` can throw for schemas it cannot convert\n // (e.g. a vendor without `~standard.jsonSchema`); the try/catch keeps\n // the \"warn, never throw\" contract.\n if (inputSchema !== undefined) {\n try {\n const json = standardSchemaToJsonSchema(inputSchema, 'input');\n this._toolInputSchemaJson[name] = json;\n const scan = scanXMcpHeaderDeclarations(json);\n if (!scan.valid) {\n console.warn(\n `[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by ` +\n `conforming Streamable HTTP clients: ${scan.reason}`\n );\n }\n } catch {\n // Conversion failure: leave the cache slot unset so the lazy\n // path in `toolInputSchemaJson()` (and `tools/list`) surfaces\n // the failure where it always has.\n }\n }\n\n // Track current handler for executor regeneration\n let currentHandler = handler;\n\n const registeredTool: RegisteredTool = {\n title,\n description,\n inputSchema,\n outputSchema,\n outputSchemaJson: convertOutputSchemaJson(outputSchema),\n annotations,\n icons,\n execution,\n _meta,\n handler: handler,\n executor: createToolExecutor(inputSchema, 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 // The closure's `name` tracks the CURRENT registry key, not\n // the original registration name — renaming reassigns it so\n // subsequent paramsSchema/rename invalidations evict the live\n // `_toolInputSchemaJson` slot rather than the original.\n if (updates.name !== undefined && updates.name !== name) {\n if (typeof updates.name === 'string') {\n validateAndWarnToolName(updates.name);\n }\n delete this._registeredTools[name];\n delete this._toolInputSchemaJson[name];\n if (updates.name) {\n // The TARGET key may already be occupied by another\n // tool (rename has no duplicate-name guard) — drop\n // its memo too, otherwise `toolInputSchemaJson()`\n // returns the displaced tool's converted schema and\n // the SEP-2243 pre-dispatch validation runs against\n // the wrong schema for this name.\n delete this._toolInputSchemaJson[updates.name];\n this._registeredTools[updates.name] = registeredTool;\n name = updates.name;\n }\n }\n if (updates.title !== undefined) registeredTool.title = updates.title;\n if (updates.description !== undefined) registeredTool.description = updates.description;\n\n // Track if we need to regenerate the executor\n let needsExecutorRegen = false;\n if (updates.paramsSchema !== undefined) {\n registeredTool.inputSchema = updates.paramsSchema;\n delete this._toolInputSchemaJson[name];\n needsExecutorRegen = true;\n }\n if (updates.callback !== undefined) {\n registeredTool.handler = updates.callback;\n currentHandler = updates.callback as AnyToolHandler<StandardSchemaWithJSON | undefined>;\n needsExecutorRegen = true;\n }\n if (needsExecutorRegen) {\n registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler);\n }\n\n if (updates.outputSchema !== undefined) {\n registeredTool.outputSchema = updates.outputSchema;\n registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema);\n }\n if (updates.annotations !== undefined) registeredTool.annotations = updates.annotations;\n if (updates.icons !== undefined) registeredTool.icons = updates.icons;\n if (updates._meta !== undefined) registeredTool._meta = updates._meta;\n if (updates.enabled !== undefined) registeredTool.enabled = updates.enabled;\n this.sendToolListChanged();\n }\n };\n this._registeredTools[name] = registeredTool;\n\n this.setToolRequestHandlers();\n this.sendToolListChanged();\n\n return registeredTool;\n }\n\n /**\n * Registers a tool with a config object and callback.\n *\n * @example\n * ```ts source=\"./mcp.examples.ts#McpServer_registerTool_basic\"\n * server.registerTool(\n * 'calculate-bmi',\n * {\n * title: 'BMI Calculator',\n * description: 'Calculate Body Mass Index',\n * inputSchema: z.object({\n * weightKg: z.number(),\n * heightM: z.number()\n * }),\n * outputSchema: z.object({ bmi: z.number() })\n * },\n * async ({ weightKg, heightM }) => {\n * const output = { bmi: weightKg / (heightM * heightM) };\n * return {\n * content: [{ type: 'text', text: JSON.stringify(output) }],\n * structuredContent: output\n * };\n * }\n * );\n * ```\n */\n registerTool<OutputArgs extends StandardSchemaWithJSON, InputArgs extends StandardSchemaWithJSON | undefined = undefined>(\n name: string,\n config: {\n title?: string;\n description?: string;\n inputSchema?: InputArgs;\n outputSchema?: OutputArgs;\n annotations?: ToolAnnotations;\n icons?: Icon[];\n _meta?: Record<string, unknown>;\n },\n cb: ToolCallback<InputArgs>\n ): RegisteredTool;\n /** @deprecated Wrap with `z.object({...})` instead. Raw-shape form: `inputSchema`/`outputSchema` may be a plain `{ field: z.string() }` record; it is auto-wrapped with `z.object()`. */\n registerTool<InputArgs extends ZodRawShape, OutputArgs extends ZodRawShape | StandardSchemaWithJSON | undefined = undefined>(\n name: string,\n config: {\n title?: string;\n description?: string;\n inputSchema?: InputArgs;\n outputSchema?: OutputArgs;\n annotations?: ToolAnnotations;\n icons?: Icon[];\n _meta?: Record<string, unknown>;\n },\n cb: LegacyToolCallback<InputArgs>\n ): RegisteredTool;\n registerTool(\n name: string,\n config: {\n title?: string;\n description?: string;\n inputSchema?: StandardSchemaWithJSON | ZodRawShape;\n outputSchema?: StandardSchemaWithJSON | ZodRawShape;\n annotations?: ToolAnnotations;\n icons?: Icon[];\n _meta?: Record<string, unknown>;\n },\n cb: ToolCallback<StandardSchemaWithJSON | undefined> | LegacyToolCallback<ZodRawShape>\n ): RegisteredTool {\n if (this._registeredTools[name]) {\n throw new Error(`Tool ${name} is already registered`);\n }\n\n const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config;\n\n return this._createRegisteredTool(\n name,\n title,\n description,\n normalizeRawShapeSchema(inputSchema),\n normalizeRawShapeSchema(outputSchema),\n annotations,\n icons,\n undefined,\n _meta,\n cb as ToolCallback<StandardSchemaWithJSON | undefined>\n );\n }\n\n /**\n * Registers a prompt with a config object and callback.\n *\n * @example\n * ```ts source=\"./mcp.examples.ts#McpServer_registerPrompt_basic\"\n * server.registerPrompt(\n * 'review-code',\n * {\n * title: 'Code Review',\n * description: 'Review code for best practices',\n * argsSchema: z.object({ code: z.string() })\n * },\n * ({ code }) => ({\n * messages: [\n * {\n * role: 'user' as const,\n * content: {\n * type: 'text' as const,\n * text: `Please review this code:\\n\\n${code}`\n * }\n * }\n * ]\n * })\n * );\n * ```\n */\n registerPrompt<Args extends StandardSchemaWithJSON>(\n name: string,\n config: {\n title?: string;\n description?: string;\n argsSchema?: Args;\n icons?: Icon[];\n _meta?: Record<string, unknown>;\n },\n cb: PromptCallback<Args>\n ): RegisteredPrompt;\n /** @deprecated Wrap with `z.object({...})` instead. Raw-shape form: `argsSchema` may be a plain `{ field: z.string() }` record; it is auto-wrapped with `z.object()`. */\n registerPrompt<Args extends ZodRawShape>(\n name: string,\n config: {\n title?: string;\n description?: string;\n argsSchema?: Args;\n icons?: Icon[];\n _meta?: Record<string, unknown>;\n },\n cb: LegacyPromptCallback<Args>\n ): RegisteredPrompt;\n registerPrompt(\n name: string,\n config: {\n title?: string;\n description?: string;\n argsSchema?: StandardSchemaWithJSON | ZodRawShape;\n icons?: Icon[];\n _meta?: Record<string, unknown>;\n },\n cb: PromptCallback<StandardSchemaWithJSON> | LegacyPromptCallback<ZodRawShape>\n ): RegisteredPrompt {\n if (this._registeredPrompts[name]) {\n throw new Error(`Prompt ${name} is already registered`);\n }\n\n const { title, description, argsSchema, icons, _meta } = config;\n\n const registeredPrompt = this._createRegisteredPrompt(\n name,\n title,\n description,\n normalizeRawShapeSchema(argsSchema),\n cb as PromptCallback<StandardSchemaWithJSON | undefined>,\n icons,\n _meta\n );\n\n this.setPromptRequestHandlers();\n this.sendPromptListChanged();\n\n return registeredPrompt;\n }\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 /**\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 {@linkcode LoggingMessageNotification}\n * @param params\n * @param sessionId Optional for stateless transports and backward compatibility.\n *\n * @example\n * ```ts source=\"./mcp.examples.ts#McpServer_sendLoggingMessage_basic\"\n * await server.sendLoggingMessage({\n * level: 'info',\n * data: 'Processing complete'\n * });\n * ```\n *\n * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577).\n * Remains functional during the deprecation window (at least twelve months).\n * Migrate to stderr logging (STDIO servers) or OpenTelemetry.\n */\n async sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string) {\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 /**\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 /**\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/**\n * A callback to complete one variable within a resource template's URI template.\n */\nexport type CompleteResourceTemplateCallback = (\n value: string,\n context?: {\n arguments?: Record<string, string>;\n }\n) => string[] | Promise<string[]>;\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 private _uriTemplate: UriTemplate;\n\n constructor(\n uriTemplate: string | UriTemplate,\n private _callbacks: {\n /**\n * A callback to list all resources matching this template. This is required to be specified, even if `undefined`, to avoid accidentally forgetting resource listing.\n */\n list: ListResourcesCallback | undefined;\n\n /**\n * An optional callback to autocomplete variables within the URI template. Useful for clients and users to discover possible values.\n */\n complete?: {\n [variable: string]: CompleteResourceTemplateCallback;\n };\n }\n ) {\n this._uriTemplate = typeof uriTemplate === 'string' ? new UriTemplate(uriTemplate) : uriTemplate;\n }\n\n /**\n * Gets the URI template pattern.\n */\n get uriTemplate(): UriTemplate {\n return this._uriTemplate;\n }\n\n /**\n * Gets the list callback, if one was provided.\n */\n get listCallback(): ListResourcesCallback | undefined {\n return this._callbacks.list;\n }\n\n /**\n * Gets the callback for completing a specific URI template variable, if one was provided.\n */\n completeCallback(variable: string): CompleteResourceTemplateCallback | undefined {\n return this._callbacks.complete?.[variable];\n }\n}\n\n/**\n * A plain record of Zod field schemas, e.g. `{ name: z.string() }`. Accepted by\n * `registerTool`/`registerPrompt` as a shorthand; auto-wrapped with `z.object()`.\n * Zod schemas only — `z.object()` cannot wrap other Standard Schema libraries.\n */\nexport type ZodRawShape = Record<string, z.ZodType>;\n\n/** Infers the parsed-output type of a {@linkcode ZodRawShape}. */\nexport type InferRawShape<S extends ZodRawShape> = z.infer<z.ZodObject<S>>;\n\n/** {@linkcode ToolCallback} variant used when `inputSchema` is a {@linkcode ZodRawShape}. */\nexport type LegacyToolCallback<Args extends ZodRawShape | undefined> = Args extends ZodRawShape\n ? (\n args: InferRawShape<Args>,\n ctx: ServerContext\n ) => CallToolResult | InputRequiredResult | Promise<CallToolResult | InputRequiredResult>\n : (ctx: ServerContext) => CallToolResult | InputRequiredResult | Promise<CallToolResult | InputRequiredResult>;\n\n/** {@linkcode PromptCallback} variant used when `argsSchema` is a {@linkcode ZodRawShape}. */\nexport type LegacyPromptCallback<Args extends ZodRawShape | undefined> = Args extends ZodRawShape\n ? (\n args: InferRawShape<Args>,\n ctx: ServerContext\n ) => GetPromptResult | InputRequiredResult | Promise<GetPromptResult | InputRequiredResult>\n : (ctx: ServerContext) => GetPromptResult | InputRequiredResult | Promise<GetPromptResult | InputRequiredResult>;\n\nexport type BaseToolCallback<\n SendResultT extends Result,\n Ctx extends ServerContext,\n Args extends StandardSchemaWithJSON | undefined\n> = Args extends StandardSchemaWithJSON\n ? (args: StandardSchemaWithJSON.InferOutput<Args>, ctx: Ctx) => SendResultT | Promise<SendResultT>\n : (ctx: Ctx) => SendResultT | Promise<SendResultT>;\n\n/**\n * Callback for a tool handler registered with {@linkcode McpServer.registerTool}.\n */\nexport type ToolCallback<Args extends StandardSchemaWithJSON | undefined = undefined> = BaseToolCallback<\n CallToolResult | InputRequiredResult,\n ServerContext,\n Args\n>;\n\n/**\n * Tool handler callback type.\n */\nexport type AnyToolHandler<Args extends StandardSchemaWithJSON | undefined = undefined> = ToolCallback<Args>;\n\n/**\n * Internal executor type that encapsulates handler invocation with proper types.\n */\ntype ToolExecutor = (args: unknown, ctx: ServerContext) => Promise<CallToolResult | InputRequiredResult>;\n\nexport type RegisteredTool = {\n title?: string;\n description?: string;\n inputSchema?: StandardSchemaWithJSON;\n outputSchema?: StandardSchemaWithJSON;\n /**\n * @hidden\n * The converted JSON Schema of `outputSchema`, memoised at registration (and on\n * `update({outputSchema})`) so the `tools/call` handler passes the SAME advertised schema\n * `tools/list` emits to the wire codec's `projectCallToolResult` — the SEP-2106 `{result:…}`\n * wrap predicate follows the schema's root, never the runtime value shape. `undefined` when\n * no `outputSchema` is registered or its conversion threw (see {@link convertOutputSchemaJson}).\n */\n outputSchemaJson?: Record<string, unknown>;\n annotations?: ToolAnnotations;\n icons?: Icon[];\n execution?: ToolExecution;\n _meta?: Record<string, unknown>;\n handler: AnyToolHandler<StandardSchemaWithJSON | undefined>;\n /** @hidden */\n executor: ToolExecutor;\n enabled: boolean;\n enable(): void;\n disable(): void;\n update(updates: {\n name?: string | null;\n title?: string;\n description?: string;\n paramsSchema?: StandardSchemaWithJSON;\n outputSchema?: StandardSchemaWithJSON;\n annotations?: ToolAnnotations;\n icons?: Icon[];\n _meta?: Record<string, unknown>;\n callback?: ToolCallback<StandardSchemaWithJSON>;\n enabled?: boolean;\n }): void;\n remove(): void;\n};\n\n/**\n * Creates an executor that invokes the handler with the appropriate arguments.\n * When `inputSchema` is defined, the handler is called with `(args, ctx)`.\n * When `inputSchema` is undefined, the handler is called with just `(ctx)`.\n */\nfunction createToolExecutor(\n inputSchema: StandardSchemaWithJSON | undefined,\n handler: AnyToolHandler<StandardSchemaWithJSON | undefined>\n): ToolExecutor {\n if (inputSchema) {\n const callback = handler as ToolCallbackInternal;\n return async (args, ctx) => callback(args, ctx);\n }\n\n // When no inputSchema, call with just ctx (the handler expects (ctx) signature)\n const callback = handler as (\n ctx: ServerContext\n ) => CallToolResult | InputRequiredResult | Promise<CallToolResult | InputRequiredResult>;\n return async (_args, ctx) => callback(ctx);\n}\n\nconst EMPTY_OBJECT_JSON_SCHEMA = {\n type: 'object' as const,\n properties: {}\n};\n\n/**\n * Convert a registered `outputSchema` to JSON Schema, memoised on {@link RegisteredTool.outputSchemaJson}\n * so `tools/call` passes the SAME advertised schema to the wire codec's `projectCallToolResult` that\n * `tools/list` emits (and that the 2025 codec's `encodeResult('tools/list', …)` may wrap). A conversion\n * failure yields `undefined` so the failure surfaces where it always has (`tools/list`).\n */\nfunction convertOutputSchemaJson(outputSchema: StandardSchemaWithJSON | undefined): Record<string, unknown> | undefined {\n if (outputSchema === undefined) return undefined;\n try {\n return standardSchemaToJsonSchema(outputSchema, 'output');\n } catch {\n return undefined;\n }\n}\n\n/**\n * Additional, optional information for annotating a resource.\n */\nexport type ResourceMetadata = Omit<Resource, 'uri' | 'name'>;\n\n/**\n * Callback to list all resources matching a given template.\n */\nexport type ListResourcesCallback = (ctx: ServerContext) => ListResourcesResult | Promise<ListResourcesResult>;\n\n/**\n * Callback to read a resource at a given URI.\n */\nexport type ReadResourceCallback = (\n uri: URL,\n ctx: ServerContext\n) => ReadResourceResult | InputRequiredResult | Promise<ReadResourceResult | InputRequiredResult>;\n\nexport type RegisteredResource = {\n name: string;\n title?: string;\n metadata?: ResourceMetadata;\n /** Cache hint applied to this resource's `resources/read` results on the 2026-07-28 revision. */\n cacheHint?: CacheHint;\n readCallback: ReadResourceCallback;\n enabled: boolean;\n enable(): void;\n disable(): void;\n update(updates: {\n name?: string;\n title?: string;\n uri?: string | null;\n metadata?: ResourceMetadata;\n callback?: ReadResourceCallback;\n enabled?: boolean;\n }): void;\n remove(): void;\n};\n\n/**\n * Callback to read a resource at a given URI, following a filled-in URI template.\n */\nexport type ReadResourceTemplateCallback = (\n uri: URL,\n variables: Variables,\n ctx: ServerContext\n) => ReadResourceResult | InputRequiredResult | Promise<ReadResourceResult | InputRequiredResult>;\n\nexport type RegisteredResourceTemplate = {\n resourceTemplate: ResourceTemplate;\n title?: string;\n metadata?: ResourceMetadata;\n /** Cache hint applied to this template's `resources/read` results on the 2026-07-28 revision. */\n cacheHint?: CacheHint;\n readCallback: ReadResourceTemplateCallback;\n enabled: boolean;\n enable(): void;\n disable(): void;\n update(updates: {\n name?: string | null;\n title?: string;\n template?: ResourceTemplate;\n metadata?: ResourceMetadata;\n callback?: ReadResourceTemplateCallback;\n enabled?: boolean;\n }): void;\n remove(): void;\n};\n\nexport type PromptCallback<Args extends StandardSchemaWithJSON | undefined = undefined> = Args extends StandardSchemaWithJSON\n ? (\n args: StandardSchemaWithJSON.InferOutput<Args>,\n ctx: ServerContext\n ) => GetPromptResult | InputRequiredResult | Promise<GetPromptResult | InputRequiredResult>\n : (ctx: ServerContext) => GetPromptResult | InputRequiredResult | Promise<GetPromptResult | InputRequiredResult>;\n\n/**\n * Internal handler type that encapsulates parsing and callback invocation.\n * This allows type-safe handling without runtime type assertions.\n */\ntype PromptHandler = (args: Record<string, unknown> | undefined, ctx: ServerContext) => Promise<GetPromptResult | InputRequiredResult>;\n\ntype ToolCallbackInternal = (\n args: unknown,\n ctx: ServerContext\n) => CallToolResult | InputRequiredResult | Promise<CallToolResult | InputRequiredResult>;\n\nexport type RegisteredPrompt = {\n title?: string;\n description?: string;\n argsSchema?: StandardSchemaWithJSON;\n icons?: Icon[];\n _meta?: Record<string, unknown>;\n /** @hidden */\n handler: PromptHandler;\n enabled: boolean;\n enable(): void;\n disable(): void;\n update<Args extends StandardSchemaWithJSON>(updates: {\n name?: string | null;\n title?: string;\n description?: string;\n argsSchema?: Args;\n icons?: Icon[];\n _meta?: Record<string, unknown>;\n callback?: PromptCallback<Args>;\n enabled?: boolean;\n }): void;\n remove(): void;\n};\n\n/**\n * Creates a type-safe prompt handler that captures the schema and callback in a closure.\n * This eliminates the need for type assertions at the call site.\n */\nfunction createPromptHandler(\n name: string,\n argsSchema: StandardSchemaWithJSON | undefined,\n callback: PromptCallback<StandardSchemaWithJSON | undefined>\n): PromptHandler {\n if (argsSchema) {\n const typedCallback = callback as (\n args: unknown,\n ctx: ServerContext\n ) => GetPromptResult | InputRequiredResult | Promise<GetPromptResult | InputRequiredResult>;\n\n return async (args, ctx) => {\n const parseResult = await validateStandardSchema(argsSchema, args);\n if (!parseResult.success) {\n throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`);\n }\n return typedCallback(parseResult.data, ctx);\n };\n } else {\n const typedCallback = callback as (\n ctx: ServerContext\n ) => GetPromptResult | InputRequiredResult | Promise<GetPromptResult | InputRequiredResult>;\n\n return async (_args, ctx) => {\n return typedCallback(ctx);\n };\n }\n}\n\nfunction createCompletionResult(suggestions: readonly unknown[]): CompleteResult {\n const values = suggestions.map(String).slice(0, 100);\n return {\n completion: {\n values,\n total: suggestions.length,\n hasMore: suggestions.length > 100\n }\n };\n}\n\nconst EMPTY_COMPLETION_RESULT: CompleteResult = {\n completion: {\n values: [],\n hasMore: false\n }\n};\n\n/** @internal Gets the shape of a Zod object schema */\nfunction getSchemaShape(schema: unknown): Record<string, unknown> | undefined {\n const candidate = schema as { shape?: unknown };\n if (candidate.shape && typeof candidate.shape === 'object') {\n return candidate.shape as Record<string, unknown>;\n }\n return undefined;\n}\n\n/** @internal Checks if a Zod schema is optional */\nfunction isOptionalSchema(schema: unknown): boolean {\n const candidate = schema as { type?: string } | null | undefined;\n return candidate?.type === 'optional';\n}\n\n/** @internal Unwraps an optional Zod schema */\nfunction unwrapOptionalSchema(schema: unknown): unknown {\n if (!isOptionalSchema(schema)) {\n return schema;\n }\n const candidate = schema as { def?: { innerType?: unknown } };\n return candidate.def?.innerType ?? schema;\n}\n"],"mappings":";;;;;AAEA,MAAaA,qBAAoC,OAAO,IAAI,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgD9E,SAAgB,YAAwC,QAAW,UAAqD;AACpH,QAAO,eAAe,QAAkB,oBAAoB;EACxD,OAAO,EAAE,UAAU;EACnB,YAAY;EACZ,UAAU;EACV,cAAc;EACjB,CAAC;AACF,QAAO;;;;;AAMX,SAAgB,cAAc,QAAgE;AAC1F,QAAO,CAAC,CAAC,UAAU,OAAO,WAAW,YAAY,sBAAuB;;;;;AAM5E,SAAgB,aAAyC,QAA4C;AAEjG,QADc,OAAoE,qBACrE;;;;;;;;;AClEjB,IAAY,4DAAL;;;;;AAKH;;;;;AAMA;;;;;AAMA;;;;AAKA;;;;AAKA;;;;AAKA;;;;AAKA;;;;AAKA;;;;AAKA;;;;AAKA;;;;AAKA;;;;AAKA;;;;AAKA;;;;AAKA;;;;AAKA;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,MAAM,OAAO;AAClD,QAAO;EACH,QAAQ,WAAW;EACnB,QAAO,WAAU,WAAW,MAAM,OAAO;EACzC,eAAe,OAAO,oBAAoB,SAAS,aAAa;EACnE;;;;;;;;;;;;;;;;;;;ACnKL,MAAM,mBAAmB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACH;AAED,MAAM,cAAc;CAChB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACH;AA+CD,MAAMC,mBAAqD,EAAE;AAC7D,MAAMC,cAA2D,EAAE;AACnE,SAAS,SAAS,KAAa,QAAyB;CACpD,MAAM,OAAO,IAAI,MAAM,GAAG,GAAiB;AAC3C,kBAAiB,QAAQ;AACzB,aAAY,SAAS,MAAe,OAAO,UAAU,EAAE,CAAC;;AAE5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