From 5936c48441f2e150b8d47472309f681f9cccfb35 Mon Sep 17 00:00:00 2001 From: Mikko Kutilainen Date: Sat, 22 Nov 2025 22:20:09 +0200 Subject: [PATCH 1/9] add support for securitySchemes --- src/server/mcp.ts | 25 ++++++++++++++++++------- src/spec.types.ts | 36 ++++++++++++++++++++++++++++++++++++ src/types.ts | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 7 deletions(-) diff --git a/src/server/mcp.ts b/src/server/mcp.ts index b9b6d55967..11cd9072c4 100644 --- a/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -44,6 +44,7 @@ import { ServerRequest, ServerNotification, ToolAnnotations, + SecurityScheme, LoggingMessageNotification, CompleteRequestPrompt, CompleteRequestResourceTemplate, @@ -112,10 +113,11 @@ export class McpServer { this.server.setRequestHandler( ListToolsRequestSchema, - (): ListToolsResult => ({ - tools: Object.entries(this._registeredTools) - .filter(([, tool]) => tool.enabled) - .map(([name, tool]): Tool => { + (): ListToolsResult => { + return { + tools: Object.entries(this._registeredTools) + .filter(([, tool]) => tool.enabled) + .map(([name, tool]): Tool => { const toolDefinition: Tool = { name, title: tool.title, @@ -130,6 +132,7 @@ export class McpServer { : EMPTY_OBJECT_JSON_SCHEMA; })(), annotations: tool.annotations, + securitySchemes: tool.securitySchemes, _meta: tool._meta }; @@ -145,7 +148,8 @@ export class McpServer { return toolDefinition; }) - }) + }; + } ); this.server.setRequestHandler(CallToolRequestSchema, async (request, extra): Promise => { @@ -697,6 +701,7 @@ export class McpServer { inputSchema: ZodRawShapeCompat | AnySchema | undefined, outputSchema: ZodRawShapeCompat | AnySchema | undefined, annotations: ToolAnnotations | undefined, + securitySchemes: SecurityScheme[] | undefined, _meta: Record | undefined, callback: ToolCallback ): RegisteredTool { @@ -709,6 +714,7 @@ export class McpServer { inputSchema: getZodSchemaObject(inputSchema), outputSchema: getZodSchemaObject(outputSchema), annotations, + securitySchemes, _meta, callback, enabled: true, @@ -728,6 +734,7 @@ export class McpServer { if (typeof updates.paramsSchema !== 'undefined') registeredTool.inputSchema = objectFromShape(updates.paramsSchema); if (typeof updates.callback !== 'undefined') registeredTool.callback = updates.callback; if (typeof updates.annotations !== 'undefined') registeredTool.annotations = updates.annotations; + if (typeof updates.securitySchemes !== 'undefined') registeredTool.securitySchemes = updates.securitySchemes; if (typeof updates._meta !== 'undefined') registeredTool._meta = updates._meta; if (typeof updates.enabled !== 'undefined') registeredTool.enabled = updates.enabled; this.sendToolListChanged(); @@ -851,7 +858,7 @@ export class McpServer { } const callback = rest[0] as ToolCallback; - return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, undefined, callback); + return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, undefined, undefined, callback); } /** @@ -865,6 +872,7 @@ export class McpServer { inputSchema?: InputArgs; outputSchema?: OutputArgs; annotations?: ToolAnnotations; + securitySchemes?: SecurityScheme[]; _meta?: Record; }, cb: ToolCallback @@ -873,7 +881,7 @@ export class McpServer { throw new Error(`Tool ${name} is already registered`); } - const { title, description, inputSchema, outputSchema, annotations, _meta } = config; + const { title, description, inputSchema, outputSchema, annotations, securitySchemes, _meta } = config; return this._createRegisteredTool( name, @@ -882,6 +890,7 @@ export class McpServer { inputSchema, outputSchema, annotations, + securitySchemes, _meta, cb as ToolCallback ); @@ -1101,6 +1110,7 @@ export type RegisteredTool = { inputSchema?: AnySchema; outputSchema?: AnySchema; annotations?: ToolAnnotations; + securitySchemes?: SecurityScheme[]; _meta?: Record; callback: ToolCallback; enabled: boolean; @@ -1113,6 +1123,7 @@ export type RegisteredTool = { paramsSchema?: InputArgs; outputSchema?: OutputArgs; annotations?: ToolAnnotations; + securitySchemes?: SecurityScheme[]; _meta?: Record; callback?: ToolCallback; enabled?: boolean; diff --git a/src/spec.types.ts b/src/spec.types.ts index 6ce24059ef..58eca1d196 100644 --- a/src/spec.types.ts +++ b/src/spec.types.ts @@ -1075,6 +1075,35 @@ export interface ToolListChangedNotification extends JSONRPCNotification { params?: NotificationParams; } +/** + * Security scheme indicating no authentication is required. + * + * @category `tools/list` + */ +export interface NoAuthSecurityScheme { + type: "noauth"; +} + +/** + * Security scheme indicating OAuth 2.0 authentication is required. + * + * @category `tools/list` + */ +export interface OAuth2SecurityScheme { + type: "oauth2"; + /** + * Optional list of OAuth 2.0 scopes required for this tool. + */ + scopes?: string[]; +} + +/** + * A security scheme that can be used to authenticate tool calls. + * + * @category `tools/list` + */ +export type SecurityScheme = NoAuthSecurityScheme | OAuth2SecurityScheme; + /** * Additional properties describing a Tool to clients. * @@ -1170,6 +1199,13 @@ export interface Tool extends BaseMetadata, Icons { */ annotations?: ToolAnnotations; + /** + * Optional list of security schemes supported by this tool. + * If missing, the tool follows the server's default authentication policy. + * If present, lists the supported authentication schemes (e.g., "noauth", "oauth2"). + */ + securitySchemes?: SecurityScheme[]; + /** * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. */ diff --git a/src/types.ts b/src/types.ts index 4ff815ceb0..4e43c564fa 100644 --- a/src/types.ts +++ b/src/types.ts @@ -934,6 +934,34 @@ export const PromptListChangedNotificationSchema = NotificationSchema.extend({ }); /* Tools */ +/** + * Security scheme indicating no authentication is required. + */ +export const NoAuthSecuritySchemeSchema = z.object({ + type: z.literal('noauth') +}); + +/** + * Security scheme indicating OAuth 2.0 authentication is required. + */ +export const OAuth2SecuritySchemeSchema = z.object({ + type: z.literal('oauth2'), + /** + * Optional list of OAuth 2.0 scopes required for this tool. + */ + scopes: z + .array(z.string().min(1)) + .refine((arr) => new Set(arr).size === arr.length, { + message: 'Scopes must be unique' + }) + .optional() +}); + +/** + * A security scheme that can be used to authenticate tool calls. + */ +export const SecuritySchemeSchema = z.union([NoAuthSecuritySchemeSchema, OAuth2SecuritySchemeSchema]); + /** * Additional properties describing a Tool to clients. * @@ -1027,6 +1055,13 @@ export const ToolSchema = z.object({ */ annotations: z.optional(ToolAnnotationsSchema), + /** + * Optional list of security schemes supported by this tool. + * If missing, the tool follows the server's default authentication policy. + * If present, lists the supported authentication schemes (e.g., "noauth", "oauth2"). + */ + securitySchemes: z.array(SecuritySchemeSchema).optional(), + /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. @@ -1946,6 +1981,9 @@ export type GetPromptResult = Infer; export type PromptListChangedNotification = Infer; /* Tools */ +export type NoAuthSecurityScheme = Infer; +export type OAuth2SecurityScheme = Infer; +export type SecurityScheme = Infer; export type ToolAnnotations = Infer; export type Tool = Infer; export type ListToolsRequest = Infer; From 1f0373040780996368d53bc4ec27bb55aa46f219 Mon Sep 17 00:00:00 2001 From: Mikko Kutilainen Date: Sat, 22 Nov 2025 22:20:44 +0200 Subject: [PATCH 2/9] include dist --- .gitignore | 4 +- dist/cjs/client/auth.d.ts | 280 ++ dist/cjs/client/auth.d.ts.map | 1 + dist/cjs/client/auth.js | 799 +++ dist/cjs/client/auth.js.map | 1 + dist/cjs/client/index.d.ts | 379 ++ dist/cjs/client/index.d.ts.map | 1 + dist/cjs/client/index.js | 423 ++ dist/cjs/client/index.js.map | 1 + dist/cjs/client/middleware.d.ts | 169 + dist/cjs/client/middleware.d.ts.map | 1 + dist/cjs/client/middleware.js | 252 + dist/cjs/client/middleware.js.map | 1 + dist/cjs/client/sse.d.ts | 81 + dist/cjs/client/sse.d.ts.map | 1 + dist/cjs/client/sse.js | 213 + dist/cjs/client/sse.js.map | 1 + dist/cjs/client/stdio.d.ts | 78 + dist/cjs/client/stdio.d.ts.map | 1 + dist/cjs/client/stdio.js | 184 + dist/cjs/client/stdio.js.map | 1 + dist/cjs/client/streamableHttp.d.ts | 159 + dist/cjs/client/streamableHttp.d.ts.map | 1 + dist/cjs/client/streamableHttp.js | 426 ++ dist/cjs/client/streamableHttp.js.map | 1 + dist/cjs/client/websocket.d.ts | 17 + dist/cjs/client/websocket.d.ts.map | 1 + dist/cjs/client/websocket.js | 63 + dist/cjs/client/websocket.js.map | 1 + .../client/elicitationUrlExample.d.ts | 2 + .../client/elicitationUrlExample.d.ts.map | 1 + .../examples/client/elicitationUrlExample.js | 693 +++ .../client/elicitationUrlExample.js.map | 1 + .../client/multipleClientsParallel.d.ts | 2 + .../client/multipleClientsParallel.d.ts.map | 1 + .../client/multipleClientsParallel.js | 134 + .../client/multipleClientsParallel.js.map | 1 + .../client/parallelToolCallsClient.d.ts | 2 + .../client/parallelToolCallsClient.d.ts.map | 1 + .../client/parallelToolCallsClient.js | 176 + .../client/parallelToolCallsClient.js.map | 1 + .../examples/client/simpleOAuthClient.d.ts | 3 + .../client/simpleOAuthClient.d.ts.map | 1 + dist/cjs/examples/client/simpleOAuthClient.js | 337 ++ .../examples/client/simpleOAuthClient.js.map | 1 + .../client/simpleOAuthClientProvider.d.ts | 26 + .../client/simpleOAuthClientProvider.d.ts.map | 1 + .../client/simpleOAuthClientProvider.js | 51 + .../client/simpleOAuthClientProvider.js.map | 1 + .../examples/client/simpleStreamableHttp.d.ts | 2 + .../client/simpleStreamableHttp.d.ts.map | 1 + .../examples/client/simpleStreamableHttp.js | 749 +++ .../client/simpleStreamableHttp.js.map | 1 + .../streamableHttpWithSseFallbackClient.d.ts | 2 + ...reamableHttpWithSseFallbackClient.d.ts.map | 1 + .../streamableHttpWithSseFallbackClient.js | 168 + ...streamableHttpWithSseFallbackClient.js.map | 1 + .../server/demoInMemoryOAuthProvider.d.ts | 78 + .../server/demoInMemoryOAuthProvider.d.ts.map | 1 + .../server/demoInMemoryOAuthProvider.js | 205 + .../server/demoInMemoryOAuthProvider.js.map | 1 + .../server/elicitationFormExample.d.ts | 2 + .../server/elicitationFormExample.d.ts.map | 1 + .../examples/server/elicitationFormExample.js | 441 ++ .../server/elicitationFormExample.js.map | 1 + .../server/elicitationUrlExample.d.ts | 2 + .../server/elicitationUrlExample.d.ts.map | 1 + .../examples/server/elicitationUrlExample.js | 655 +++ .../server/elicitationUrlExample.js.map | 1 + .../server/jsonResponseStreamableHttp.d.ts | 2 + .../jsonResponseStreamableHttp.d.ts.map | 1 + .../server/jsonResponseStreamableHttp.js | 175 + .../server/jsonResponseStreamableHttp.js.map | 1 + .../server/mcpServerOutputSchema.d.ts | 7 + .../server/mcpServerOutputSchema.d.ts.map | 1 + .../examples/server/mcpServerOutputSchema.js | 95 + .../server/mcpServerOutputSchema.js.map | 1 + dist/cjs/examples/server/simpleSseServer.d.ts | 2 + .../examples/server/simpleSseServer.d.ts.map | 1 + dist/cjs/examples/server/simpleSseServer.js | 169 + .../examples/server/simpleSseServer.js.map | 1 + .../server/simpleStatelessStreamableHttp.d.ts | 2 + .../simpleStatelessStreamableHttp.d.ts.map | 1 + .../server/simpleStatelessStreamableHttp.js | 170 + .../simpleStatelessStreamableHttp.js.map | 1 + .../examples/server/simpleStreamableHttp.d.ts | 2 + .../server/simpleStreamableHttp.d.ts.map | 1 + .../examples/server/simpleStreamableHttp.js | 611 +++ .../server/simpleStreamableHttp.js.map | 1 + .../sseAndStreamableHttpCompatibleServer.d.ts | 2 + ...AndStreamableHttpCompatibleServer.d.ts.map | 1 + .../sseAndStreamableHttpCompatibleServer.js | 263 + ...seAndStreamableHttpCompatibleServer.js.map | 1 + .../standaloneSseWithGetStreamableHttp.d.ts | 2 + ...tandaloneSseWithGetStreamableHttp.d.ts.map | 1 + .../standaloneSseWithGetStreamableHttp.js | 116 + .../standaloneSseWithGetStreamableHttp.js.map | 1 + .../examples/server/toolWithSampleServer.d.ts | 2 + .../server/toolWithSampleServer.d.ts.map | 1 + .../examples/server/toolWithSampleServer.js | 71 + .../server/toolWithSampleServer.js.map | 1 + .../examples/shared/inMemoryEventStore.d.ts | 31 + .../shared/inMemoryEventStore.d.ts.map | 1 + .../cjs/examples/shared/inMemoryEventStore.js | 69 + .../examples/shared/inMemoryEventStore.js.map | 1 + dist/cjs/inMemory.d.ts | 31 + dist/cjs/inMemory.d.ts.map | 1 + dist/cjs/inMemory.js | 53 + dist/cjs/inMemory.js.map | 1 + dist/cjs/package.json | 1 + dist/cjs/server/auth/clients.d.ts | 19 + dist/cjs/server/auth/clients.d.ts.map | 1 + dist/cjs/server/auth/clients.js | 3 + dist/cjs/server/auth/clients.js.map | 1 + dist/cjs/server/auth/errors.d.ts | 141 + dist/cjs/server/auth/errors.d.ts.map | 1 + dist/cjs/server/auth/errors.js | 193 + dist/cjs/server/auth/errors.js.map | 1 + dist/cjs/server/auth/handlers/authorize.d.ts | 13 + .../server/auth/handlers/authorize.d.ts.map | 1 + dist/cjs/server/auth/handlers/authorize.js | 167 + .../cjs/server/auth/handlers/authorize.js.map | 1 + dist/cjs/server/auth/handlers/metadata.d.ts | 4 + .../server/auth/handlers/metadata.d.ts.map | 1 + dist/cjs/server/auth/handlers/metadata.js | 21 + dist/cjs/server/auth/handlers/metadata.js.map | 1 + dist/cjs/server/auth/handlers/register.d.ts | 29 + .../server/auth/handlers/register.d.ts.map | 1 + dist/cjs/server/auth/handlers/register.js | 77 + dist/cjs/server/auth/handlers/register.js.map | 1 + dist/cjs/server/auth/handlers/revoke.d.ts | 13 + dist/cjs/server/auth/handlers/revoke.d.ts.map | 1 + dist/cjs/server/auth/handlers/revoke.js | 65 + dist/cjs/server/auth/handlers/revoke.js.map | 1 + dist/cjs/server/auth/handlers/token.d.ts | 13 + dist/cjs/server/auth/handlers/token.d.ts.map | 1 + dist/cjs/server/auth/handlers/token.js | 136 + dist/cjs/server/auth/handlers/token.js.map | 1 + .../auth/middleware/allowedMethods.d.ts | 9 + .../auth/middleware/allowedMethods.d.ts.map | 1 + .../server/auth/middleware/allowedMethods.js | 21 + .../auth/middleware/allowedMethods.js.map | 1 + .../server/auth/middleware/bearerAuth.d.ts | 35 + .../auth/middleware/bearerAuth.d.ts.map | 1 + dist/cjs/server/auth/middleware/bearerAuth.js | 75 + .../server/auth/middleware/bearerAuth.js.map | 1 + .../server/auth/middleware/clientAuth.d.ts | 19 + .../auth/middleware/clientAuth.d.ts.map | 1 + dist/cjs/server/auth/middleware/clientAuth.js | 75 + .../server/auth/middleware/clientAuth.js.map | 1 + dist/cjs/server/auth/provider.d.ts | 68 + dist/cjs/server/auth/provider.d.ts.map | 1 + dist/cjs/server/auth/provider.js | 3 + dist/cjs/server/auth/provider.js.map | 1 + .../server/auth/providers/proxyProvider.d.ts | 49 + .../auth/providers/proxyProvider.d.ts.map | 1 + .../server/auth/providers/proxyProvider.js | 161 + .../auth/providers/proxyProvider.js.map | 1 + dist/cjs/server/auth/router.d.ts | 101 + dist/cjs/server/auth/router.d.ts.map | 1 + dist/cjs/server/auth/router.js | 125 + dist/cjs/server/auth/router.js.map | 1 + dist/cjs/server/auth/types.d.ts | 32 + dist/cjs/server/auth/types.d.ts.map | 1 + dist/cjs/server/auth/types.js | 3 + dist/cjs/server/auth/types.js.map | 1 + dist/cjs/server/completable.d.ts | 38 + dist/cjs/server/completable.d.ts.map | 1 + dist/cjs/server/completable.js | 48 + dist/cjs/server/completable.js.map | 1 + dist/cjs/server/index.d.ts | 333 ++ dist/cjs/server/index.d.ts.map | 1 + dist/cjs/server/index.js | 304 ++ dist/cjs/server/index.js.map | 1 + dist/cjs/server/mcp.d.ts | 332 ++ dist/cjs/server/mcp.d.ts.map | 1 + dist/cjs/server/mcp.js | 758 +++ dist/cjs/server/mcp.js.map | 1 + dist/cjs/server/sse.d.ts | 76 + dist/cjs/server/sse.d.ts.map | 1 + dist/cjs/server/sse.js | 168 + dist/cjs/server/sse.js.map | 1 + dist/cjs/server/stdio.d.ts | 28 + dist/cjs/server/stdio.d.ts.map | 1 + dist/cjs/server/stdio.js | 85 + dist/cjs/server/stdio.js.map | 1 + dist/cjs/server/streamableHttp.d.ts | 185 + dist/cjs/server/streamableHttp.d.ts.map | 1 + dist/cjs/server/streamableHttp.js | 631 +++ dist/cjs/server/streamableHttp.js.map | 1 + dist/cjs/server/zod-compat.d.ts | 82 + dist/cjs/server/zod-compat.d.ts.map | 1 + dist/cjs/server/zod-compat.js | 252 + dist/cjs/server/zod-compat.js.map | 1 + dist/cjs/server/zod-json-schema-compat.d.ts | 12 + .../server/zod-json-schema-compat.d.ts.map | 1 + dist/cjs/server/zod-json-schema-compat.js | 80 + dist/cjs/server/zod-json-schema-compat.js.map | 1 + dist/cjs/shared/auth-utils.d.ts | 23 + dist/cjs/shared/auth-utils.d.ts.map | 1 + dist/cjs/shared/auth-utils.js | 48 + dist/cjs/shared/auth-utils.js.map | 1 + dist/cjs/shared/auth.d.ts | 240 + dist/cjs/shared/auth.d.ts.map | 1 + dist/cjs/shared/auth.js | 224 + dist/cjs/shared/auth.js.map | 1 + dist/cjs/shared/metadataUtils.d.ts | 16 + dist/cjs/shared/metadataUtils.d.ts.map | 1 + dist/cjs/shared/metadataUtils.js | 26 + dist/cjs/shared/metadataUtils.js.map | 1 + dist/cjs/shared/protocol.d.ts | 226 + dist/cjs/shared/protocol.d.ts.map | 1 + dist/cjs/shared/protocol.js | 442 ++ dist/cjs/shared/protocol.js.map | 1 + dist/cjs/shared/stdio.d.ts | 13 + dist/cjs/shared/stdio.d.ts.map | 1 + dist/cjs/shared/stdio.js | 37 + dist/cjs/shared/stdio.js.map | 1 + dist/cjs/shared/toolNameValidation.d.ts | 31 + dist/cjs/shared/toolNameValidation.d.ts.map | 1 + dist/cjs/shared/toolNameValidation.js | 97 + dist/cjs/shared/toolNameValidation.js.map | 1 + dist/cjs/shared/transport.d.ts | 89 + dist/cjs/shared/transport.d.ts.map | 1 + dist/cjs/shared/transport.js | 43 + dist/cjs/shared/transport.js.map | 1 + dist/cjs/shared/uriTemplate.d.ts | 25 + dist/cjs/shared/uriTemplate.d.ts.map | 1 + dist/cjs/shared/uriTemplate.js | 243 + dist/cjs/shared/uriTemplate.js.map | 1 + dist/cjs/shared/zodTestMatrix.d.ts | 16 + dist/cjs/shared/zodTestMatrix.d.ts.map | 1 + dist/cjs/shared/zodTestMatrix.js | 43 + dist/cjs/shared/zodTestMatrix.js.map | 1 + dist/cjs/spec.types.d.ts | 2033 ++++++++ dist/cjs/spec.types.d.ts.map | 1 + dist/cjs/spec.types.js | 27 + dist/cjs/spec.types.js.map | 1 + dist/cjs/types.d.ts | 4390 +++++++++++++++++ dist/cjs/types.d.ts.map | 1 + dist/cjs/types.js | 1697 +++++++ dist/cjs/types.js.map | 1 + dist/cjs/validation/ajv-provider.d.ts | 53 + dist/cjs/validation/ajv-provider.d.ts.map | 1 + dist/cjs/validation/ajv-provider.js | 95 + dist/cjs/validation/ajv-provider.js.map | 1 + dist/cjs/validation/cfworker-provider.d.ts | 51 + .../cjs/validation/cfworker-provider.d.ts.map | 1 + dist/cjs/validation/cfworker-provider.js | 70 + dist/cjs/validation/cfworker-provider.js.map | 1 + dist/cjs/validation/index.d.ts | 29 + dist/cjs/validation/index.d.ts.map | 1 + dist/cjs/validation/index.js | 30 + dist/cjs/validation/index.js.map | 1 + dist/cjs/validation/types.d.ts | 55 + dist/cjs/validation/types.d.ts.map | 1 + dist/cjs/validation/types.js | 3 + dist/cjs/validation/types.js.map | 1 + dist/esm/client/auth.d.ts | 280 ++ dist/esm/client/auth.d.ts.map | 1 + dist/esm/client/auth.js | 777 +++ dist/esm/client/auth.js.map | 1 + dist/esm/client/index.d.ts | 379 ++ dist/esm/client/index.d.ts.map | 1 + dist/esm/client/index.js | 418 ++ dist/esm/client/index.js.map | 1 + dist/esm/client/middleware.d.ts | 169 + dist/esm/client/middleware.d.ts.map | 1 + dist/esm/client/middleware.js | 245 + dist/esm/client/middleware.js.map | 1 + dist/esm/client/sse.d.ts | 81 + dist/esm/client/sse.d.ts.map | 1 + dist/esm/client/sse.js | 208 + dist/esm/client/sse.js.map | 1 + dist/esm/client/stdio.d.ts | 78 + dist/esm/client/stdio.d.ts.map | 1 + dist/esm/client/stdio.js | 176 + dist/esm/client/stdio.js.map | 1 + dist/esm/client/streamableHttp.d.ts | 159 + dist/esm/client/streamableHttp.d.ts.map | 1 + dist/esm/client/streamableHttp.js | 421 ++ dist/esm/client/streamableHttp.js.map | 1 + dist/esm/client/websocket.d.ts | 17 + dist/esm/client/websocket.d.ts.map | 1 + dist/esm/client/websocket.js | 59 + dist/esm/client/websocket.js.map | 1 + .../client/elicitationUrlExample.d.ts | 2 + .../client/elicitationUrlExample.d.ts.map | 1 + .../examples/client/elicitationUrlExample.js | 691 +++ .../client/elicitationUrlExample.js.map | 1 + .../client/multipleClientsParallel.d.ts | 2 + .../client/multipleClientsParallel.d.ts.map | 1 + .../client/multipleClientsParallel.js | 132 + .../client/multipleClientsParallel.js.map | 1 + .../client/parallelToolCallsClient.d.ts | 2 + .../client/parallelToolCallsClient.d.ts.map | 1 + .../client/parallelToolCallsClient.js | 174 + .../client/parallelToolCallsClient.js.map | 1 + .../examples/client/simpleOAuthClient.d.ts | 3 + .../client/simpleOAuthClient.d.ts.map | 1 + dist/esm/examples/client/simpleOAuthClient.js | 335 ++ .../examples/client/simpleOAuthClient.js.map | 1 + .../client/simpleOAuthClientProvider.d.ts | 26 + .../client/simpleOAuthClientProvider.d.ts.map | 1 + .../client/simpleOAuthClientProvider.js | 47 + .../client/simpleOAuthClientProvider.js.map | 1 + .../examples/client/simpleStreamableHttp.d.ts | 2 + .../client/simpleStreamableHttp.d.ts.map | 1 + .../examples/client/simpleStreamableHttp.js | 747 +++ .../client/simpleStreamableHttp.js.map | 1 + .../streamableHttpWithSseFallbackClient.d.ts | 2 + ...reamableHttpWithSseFallbackClient.d.ts.map | 1 + .../streamableHttpWithSseFallbackClient.js | 166 + ...streamableHttpWithSseFallbackClient.js.map | 1 + .../server/demoInMemoryOAuthProvider.d.ts | 78 + .../server/demoInMemoryOAuthProvider.d.ts.map | 1 + .../server/demoInMemoryOAuthProvider.js | 196 + .../server/demoInMemoryOAuthProvider.js.map | 1 + .../server/elicitationFormExample.d.ts | 2 + .../server/elicitationFormExample.d.ts.map | 1 + .../examples/server/elicitationFormExample.js | 436 ++ .../server/elicitationFormExample.js.map | 1 + .../server/elicitationUrlExample.d.ts | 2 + .../server/elicitationUrlExample.d.ts.map | 1 + .../examples/server/elicitationUrlExample.js | 650 +++ .../server/elicitationUrlExample.js.map | 1 + .../server/jsonResponseStreamableHttp.d.ts | 2 + .../jsonResponseStreamableHttp.d.ts.map | 1 + .../server/jsonResponseStreamableHttp.js | 147 + .../server/jsonResponseStreamableHttp.js.map | 1 + .../server/mcpServerOutputSchema.d.ts | 7 + .../server/mcpServerOutputSchema.d.ts.map | 1 + .../examples/server/mcpServerOutputSchema.js | 70 + .../server/mcpServerOutputSchema.js.map | 1 + dist/esm/examples/server/simpleSseServer.d.ts | 2 + .../examples/server/simpleSseServer.d.ts.map | 1 + dist/esm/examples/server/simpleSseServer.js | 141 + .../examples/server/simpleSseServer.js.map | 1 + .../server/simpleStatelessStreamableHttp.d.ts | 2 + .../simpleStatelessStreamableHttp.d.ts.map | 1 + .../server/simpleStatelessStreamableHttp.js | 142 + .../simpleStatelessStreamableHttp.js.map | 1 + .../examples/server/simpleStreamableHttp.d.ts | 2 + .../server/simpleStreamableHttp.d.ts.map | 1 + .../examples/server/simpleStreamableHttp.js | 583 +++ .../server/simpleStreamableHttp.js.map | 1 + .../sseAndStreamableHttpCompatibleServer.d.ts | 2 + ...AndStreamableHttpCompatibleServer.d.ts.map | 1 + .../sseAndStreamableHttpCompatibleServer.js | 235 + ...seAndStreamableHttpCompatibleServer.js.map | 1 + .../standaloneSseWithGetStreamableHttp.d.ts | 2 + ...tandaloneSseWithGetStreamableHttp.d.ts.map | 1 + .../standaloneSseWithGetStreamableHttp.js | 111 + .../standaloneSseWithGetStreamableHttp.js.map | 1 + .../examples/server/toolWithSampleServer.d.ts | 2 + .../server/toolWithSampleServer.d.ts.map | 1 + .../examples/server/toolWithSampleServer.js | 46 + .../server/toolWithSampleServer.js.map | 1 + .../examples/shared/inMemoryEventStore.d.ts | 31 + .../shared/inMemoryEventStore.d.ts.map | 1 + .../esm/examples/shared/inMemoryEventStore.js | 65 + .../examples/shared/inMemoryEventStore.js.map | 1 + dist/esm/inMemory.d.ts | 31 + dist/esm/inMemory.d.ts.map | 1 + dist/esm/inMemory.js | 49 + dist/esm/inMemory.js.map | 1 + dist/esm/package.json | 1 + dist/esm/server/auth/clients.d.ts | 19 + dist/esm/server/auth/clients.d.ts.map | 1 + dist/esm/server/auth/clients.js | 2 + dist/esm/server/auth/clients.js.map | 1 + dist/esm/server/auth/errors.d.ts | 141 + dist/esm/server/auth/errors.d.ts.map | 1 + dist/esm/server/auth/errors.js | 172 + dist/esm/server/auth/errors.js.map | 1 + dist/esm/server/auth/handlers/authorize.d.ts | 13 + .../server/auth/handlers/authorize.d.ts.map | 1 + dist/esm/server/auth/handlers/authorize.js | 138 + .../esm/server/auth/handlers/authorize.js.map | 1 + dist/esm/server/auth/handlers/metadata.d.ts | 4 + .../server/auth/handlers/metadata.d.ts.map | 1 + dist/esm/server/auth/handlers/metadata.js | 15 + dist/esm/server/auth/handlers/metadata.js.map | 1 + dist/esm/server/auth/handlers/register.d.ts | 29 + .../server/auth/handlers/register.d.ts.map | 1 + dist/esm/server/auth/handlers/register.js | 71 + dist/esm/server/auth/handlers/register.js.map | 1 + dist/esm/server/auth/handlers/revoke.d.ts | 13 + dist/esm/server/auth/handlers/revoke.d.ts.map | 1 + dist/esm/server/auth/handlers/revoke.js | 59 + dist/esm/server/auth/handlers/revoke.js.map | 1 + dist/esm/server/auth/handlers/token.d.ts | 13 + dist/esm/server/auth/handlers/token.d.ts.map | 1 + dist/esm/server/auth/handlers/token.js | 107 + dist/esm/server/auth/handlers/token.js.map | 1 + .../auth/middleware/allowedMethods.d.ts | 9 + .../auth/middleware/allowedMethods.d.ts.map | 1 + .../server/auth/middleware/allowedMethods.js | 18 + .../auth/middleware/allowedMethods.js.map | 1 + .../server/auth/middleware/bearerAuth.d.ts | 35 + .../auth/middleware/bearerAuth.d.ts.map | 1 + dist/esm/server/auth/middleware/bearerAuth.js | 72 + .../server/auth/middleware/bearerAuth.js.map | 1 + .../server/auth/middleware/clientAuth.d.ts | 19 + .../auth/middleware/clientAuth.d.ts.map | 1 + dist/esm/server/auth/middleware/clientAuth.js | 49 + .../server/auth/middleware/clientAuth.js.map | 1 + dist/esm/server/auth/provider.d.ts | 68 + dist/esm/server/auth/provider.d.ts.map | 1 + dist/esm/server/auth/provider.js | 2 + dist/esm/server/auth/provider.js.map | 1 + .../server/auth/providers/proxyProvider.d.ts | 49 + .../auth/providers/proxyProvider.d.ts.map | 1 + .../server/auth/providers/proxyProvider.js | 157 + .../auth/providers/proxyProvider.js.map | 1 + dist/esm/server/auth/router.d.ts | 101 + dist/esm/server/auth/router.d.ts.map | 1 + dist/esm/server/auth/router.js | 115 + dist/esm/server/auth/router.js.map | 1 + dist/esm/server/auth/types.d.ts | 32 + dist/esm/server/auth/types.d.ts.map | 1 + dist/esm/server/auth/types.js | 2 + dist/esm/server/auth/types.js.map | 1 + dist/esm/server/completable.d.ts | 38 + dist/esm/server/completable.d.ts.map | 1 + dist/esm/server/completable.js | 41 + dist/esm/server/completable.js.map | 1 + dist/esm/server/index.d.ts | 333 ++ dist/esm/server/index.d.ts.map | 1 + dist/esm/server/index.js | 300 ++ dist/esm/server/index.js.map | 1 + dist/esm/server/mcp.d.ts | 332 ++ dist/esm/server/mcp.d.ts.map | 1 + dist/esm/server/mcp.js | 753 +++ dist/esm/server/mcp.js.map | 1 + dist/esm/server/sse.d.ts | 76 + dist/esm/server/sse.d.ts.map | 1 + dist/esm/server/sse.js | 161 + dist/esm/server/sse.js.map | 1 + dist/esm/server/stdio.d.ts | 28 + dist/esm/server/stdio.d.ts.map | 1 + dist/esm/server/stdio.js | 78 + dist/esm/server/stdio.js.map | 1 + dist/esm/server/streamableHttp.d.ts | 185 + dist/esm/server/streamableHttp.d.ts.map | 1 + dist/esm/server/streamableHttp.js | 624 +++ dist/esm/server/streamableHttp.js.map | 1 + dist/esm/server/zod-compat.d.ts | 82 + dist/esm/server/zod-compat.d.ts.map | 1 + dist/esm/server/zod-compat.js | 217 + dist/esm/server/zod-compat.js.map | 1 + dist/esm/server/zod-json-schema-compat.d.ts | 12 + .../server/zod-json-schema-compat.d.ts.map | 1 + dist/esm/server/zod-json-schema-compat.js | 52 + dist/esm/server/zod-json-schema-compat.js.map | 1 + dist/esm/shared/auth-utils.d.ts | 23 + dist/esm/shared/auth-utils.d.ts.map | 1 + dist/esm/shared/auth-utils.js | 44 + dist/esm/shared/auth-utils.js.map | 1 + dist/esm/shared/auth.d.ts | 240 + dist/esm/shared/auth.d.ts.map | 1 + dist/esm/shared/auth.js | 198 + dist/esm/shared/auth.js.map | 1 + dist/esm/shared/metadataUtils.d.ts | 16 + dist/esm/shared/metadataUtils.d.ts.map | 1 + dist/esm/shared/metadataUtils.js | 23 + dist/esm/shared/metadataUtils.js.map | 1 + dist/esm/shared/protocol.d.ts | 226 + dist/esm/shared/protocol.d.ts.map | 1 + dist/esm/shared/protocol.js | 437 ++ dist/esm/shared/protocol.js.map | 1 + dist/esm/shared/stdio.d.ts | 13 + dist/esm/shared/stdio.d.ts.map | 1 + dist/esm/shared/stdio.js | 31 + dist/esm/shared/stdio.js.map | 1 + dist/esm/shared/toolNameValidation.d.ts | 31 + dist/esm/shared/toolNameValidation.d.ts.map | 1 + dist/esm/shared/toolNameValidation.js | 92 + dist/esm/shared/toolNameValidation.js.map | 1 + dist/esm/shared/transport.d.ts | 89 + dist/esm/shared/transport.d.ts.map | 1 + dist/esm/shared/transport.js | 39 + dist/esm/shared/transport.js.map | 1 + dist/esm/shared/uriTemplate.d.ts | 25 + dist/esm/shared/uriTemplate.d.ts.map | 1 + dist/esm/shared/uriTemplate.js | 239 + dist/esm/shared/uriTemplate.js.map | 1 + dist/esm/shared/zodTestMatrix.d.ts | 16 + dist/esm/shared/zodTestMatrix.d.ts.map | 1 + dist/esm/shared/zodTestMatrix.js | 17 + dist/esm/shared/zodTestMatrix.js.map | 1 + dist/esm/spec.types.d.ts | 2033 ++++++++ dist/esm/spec.types.d.ts.map | 1 + dist/esm/spec.types.js | 24 + dist/esm/spec.types.js.map | 1 + dist/esm/types.d.ts | 4390 +++++++++++++++++ dist/esm/types.d.ts.map | 1 + dist/esm/types.js | 1659 +++++++ dist/esm/types.js.map | 1 + dist/esm/validation/ajv-provider.d.ts | 53 + dist/esm/validation/ajv-provider.d.ts.map | 1 + dist/esm/validation/ajv-provider.js | 88 + dist/esm/validation/ajv-provider.js.map | 1 + dist/esm/validation/cfworker-provider.d.ts | 51 + .../esm/validation/cfworker-provider.d.ts.map | 1 + dist/esm/validation/cfworker-provider.js | 66 + dist/esm/validation/cfworker-provider.js.map | 1 + dist/esm/validation/index.d.ts | 29 + dist/esm/validation/index.d.ts.map | 1 + dist/esm/validation/index.js | 29 + dist/esm/validation/index.js.map | 1 + dist/esm/validation/types.d.ts | 55 + dist/esm/validation/types.d.ts.map | 1 + dist/esm/validation/types.js | 2 + dist/esm/validation/types.js.map | 1 + 515 files changed, 48834 insertions(+), 1 deletion(-) create mode 100644 dist/cjs/client/auth.d.ts create mode 100644 dist/cjs/client/auth.d.ts.map create mode 100644 dist/cjs/client/auth.js create mode 100644 dist/cjs/client/auth.js.map create mode 100644 dist/cjs/client/index.d.ts create mode 100644 dist/cjs/client/index.d.ts.map create mode 100644 dist/cjs/client/index.js create mode 100644 dist/cjs/client/index.js.map create mode 100644 dist/cjs/client/middleware.d.ts create mode 100644 dist/cjs/client/middleware.d.ts.map create mode 100644 dist/cjs/client/middleware.js create mode 100644 dist/cjs/client/middleware.js.map create mode 100644 dist/cjs/client/sse.d.ts create mode 100644 dist/cjs/client/sse.d.ts.map create mode 100644 dist/cjs/client/sse.js create mode 100644 dist/cjs/client/sse.js.map create mode 100644 dist/cjs/client/stdio.d.ts create mode 100644 dist/cjs/client/stdio.d.ts.map create mode 100644 dist/cjs/client/stdio.js create mode 100644 dist/cjs/client/stdio.js.map create mode 100644 dist/cjs/client/streamableHttp.d.ts create mode 100644 dist/cjs/client/streamableHttp.d.ts.map create mode 100644 dist/cjs/client/streamableHttp.js create mode 100644 dist/cjs/client/streamableHttp.js.map create mode 100644 dist/cjs/client/websocket.d.ts create mode 100644 dist/cjs/client/websocket.d.ts.map create mode 100644 dist/cjs/client/websocket.js create mode 100644 dist/cjs/client/websocket.js.map create mode 100644 dist/cjs/examples/client/elicitationUrlExample.d.ts create mode 100644 dist/cjs/examples/client/elicitationUrlExample.d.ts.map create mode 100644 dist/cjs/examples/client/elicitationUrlExample.js create mode 100644 dist/cjs/examples/client/elicitationUrlExample.js.map create mode 100644 dist/cjs/examples/client/multipleClientsParallel.d.ts create mode 100644 dist/cjs/examples/client/multipleClientsParallel.d.ts.map create mode 100644 dist/cjs/examples/client/multipleClientsParallel.js create mode 100644 dist/cjs/examples/client/multipleClientsParallel.js.map create mode 100644 dist/cjs/examples/client/parallelToolCallsClient.d.ts create mode 100644 dist/cjs/examples/client/parallelToolCallsClient.d.ts.map create mode 100644 dist/cjs/examples/client/parallelToolCallsClient.js create mode 100644 dist/cjs/examples/client/parallelToolCallsClient.js.map create mode 100644 dist/cjs/examples/client/simpleOAuthClient.d.ts create mode 100644 dist/cjs/examples/client/simpleOAuthClient.d.ts.map create mode 100644 dist/cjs/examples/client/simpleOAuthClient.js create mode 100644 dist/cjs/examples/client/simpleOAuthClient.js.map create mode 100644 dist/cjs/examples/client/simpleOAuthClientProvider.d.ts create mode 100644 dist/cjs/examples/client/simpleOAuthClientProvider.d.ts.map create mode 100644 dist/cjs/examples/client/simpleOAuthClientProvider.js create mode 100644 dist/cjs/examples/client/simpleOAuthClientProvider.js.map create mode 100644 dist/cjs/examples/client/simpleStreamableHttp.d.ts create mode 100644 dist/cjs/examples/client/simpleStreamableHttp.d.ts.map create mode 100644 dist/cjs/examples/client/simpleStreamableHttp.js create mode 100644 dist/cjs/examples/client/simpleStreamableHttp.js.map create mode 100644 dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts create mode 100644 dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts.map create mode 100644 dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js create mode 100644 dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js.map create mode 100644 dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts create mode 100644 dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts.map create mode 100644 dist/cjs/examples/server/demoInMemoryOAuthProvider.js create mode 100644 dist/cjs/examples/server/demoInMemoryOAuthProvider.js.map create mode 100644 dist/cjs/examples/server/elicitationFormExample.d.ts create mode 100644 dist/cjs/examples/server/elicitationFormExample.d.ts.map create mode 100644 dist/cjs/examples/server/elicitationFormExample.js create mode 100644 dist/cjs/examples/server/elicitationFormExample.js.map create mode 100644 dist/cjs/examples/server/elicitationUrlExample.d.ts create mode 100644 dist/cjs/examples/server/elicitationUrlExample.d.ts.map create mode 100644 dist/cjs/examples/server/elicitationUrlExample.js create mode 100644 dist/cjs/examples/server/elicitationUrlExample.js.map create mode 100644 dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts create mode 100644 dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts.map create mode 100644 dist/cjs/examples/server/jsonResponseStreamableHttp.js create mode 100644 dist/cjs/examples/server/jsonResponseStreamableHttp.js.map create mode 100644 dist/cjs/examples/server/mcpServerOutputSchema.d.ts create mode 100644 dist/cjs/examples/server/mcpServerOutputSchema.d.ts.map create mode 100644 dist/cjs/examples/server/mcpServerOutputSchema.js create mode 100644 dist/cjs/examples/server/mcpServerOutputSchema.js.map create mode 100644 dist/cjs/examples/server/simpleSseServer.d.ts create mode 100644 dist/cjs/examples/server/simpleSseServer.d.ts.map create mode 100644 dist/cjs/examples/server/simpleSseServer.js create mode 100644 dist/cjs/examples/server/simpleSseServer.js.map create mode 100644 dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts create mode 100644 dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts.map create mode 100644 dist/cjs/examples/server/simpleStatelessStreamableHttp.js create mode 100644 dist/cjs/examples/server/simpleStatelessStreamableHttp.js.map create mode 100644 dist/cjs/examples/server/simpleStreamableHttp.d.ts create mode 100644 dist/cjs/examples/server/simpleStreamableHttp.d.ts.map create mode 100644 dist/cjs/examples/server/simpleStreamableHttp.js create mode 100644 dist/cjs/examples/server/simpleStreamableHttp.js.map create mode 100644 dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts create mode 100644 dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map create mode 100644 dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js create mode 100644 dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js.map create mode 100644 dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts create mode 100644 dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map create mode 100644 dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js create mode 100644 dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js.map create mode 100644 dist/cjs/examples/server/toolWithSampleServer.d.ts create mode 100644 dist/cjs/examples/server/toolWithSampleServer.d.ts.map create mode 100644 dist/cjs/examples/server/toolWithSampleServer.js create mode 100644 dist/cjs/examples/server/toolWithSampleServer.js.map create mode 100644 dist/cjs/examples/shared/inMemoryEventStore.d.ts create mode 100644 dist/cjs/examples/shared/inMemoryEventStore.d.ts.map create mode 100644 dist/cjs/examples/shared/inMemoryEventStore.js create mode 100644 dist/cjs/examples/shared/inMemoryEventStore.js.map create mode 100644 dist/cjs/inMemory.d.ts create mode 100644 dist/cjs/inMemory.d.ts.map create mode 100644 dist/cjs/inMemory.js create mode 100644 dist/cjs/inMemory.js.map create mode 100644 dist/cjs/package.json create mode 100644 dist/cjs/server/auth/clients.d.ts create mode 100644 dist/cjs/server/auth/clients.d.ts.map create mode 100644 dist/cjs/server/auth/clients.js create mode 100644 dist/cjs/server/auth/clients.js.map create mode 100644 dist/cjs/server/auth/errors.d.ts create mode 100644 dist/cjs/server/auth/errors.d.ts.map create mode 100644 dist/cjs/server/auth/errors.js create mode 100644 dist/cjs/server/auth/errors.js.map create mode 100644 dist/cjs/server/auth/handlers/authorize.d.ts create mode 100644 dist/cjs/server/auth/handlers/authorize.d.ts.map create mode 100644 dist/cjs/server/auth/handlers/authorize.js create mode 100644 dist/cjs/server/auth/handlers/authorize.js.map create mode 100644 dist/cjs/server/auth/handlers/metadata.d.ts create mode 100644 dist/cjs/server/auth/handlers/metadata.d.ts.map create mode 100644 dist/cjs/server/auth/handlers/metadata.js create mode 100644 dist/cjs/server/auth/handlers/metadata.js.map create mode 100644 dist/cjs/server/auth/handlers/register.d.ts create mode 100644 dist/cjs/server/auth/handlers/register.d.ts.map create mode 100644 dist/cjs/server/auth/handlers/register.js create mode 100644 dist/cjs/server/auth/handlers/register.js.map create mode 100644 dist/cjs/server/auth/handlers/revoke.d.ts create mode 100644 dist/cjs/server/auth/handlers/revoke.d.ts.map create mode 100644 dist/cjs/server/auth/handlers/revoke.js create mode 100644 dist/cjs/server/auth/handlers/revoke.js.map create mode 100644 dist/cjs/server/auth/handlers/token.d.ts create mode 100644 dist/cjs/server/auth/handlers/token.d.ts.map create mode 100644 dist/cjs/server/auth/handlers/token.js create mode 100644 dist/cjs/server/auth/handlers/token.js.map create mode 100644 dist/cjs/server/auth/middleware/allowedMethods.d.ts create mode 100644 dist/cjs/server/auth/middleware/allowedMethods.d.ts.map create mode 100644 dist/cjs/server/auth/middleware/allowedMethods.js create mode 100644 dist/cjs/server/auth/middleware/allowedMethods.js.map create mode 100644 dist/cjs/server/auth/middleware/bearerAuth.d.ts create mode 100644 dist/cjs/server/auth/middleware/bearerAuth.d.ts.map create mode 100644 dist/cjs/server/auth/middleware/bearerAuth.js create mode 100644 dist/cjs/server/auth/middleware/bearerAuth.js.map create mode 100644 dist/cjs/server/auth/middleware/clientAuth.d.ts create mode 100644 dist/cjs/server/auth/middleware/clientAuth.d.ts.map create mode 100644 dist/cjs/server/auth/middleware/clientAuth.js create mode 100644 dist/cjs/server/auth/middleware/clientAuth.js.map create mode 100644 dist/cjs/server/auth/provider.d.ts create mode 100644 dist/cjs/server/auth/provider.d.ts.map create mode 100644 dist/cjs/server/auth/provider.js create mode 100644 dist/cjs/server/auth/provider.js.map create mode 100644 dist/cjs/server/auth/providers/proxyProvider.d.ts create mode 100644 dist/cjs/server/auth/providers/proxyProvider.d.ts.map create mode 100644 dist/cjs/server/auth/providers/proxyProvider.js create mode 100644 dist/cjs/server/auth/providers/proxyProvider.js.map create mode 100644 dist/cjs/server/auth/router.d.ts create mode 100644 dist/cjs/server/auth/router.d.ts.map create mode 100644 dist/cjs/server/auth/router.js create mode 100644 dist/cjs/server/auth/router.js.map create mode 100644 dist/cjs/server/auth/types.d.ts create mode 100644 dist/cjs/server/auth/types.d.ts.map create mode 100644 dist/cjs/server/auth/types.js create mode 100644 dist/cjs/server/auth/types.js.map create mode 100644 dist/cjs/server/completable.d.ts create mode 100644 dist/cjs/server/completable.d.ts.map create mode 100644 dist/cjs/server/completable.js create mode 100644 dist/cjs/server/completable.js.map create mode 100644 dist/cjs/server/index.d.ts create mode 100644 dist/cjs/server/index.d.ts.map create mode 100644 dist/cjs/server/index.js create mode 100644 dist/cjs/server/index.js.map create mode 100644 dist/cjs/server/mcp.d.ts create mode 100644 dist/cjs/server/mcp.d.ts.map create mode 100644 dist/cjs/server/mcp.js create mode 100644 dist/cjs/server/mcp.js.map create mode 100644 dist/cjs/server/sse.d.ts create mode 100644 dist/cjs/server/sse.d.ts.map create mode 100644 dist/cjs/server/sse.js create mode 100644 dist/cjs/server/sse.js.map create mode 100644 dist/cjs/server/stdio.d.ts create mode 100644 dist/cjs/server/stdio.d.ts.map create mode 100644 dist/cjs/server/stdio.js create mode 100644 dist/cjs/server/stdio.js.map create mode 100644 dist/cjs/server/streamableHttp.d.ts create mode 100644 dist/cjs/server/streamableHttp.d.ts.map create mode 100644 dist/cjs/server/streamableHttp.js create mode 100644 dist/cjs/server/streamableHttp.js.map create mode 100644 dist/cjs/server/zod-compat.d.ts create mode 100644 dist/cjs/server/zod-compat.d.ts.map create mode 100644 dist/cjs/server/zod-compat.js create mode 100644 dist/cjs/server/zod-compat.js.map create mode 100644 dist/cjs/server/zod-json-schema-compat.d.ts create mode 100644 dist/cjs/server/zod-json-schema-compat.d.ts.map create mode 100644 dist/cjs/server/zod-json-schema-compat.js create mode 100644 dist/cjs/server/zod-json-schema-compat.js.map create mode 100644 dist/cjs/shared/auth-utils.d.ts create mode 100644 dist/cjs/shared/auth-utils.d.ts.map create mode 100644 dist/cjs/shared/auth-utils.js create mode 100644 dist/cjs/shared/auth-utils.js.map create mode 100644 dist/cjs/shared/auth.d.ts create mode 100644 dist/cjs/shared/auth.d.ts.map create mode 100644 dist/cjs/shared/auth.js create mode 100644 dist/cjs/shared/auth.js.map create mode 100644 dist/cjs/shared/metadataUtils.d.ts create mode 100644 dist/cjs/shared/metadataUtils.d.ts.map create mode 100644 dist/cjs/shared/metadataUtils.js create mode 100644 dist/cjs/shared/metadataUtils.js.map create mode 100644 dist/cjs/shared/protocol.d.ts create mode 100644 dist/cjs/shared/protocol.d.ts.map create mode 100644 dist/cjs/shared/protocol.js create mode 100644 dist/cjs/shared/protocol.js.map create mode 100644 dist/cjs/shared/stdio.d.ts create mode 100644 dist/cjs/shared/stdio.d.ts.map create mode 100644 dist/cjs/shared/stdio.js create mode 100644 dist/cjs/shared/stdio.js.map create mode 100644 dist/cjs/shared/toolNameValidation.d.ts create mode 100644 dist/cjs/shared/toolNameValidation.d.ts.map create mode 100644 dist/cjs/shared/toolNameValidation.js create mode 100644 dist/cjs/shared/toolNameValidation.js.map create mode 100644 dist/cjs/shared/transport.d.ts create mode 100644 dist/cjs/shared/transport.d.ts.map create mode 100644 dist/cjs/shared/transport.js create mode 100644 dist/cjs/shared/transport.js.map create mode 100644 dist/cjs/shared/uriTemplate.d.ts create mode 100644 dist/cjs/shared/uriTemplate.d.ts.map create mode 100644 dist/cjs/shared/uriTemplate.js create mode 100644 dist/cjs/shared/uriTemplate.js.map create mode 100644 dist/cjs/shared/zodTestMatrix.d.ts create mode 100644 dist/cjs/shared/zodTestMatrix.d.ts.map create mode 100644 dist/cjs/shared/zodTestMatrix.js create mode 100644 dist/cjs/shared/zodTestMatrix.js.map create mode 100644 dist/cjs/spec.types.d.ts create mode 100644 dist/cjs/spec.types.d.ts.map create mode 100644 dist/cjs/spec.types.js create mode 100644 dist/cjs/spec.types.js.map create mode 100644 dist/cjs/types.d.ts create mode 100644 dist/cjs/types.d.ts.map create mode 100644 dist/cjs/types.js create mode 100644 dist/cjs/types.js.map create mode 100644 dist/cjs/validation/ajv-provider.d.ts create mode 100644 dist/cjs/validation/ajv-provider.d.ts.map create mode 100644 dist/cjs/validation/ajv-provider.js create mode 100644 dist/cjs/validation/ajv-provider.js.map create mode 100644 dist/cjs/validation/cfworker-provider.d.ts create mode 100644 dist/cjs/validation/cfworker-provider.d.ts.map create mode 100644 dist/cjs/validation/cfworker-provider.js create mode 100644 dist/cjs/validation/cfworker-provider.js.map create mode 100644 dist/cjs/validation/index.d.ts create mode 100644 dist/cjs/validation/index.d.ts.map create mode 100644 dist/cjs/validation/index.js create mode 100644 dist/cjs/validation/index.js.map create mode 100644 dist/cjs/validation/types.d.ts create mode 100644 dist/cjs/validation/types.d.ts.map create mode 100644 dist/cjs/validation/types.js create mode 100644 dist/cjs/validation/types.js.map create mode 100644 dist/esm/client/auth.d.ts create mode 100644 dist/esm/client/auth.d.ts.map create mode 100644 dist/esm/client/auth.js create mode 100644 dist/esm/client/auth.js.map create mode 100644 dist/esm/client/index.d.ts create mode 100644 dist/esm/client/index.d.ts.map create mode 100644 dist/esm/client/index.js create mode 100644 dist/esm/client/index.js.map create mode 100644 dist/esm/client/middleware.d.ts create mode 100644 dist/esm/client/middleware.d.ts.map create mode 100644 dist/esm/client/middleware.js create mode 100644 dist/esm/client/middleware.js.map create mode 100644 dist/esm/client/sse.d.ts create mode 100644 dist/esm/client/sse.d.ts.map create mode 100644 dist/esm/client/sse.js create mode 100644 dist/esm/client/sse.js.map create mode 100644 dist/esm/client/stdio.d.ts create mode 100644 dist/esm/client/stdio.d.ts.map create mode 100644 dist/esm/client/stdio.js create mode 100644 dist/esm/client/stdio.js.map create mode 100644 dist/esm/client/streamableHttp.d.ts create mode 100644 dist/esm/client/streamableHttp.d.ts.map create mode 100644 dist/esm/client/streamableHttp.js create mode 100644 dist/esm/client/streamableHttp.js.map create mode 100644 dist/esm/client/websocket.d.ts create mode 100644 dist/esm/client/websocket.d.ts.map create mode 100644 dist/esm/client/websocket.js create mode 100644 dist/esm/client/websocket.js.map create mode 100644 dist/esm/examples/client/elicitationUrlExample.d.ts create mode 100644 dist/esm/examples/client/elicitationUrlExample.d.ts.map create mode 100644 dist/esm/examples/client/elicitationUrlExample.js create mode 100644 dist/esm/examples/client/elicitationUrlExample.js.map create mode 100644 dist/esm/examples/client/multipleClientsParallel.d.ts create mode 100644 dist/esm/examples/client/multipleClientsParallel.d.ts.map create mode 100644 dist/esm/examples/client/multipleClientsParallel.js create mode 100644 dist/esm/examples/client/multipleClientsParallel.js.map create mode 100644 dist/esm/examples/client/parallelToolCallsClient.d.ts create mode 100644 dist/esm/examples/client/parallelToolCallsClient.d.ts.map create mode 100644 dist/esm/examples/client/parallelToolCallsClient.js create mode 100644 dist/esm/examples/client/parallelToolCallsClient.js.map create mode 100644 dist/esm/examples/client/simpleOAuthClient.d.ts create mode 100644 dist/esm/examples/client/simpleOAuthClient.d.ts.map create mode 100644 dist/esm/examples/client/simpleOAuthClient.js create mode 100644 dist/esm/examples/client/simpleOAuthClient.js.map create mode 100644 dist/esm/examples/client/simpleOAuthClientProvider.d.ts create mode 100644 dist/esm/examples/client/simpleOAuthClientProvider.d.ts.map create mode 100644 dist/esm/examples/client/simpleOAuthClientProvider.js create mode 100644 dist/esm/examples/client/simpleOAuthClientProvider.js.map create mode 100644 dist/esm/examples/client/simpleStreamableHttp.d.ts create mode 100644 dist/esm/examples/client/simpleStreamableHttp.d.ts.map create mode 100644 dist/esm/examples/client/simpleStreamableHttp.js create mode 100644 dist/esm/examples/client/simpleStreamableHttp.js.map create mode 100644 dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts create mode 100644 dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts.map create mode 100644 dist/esm/examples/client/streamableHttpWithSseFallbackClient.js create mode 100644 dist/esm/examples/client/streamableHttpWithSseFallbackClient.js.map create mode 100644 dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts create mode 100644 dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts.map create mode 100644 dist/esm/examples/server/demoInMemoryOAuthProvider.js create mode 100644 dist/esm/examples/server/demoInMemoryOAuthProvider.js.map create mode 100644 dist/esm/examples/server/elicitationFormExample.d.ts create mode 100644 dist/esm/examples/server/elicitationFormExample.d.ts.map create mode 100644 dist/esm/examples/server/elicitationFormExample.js create mode 100644 dist/esm/examples/server/elicitationFormExample.js.map create mode 100644 dist/esm/examples/server/elicitationUrlExample.d.ts create mode 100644 dist/esm/examples/server/elicitationUrlExample.d.ts.map create mode 100644 dist/esm/examples/server/elicitationUrlExample.js create mode 100644 dist/esm/examples/server/elicitationUrlExample.js.map create mode 100644 dist/esm/examples/server/jsonResponseStreamableHttp.d.ts create mode 100644 dist/esm/examples/server/jsonResponseStreamableHttp.d.ts.map create mode 100644 dist/esm/examples/server/jsonResponseStreamableHttp.js create mode 100644 dist/esm/examples/server/jsonResponseStreamableHttp.js.map create mode 100644 dist/esm/examples/server/mcpServerOutputSchema.d.ts create mode 100644 dist/esm/examples/server/mcpServerOutputSchema.d.ts.map create mode 100644 dist/esm/examples/server/mcpServerOutputSchema.js create mode 100644 dist/esm/examples/server/mcpServerOutputSchema.js.map create mode 100644 dist/esm/examples/server/simpleSseServer.d.ts create mode 100644 dist/esm/examples/server/simpleSseServer.d.ts.map create mode 100644 dist/esm/examples/server/simpleSseServer.js create mode 100644 dist/esm/examples/server/simpleSseServer.js.map create mode 100644 dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts create mode 100644 dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts.map create mode 100644 dist/esm/examples/server/simpleStatelessStreamableHttp.js create mode 100644 dist/esm/examples/server/simpleStatelessStreamableHttp.js.map create mode 100644 dist/esm/examples/server/simpleStreamableHttp.d.ts create mode 100644 dist/esm/examples/server/simpleStreamableHttp.d.ts.map create mode 100644 dist/esm/examples/server/simpleStreamableHttp.js create mode 100644 dist/esm/examples/server/simpleStreamableHttp.js.map create mode 100644 dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts create mode 100644 dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map create mode 100644 dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js create mode 100644 dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js.map create mode 100644 dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts create mode 100644 dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map create mode 100644 dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js create mode 100644 dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js.map create mode 100644 dist/esm/examples/server/toolWithSampleServer.d.ts create mode 100644 dist/esm/examples/server/toolWithSampleServer.d.ts.map create mode 100644 dist/esm/examples/server/toolWithSampleServer.js create mode 100644 dist/esm/examples/server/toolWithSampleServer.js.map create mode 100644 dist/esm/examples/shared/inMemoryEventStore.d.ts create mode 100644 dist/esm/examples/shared/inMemoryEventStore.d.ts.map create mode 100644 dist/esm/examples/shared/inMemoryEventStore.js create mode 100644 dist/esm/examples/shared/inMemoryEventStore.js.map create mode 100644 dist/esm/inMemory.d.ts create mode 100644 dist/esm/inMemory.d.ts.map create mode 100644 dist/esm/inMemory.js create mode 100644 dist/esm/inMemory.js.map create mode 100644 dist/esm/package.json create mode 100644 dist/esm/server/auth/clients.d.ts create mode 100644 dist/esm/server/auth/clients.d.ts.map create mode 100644 dist/esm/server/auth/clients.js create mode 100644 dist/esm/server/auth/clients.js.map create mode 100644 dist/esm/server/auth/errors.d.ts create mode 100644 dist/esm/server/auth/errors.d.ts.map create mode 100644 dist/esm/server/auth/errors.js create mode 100644 dist/esm/server/auth/errors.js.map create mode 100644 dist/esm/server/auth/handlers/authorize.d.ts create mode 100644 dist/esm/server/auth/handlers/authorize.d.ts.map create mode 100644 dist/esm/server/auth/handlers/authorize.js create mode 100644 dist/esm/server/auth/handlers/authorize.js.map create mode 100644 dist/esm/server/auth/handlers/metadata.d.ts create mode 100644 dist/esm/server/auth/handlers/metadata.d.ts.map create mode 100644 dist/esm/server/auth/handlers/metadata.js create mode 100644 dist/esm/server/auth/handlers/metadata.js.map create mode 100644 dist/esm/server/auth/handlers/register.d.ts create mode 100644 dist/esm/server/auth/handlers/register.d.ts.map create mode 100644 dist/esm/server/auth/handlers/register.js create mode 100644 dist/esm/server/auth/handlers/register.js.map create mode 100644 dist/esm/server/auth/handlers/revoke.d.ts create mode 100644 dist/esm/server/auth/handlers/revoke.d.ts.map create mode 100644 dist/esm/server/auth/handlers/revoke.js create mode 100644 dist/esm/server/auth/handlers/revoke.js.map create mode 100644 dist/esm/server/auth/handlers/token.d.ts create mode 100644 dist/esm/server/auth/handlers/token.d.ts.map create mode 100644 dist/esm/server/auth/handlers/token.js create mode 100644 dist/esm/server/auth/handlers/token.js.map create mode 100644 dist/esm/server/auth/middleware/allowedMethods.d.ts create mode 100644 dist/esm/server/auth/middleware/allowedMethods.d.ts.map create mode 100644 dist/esm/server/auth/middleware/allowedMethods.js create mode 100644 dist/esm/server/auth/middleware/allowedMethods.js.map create mode 100644 dist/esm/server/auth/middleware/bearerAuth.d.ts create mode 100644 dist/esm/server/auth/middleware/bearerAuth.d.ts.map create mode 100644 dist/esm/server/auth/middleware/bearerAuth.js create mode 100644 dist/esm/server/auth/middleware/bearerAuth.js.map create mode 100644 dist/esm/server/auth/middleware/clientAuth.d.ts create mode 100644 dist/esm/server/auth/middleware/clientAuth.d.ts.map create mode 100644 dist/esm/server/auth/middleware/clientAuth.js create mode 100644 dist/esm/server/auth/middleware/clientAuth.js.map create mode 100644 dist/esm/server/auth/provider.d.ts create mode 100644 dist/esm/server/auth/provider.d.ts.map create mode 100644 dist/esm/server/auth/provider.js create mode 100644 dist/esm/server/auth/provider.js.map create mode 100644 dist/esm/server/auth/providers/proxyProvider.d.ts create mode 100644 dist/esm/server/auth/providers/proxyProvider.d.ts.map create mode 100644 dist/esm/server/auth/providers/proxyProvider.js create mode 100644 dist/esm/server/auth/providers/proxyProvider.js.map create mode 100644 dist/esm/server/auth/router.d.ts create mode 100644 dist/esm/server/auth/router.d.ts.map create mode 100644 dist/esm/server/auth/router.js create mode 100644 dist/esm/server/auth/router.js.map create mode 100644 dist/esm/server/auth/types.d.ts create mode 100644 dist/esm/server/auth/types.d.ts.map create mode 100644 dist/esm/server/auth/types.js create mode 100644 dist/esm/server/auth/types.js.map create mode 100644 dist/esm/server/completable.d.ts create mode 100644 dist/esm/server/completable.d.ts.map create mode 100644 dist/esm/server/completable.js create mode 100644 dist/esm/server/completable.js.map create mode 100644 dist/esm/server/index.d.ts create mode 100644 dist/esm/server/index.d.ts.map create mode 100644 dist/esm/server/index.js create mode 100644 dist/esm/server/index.js.map create mode 100644 dist/esm/server/mcp.d.ts create mode 100644 dist/esm/server/mcp.d.ts.map create mode 100644 dist/esm/server/mcp.js create mode 100644 dist/esm/server/mcp.js.map create mode 100644 dist/esm/server/sse.d.ts create mode 100644 dist/esm/server/sse.d.ts.map create mode 100644 dist/esm/server/sse.js create mode 100644 dist/esm/server/sse.js.map create mode 100644 dist/esm/server/stdio.d.ts create mode 100644 dist/esm/server/stdio.d.ts.map create mode 100644 dist/esm/server/stdio.js create mode 100644 dist/esm/server/stdio.js.map create mode 100644 dist/esm/server/streamableHttp.d.ts create mode 100644 dist/esm/server/streamableHttp.d.ts.map create mode 100644 dist/esm/server/streamableHttp.js create mode 100644 dist/esm/server/streamableHttp.js.map create mode 100644 dist/esm/server/zod-compat.d.ts create mode 100644 dist/esm/server/zod-compat.d.ts.map create mode 100644 dist/esm/server/zod-compat.js create mode 100644 dist/esm/server/zod-compat.js.map create mode 100644 dist/esm/server/zod-json-schema-compat.d.ts create mode 100644 dist/esm/server/zod-json-schema-compat.d.ts.map create mode 100644 dist/esm/server/zod-json-schema-compat.js create mode 100644 dist/esm/server/zod-json-schema-compat.js.map create mode 100644 dist/esm/shared/auth-utils.d.ts create mode 100644 dist/esm/shared/auth-utils.d.ts.map create mode 100644 dist/esm/shared/auth-utils.js create mode 100644 dist/esm/shared/auth-utils.js.map create mode 100644 dist/esm/shared/auth.d.ts create mode 100644 dist/esm/shared/auth.d.ts.map create mode 100644 dist/esm/shared/auth.js create mode 100644 dist/esm/shared/auth.js.map create mode 100644 dist/esm/shared/metadataUtils.d.ts create mode 100644 dist/esm/shared/metadataUtils.d.ts.map create mode 100644 dist/esm/shared/metadataUtils.js create mode 100644 dist/esm/shared/metadataUtils.js.map create mode 100644 dist/esm/shared/protocol.d.ts create mode 100644 dist/esm/shared/protocol.d.ts.map create mode 100644 dist/esm/shared/protocol.js create mode 100644 dist/esm/shared/protocol.js.map create mode 100644 dist/esm/shared/stdio.d.ts create mode 100644 dist/esm/shared/stdio.d.ts.map create mode 100644 dist/esm/shared/stdio.js create mode 100644 dist/esm/shared/stdio.js.map create mode 100644 dist/esm/shared/toolNameValidation.d.ts create mode 100644 dist/esm/shared/toolNameValidation.d.ts.map create mode 100644 dist/esm/shared/toolNameValidation.js create mode 100644 dist/esm/shared/toolNameValidation.js.map create mode 100644 dist/esm/shared/transport.d.ts create mode 100644 dist/esm/shared/transport.d.ts.map create mode 100644 dist/esm/shared/transport.js create mode 100644 dist/esm/shared/transport.js.map create mode 100644 dist/esm/shared/uriTemplate.d.ts create mode 100644 dist/esm/shared/uriTemplate.d.ts.map create mode 100644 dist/esm/shared/uriTemplate.js create mode 100644 dist/esm/shared/uriTemplate.js.map create mode 100644 dist/esm/shared/zodTestMatrix.d.ts create mode 100644 dist/esm/shared/zodTestMatrix.d.ts.map create mode 100644 dist/esm/shared/zodTestMatrix.js create mode 100644 dist/esm/shared/zodTestMatrix.js.map create mode 100644 dist/esm/spec.types.d.ts create mode 100644 dist/esm/spec.types.d.ts.map create mode 100644 dist/esm/spec.types.js create mode 100644 dist/esm/spec.types.js.map create mode 100644 dist/esm/types.d.ts create mode 100644 dist/esm/types.d.ts.map create mode 100644 dist/esm/types.js create mode 100644 dist/esm/types.js.map create mode 100644 dist/esm/validation/ajv-provider.d.ts create mode 100644 dist/esm/validation/ajv-provider.d.ts.map create mode 100644 dist/esm/validation/ajv-provider.js create mode 100644 dist/esm/validation/ajv-provider.js.map create mode 100644 dist/esm/validation/cfworker-provider.d.ts create mode 100644 dist/esm/validation/cfworker-provider.d.ts.map create mode 100644 dist/esm/validation/cfworker-provider.js create mode 100644 dist/esm/validation/cfworker-provider.js.map create mode 100644 dist/esm/validation/index.d.ts create mode 100644 dist/esm/validation/index.d.ts.map create mode 100644 dist/esm/validation/index.js create mode 100644 dist/esm/validation/index.js.map create mode 100644 dist/esm/validation/types.d.ts create mode 100644 dist/esm/validation/types.d.ts.map create mode 100644 dist/esm/validation/types.js create mode 100644 dist/esm/validation/types.js.map diff --git a/.gitignore b/.gitignore index a1b83bc4fa..397351de25 100644 --- a/.gitignore +++ b/.gitignore @@ -129,7 +129,9 @@ out .pnp.* .DS_Store -dist/ + +# Include dist for npm +# dist/ # IDE .idea/ diff --git a/dist/cjs/client/auth.d.ts b/dist/cjs/client/auth.d.ts new file mode 100644 index 0000000000..0bf7a645e4 --- /dev/null +++ b/dist/cjs/client/auth.d.ts @@ -0,0 +1,280 @@ +import { OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens, OAuthMetadata, OAuthClientInformationFull, OAuthProtectedResourceMetadata, AuthorizationServerMetadata } from '../shared/auth.js'; +import { OAuthError } from '../server/auth/errors.js'; +import { FetchLike } from '../shared/transport.js'; +/** + * Implements an end-to-end OAuth client to be used with one MCP server. + * + * This client relies upon a concept of an authorized "session," the exact + * meaning of which is application-defined. Tokens, authorization codes, and + * code verifiers should not cross different sessions. + */ +export interface OAuthClientProvider { + /** + * The URL to redirect the user agent to after authorization. + */ + get redirectUrl(): string | URL; + /** + * External URL the server should use to fetch client metadata document + */ + clientMetadataUrl?: string; + /** + * Metadata about this OAuth client. + */ + get clientMetadata(): OAuthClientMetadata; + /** + * Returns a OAuth2 state parameter. + */ + state?(): string | Promise; + /** + * Loads information about this OAuth client, as registered already with the + * server, or returns `undefined` if the client is not registered with the + * server. + */ + clientInformation(): OAuthClientInformationMixed | undefined | Promise; + /** + * If implemented, this permits the OAuth client to dynamically register with + * the server. Client information saved this way should later be read via + * `clientInformation()`. + * + * This method is not required to be implemented if client information is + * statically known (e.g., pre-registered). + */ + saveClientInformation?(clientInformation: OAuthClientInformationMixed): void | Promise; + /** + * Loads any existing OAuth tokens for the current session, or returns + * `undefined` if there are no saved tokens. + */ + tokens(): OAuthTokens | undefined | Promise; + /** + * Stores new OAuth tokens for the current session, after a successful + * authorization. + */ + saveTokens(tokens: OAuthTokens): void | Promise; + /** + * Invoked to redirect the user agent to the given URL to begin the authorization flow. + */ + redirectToAuthorization(authorizationUrl: URL): void | Promise; + /** + * Saves a PKCE code verifier for the current session, before redirecting to + * the authorization flow. + */ + saveCodeVerifier(codeVerifier: string): void | Promise; + /** + * Loads the PKCE code verifier for the current session, necessary to validate + * the authorization result. + */ + codeVerifier(): string | Promise; + /** + * Adds custom client authentication to OAuth token requests. + * + * This optional method allows implementations to customize how client credentials + * are included in token exchange and refresh requests. When provided, this method + * is called instead of the default authentication logic, giving full control over + * the authentication mechanism. + * + * Common use cases include: + * - Supporting authentication methods beyond the standard OAuth 2.0 methods + * - Adding custom headers for proprietary authentication schemes + * - Implementing client assertion-based authentication (e.g., JWT bearer tokens) + * + * @param headers - The request headers (can be modified to add authentication) + * @param params - The request body parameters (can be modified to add credentials) + * @param url - The token endpoint URL being called + * @param metadata - Optional OAuth metadata for the server, which may include supported authentication methods + */ + addClientAuthentication?(headers: Headers, params: URLSearchParams, url: string | URL, metadata?: AuthorizationServerMetadata): void | Promise; + /** + * If defined, overrides the selection and validation of the + * RFC 8707 Resource Indicator. If left undefined, default + * validation behavior will be used. + * + * Implementations must verify the returned resource matches the MCP server. + */ + validateResourceURL?(serverUrl: string | URL, resource?: string): Promise; + /** + * If implemented, provides a way for the client to invalidate (e.g. delete) the specified + * credentials, in the case where the server has indicated that they are no longer valid. + * This avoids requiring the user to intervene manually. + */ + invalidateCredentials?(scope: 'all' | 'client' | 'tokens' | 'verifier'): void | Promise; +} +export type AuthResult = 'AUTHORIZED' | 'REDIRECT'; +export declare class UnauthorizedError extends Error { + constructor(message?: string); +} +type ClientAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'none'; +/** + * Determines the best client authentication method to use based on server support and client configuration. + * + * Priority order (highest to lowest): + * 1. client_secret_basic (if client secret is available) + * 2. client_secret_post (if client secret is available) + * 3. none (for public clients) + * + * @param clientInformation - OAuth client information containing credentials + * @param supportedMethods - Authentication methods supported by the authorization server + * @returns The selected authentication method + */ +export declare function selectClientAuthMethod(clientInformation: OAuthClientInformationMixed, supportedMethods: string[]): ClientAuthMethod; +/** + * Parses an OAuth error response from a string or Response object. + * + * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec + * and an instance of the appropriate OAuthError subclass will be returned. + * If parsing fails, it falls back to a generic ServerError that includes + * the response status (if available) and original content. + * + * @param input - A Response object or string containing the error response + * @returns A Promise that resolves to an OAuthError instance + */ +export declare function parseErrorResponse(input: Response | string): Promise; +/** + * Orchestrates the full auth flow with a server. + * + * This can be used as a single entry point for all authorization functionality, + * instead of linking together the other lower-level functions in this module. + */ +export declare function auth(provider: OAuthClientProvider, options: { + serverUrl: string | URL; + authorizationCode?: string; + scope?: string; + resourceMetadataUrl?: URL; + fetchFn?: FetchLike; +}): Promise; +/** + * SEP-991: URL-based Client IDs + * Validate that the client_id is a valid URL with https scheme + */ +export declare function isHttpsUrl(value?: string): boolean; +export declare function selectResourceURL(serverUrl: string | URL, provider: OAuthClientProvider, resourceMetadata?: OAuthProtectedResourceMetadata): Promise; +/** + * Extract resource_metadata, scope, and error from WWW-Authenticate header. + */ +export declare function extractWWWAuthenticateParams(res: Response): { + resourceMetadataUrl?: URL; + scope?: string; + error?: string; +}; +/** + * Extract resource_metadata from response header. + * @deprecated Use `extractWWWAuthenticateParams` instead. + */ +export declare function extractResourceMetadataUrl(res: Response): URL | undefined; +/** + * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + */ +export declare function discoverOAuthProtectedResourceMetadata(serverUrl: string | URL, opts?: { + protocolVersion?: string; + resourceMetadataUrl?: string | URL; +}, fetchFn?: FetchLike): Promise; +/** + * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + * + * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`. + */ +export declare function discoverOAuthMetadata(issuer: string | URL, { authorizationServerUrl, protocolVersion }?: { + authorizationServerUrl?: string | URL; + protocolVersion?: string; +}, fetchFn?: FetchLike): Promise; +/** + * Builds a list of discovery URLs to try for authorization server metadata. + * URLs are returned in priority order: + * 1. OAuth metadata at the given URL + * 2. OIDC metadata endpoints at the given URL + */ +export declare function buildDiscoveryUrls(authorizationServerUrl: string | URL): { + url: URL; + type: 'oauth' | 'oidc'; +}[]; +/** + * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata + * and OpenID Connect Discovery 1.0 specifications. + * + * This function implements a fallback strategy for authorization server discovery: + * 1. Attempts RFC 8414 OAuth metadata discovery first + * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery + * + * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's + * protected resource metadata, or the MCP server's URL if the + * metadata was not found. + * @param options - Configuration options + * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch + * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION + * @returns Promise resolving to authorization server metadata, or undefined if discovery fails + */ +export declare function discoverAuthorizationServerMetadata(authorizationServerUrl: string | URL, { fetchFn, protocolVersion }?: { + fetchFn?: FetchLike; + protocolVersion?: string; +}): Promise; +/** + * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL. + */ +export declare function startAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, redirectUrl, scope, state, resource }: { + metadata?: AuthorizationServerMetadata; + clientInformation: OAuthClientInformationMixed; + redirectUrl: string | URL; + scope?: string; + state?: string; + resource?: URL; +}): Promise<{ + authorizationUrl: URL; + codeVerifier: string; +}>; +/** + * Exchanges an authorization code for an access token with the given server. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Falls back to appropriate defaults when server metadata is unavailable + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, auth code, etc. + * @returns Promise resolving to OAuth tokens + * @throws {Error} When token exchange fails or authentication is invalid + */ +export declare function exchangeAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }: { + metadata?: AuthorizationServerMetadata; + clientInformation: OAuthClientInformationMixed; + authorizationCode: string; + codeVerifier: string; + redirectUri: string | URL; + resource?: URL; + addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; + fetchFn?: FetchLike; +}): Promise; +/** + * Exchange a refresh token for an updated access token. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Preserves the original refresh token if a new one is not returned + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, refresh token, etc. + * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced) + * @throws {Error} When token refresh fails or authentication is invalid + */ +export declare function refreshAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }: { + metadata?: AuthorizationServerMetadata; + clientInformation: OAuthClientInformationMixed; + refreshToken: string; + resource?: URL; + addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; + fetchFn?: FetchLike; +}): Promise; +/** + * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. + */ +export declare function registerClient(authorizationServerUrl: string | URL, { metadata, clientMetadata, fetchFn }: { + metadata?: AuthorizationServerMetadata; + clientMetadata: OAuthClientMetadata; + fetchFn?: FetchLike; +}): Promise; +export {}; +//# sourceMappingURL=auth.d.ts.map \ No newline at end of file diff --git a/dist/cjs/client/auth.d.ts.map b/dist/cjs/client/auth.d.ts.map new file mode 100644 index 0000000000..ef03546f80 --- /dev/null +++ b/dist/cjs/client/auth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/client/auth.ts"],"names":[],"mappings":"AAEA,OAAO,EACH,mBAAmB,EAEnB,2BAA2B,EAC3B,WAAW,EACX,aAAa,EACb,0BAA0B,EAC1B,8BAA8B,EAE9B,2BAA2B,EAE9B,MAAM,mBAAmB,CAAC;AAQ3B,OAAO,EAKH,UAAU,EAGb,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;;;;;GAMG;AACH,MAAM,WAAW,mBAAmB;IAChC;;OAEG;IACH,IAAI,WAAW,IAAI,MAAM,GAAG,GAAG,CAAC;IAEhC;;OAEG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;OAEG;IACH,IAAI,cAAc,IAAI,mBAAmB,CAAC;IAE1C;;OAEG;IACH,KAAK,CAAC,IAAI,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAEnC;;;;OAIG;IACH,iBAAiB,IAAI,2BAA2B,GAAG,SAAS,GAAG,OAAO,CAAC,2BAA2B,GAAG,SAAS,CAAC,CAAC;IAEhH;;;;;;;OAOG;IACH,qBAAqB,CAAC,CAAC,iBAAiB,EAAE,2BAA2B,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE7F;;;OAGG;IACH,MAAM,IAAI,WAAW,GAAG,SAAS,GAAG,OAAO,CAAC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,SAAS,CAAC;CACvB,GACF,OAAO,CAAC,0BAA0B,CAAC,CA0BrC"} \ No newline at end of file diff --git a/dist/cjs/client/auth.js b/dist/cjs/client/auth.js new file mode 100644 index 0000000000..c929497b14 --- /dev/null +++ b/dist/cjs/client/auth.js @@ -0,0 +1,799 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UnauthorizedError = void 0; +exports.selectClientAuthMethod = selectClientAuthMethod; +exports.parseErrorResponse = parseErrorResponse; +exports.auth = auth; +exports.isHttpsUrl = isHttpsUrl; +exports.selectResourceURL = selectResourceURL; +exports.extractWWWAuthenticateParams = extractWWWAuthenticateParams; +exports.extractResourceMetadataUrl = extractResourceMetadataUrl; +exports.discoverOAuthProtectedResourceMetadata = discoverOAuthProtectedResourceMetadata; +exports.discoverOAuthMetadata = discoverOAuthMetadata; +exports.buildDiscoveryUrls = buildDiscoveryUrls; +exports.discoverAuthorizationServerMetadata = discoverAuthorizationServerMetadata; +exports.startAuthorization = startAuthorization; +exports.exchangeAuthorization = exchangeAuthorization; +exports.refreshAuthorization = refreshAuthorization; +exports.registerClient = registerClient; +const pkce_challenge_1 = __importDefault(require("pkce-challenge")); +const types_js_1 = require("../types.js"); +const auth_js_1 = require("../shared/auth.js"); +const auth_js_2 = require("../shared/auth.js"); +const auth_utils_js_1 = require("../shared/auth-utils.js"); +const errors_js_1 = require("../server/auth/errors.js"); +class UnauthorizedError extends Error { + constructor(message) { + super(message !== null && message !== void 0 ? message : 'Unauthorized'); + } +} +exports.UnauthorizedError = UnauthorizedError; +function isClientAuthMethod(method) { + return ['client_secret_basic', 'client_secret_post', 'none'].includes(method); +} +const AUTHORIZATION_CODE_RESPONSE_TYPE = 'code'; +const AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256'; +/** + * Determines the best client authentication method to use based on server support and client configuration. + * + * Priority order (highest to lowest): + * 1. client_secret_basic (if client secret is available) + * 2. client_secret_post (if client secret is available) + * 3. none (for public clients) + * + * @param clientInformation - OAuth client information containing credentials + * @param supportedMethods - Authentication methods supported by the authorization server + * @returns The selected authentication method + */ +function selectClientAuthMethod(clientInformation, supportedMethods) { + const hasClientSecret = clientInformation.client_secret !== undefined; + // If server doesn't specify supported methods, use RFC 6749 defaults + if (supportedMethods.length === 0) { + return hasClientSecret ? 'client_secret_post' : 'none'; + } + // Prefer the method returned by the server during client registration if valid and supported + if ('token_endpoint_auth_method' in clientInformation && + clientInformation.token_endpoint_auth_method && + isClientAuthMethod(clientInformation.token_endpoint_auth_method) && + supportedMethods.includes(clientInformation.token_endpoint_auth_method)) { + return clientInformation.token_endpoint_auth_method; + } + // Try methods in priority order (most secure first) + if (hasClientSecret && supportedMethods.includes('client_secret_basic')) { + return 'client_secret_basic'; + } + if (hasClientSecret && supportedMethods.includes('client_secret_post')) { + return 'client_secret_post'; + } + if (supportedMethods.includes('none')) { + return 'none'; + } + // Fallback: use what we have + return hasClientSecret ? 'client_secret_post' : 'none'; +} +/** + * Applies client authentication to the request based on the specified method. + * + * Implements OAuth 2.1 client authentication methods: + * - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1) + * - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1) + * - none: Public client authentication (RFC 6749 Section 2.1) + * + * @param method - The authentication method to use + * @param clientInformation - OAuth client information containing credentials + * @param headers - HTTP headers object to modify + * @param params - URL search parameters to modify + * @throws {Error} When required credentials are missing + */ +function applyClientAuthentication(method, clientInformation, headers, params) { + const { client_id, client_secret } = clientInformation; + switch (method) { + case 'client_secret_basic': + applyBasicAuth(client_id, client_secret, headers); + return; + case 'client_secret_post': + applyPostAuth(client_id, client_secret, params); + return; + case 'none': + applyPublicAuth(client_id, params); + return; + default: + throw new Error(`Unsupported client authentication method: ${method}`); + } +} +/** + * Applies HTTP Basic authentication (RFC 6749 Section 2.3.1) + */ +function applyBasicAuth(clientId, clientSecret, headers) { + if (!clientSecret) { + throw new Error('client_secret_basic authentication requires a client_secret'); + } + const credentials = btoa(`${clientId}:${clientSecret}`); + headers.set('Authorization', `Basic ${credentials}`); +} +/** + * Applies POST body authentication (RFC 6749 Section 2.3.1) + */ +function applyPostAuth(clientId, clientSecret, params) { + params.set('client_id', clientId); + if (clientSecret) { + params.set('client_secret', clientSecret); + } +} +/** + * Applies public client authentication (RFC 6749 Section 2.1) + */ +function applyPublicAuth(clientId, params) { + params.set('client_id', clientId); +} +/** + * Parses an OAuth error response from a string or Response object. + * + * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec + * and an instance of the appropriate OAuthError subclass will be returned. + * If parsing fails, it falls back to a generic ServerError that includes + * the response status (if available) and original content. + * + * @param input - A Response object or string containing the error response + * @returns A Promise that resolves to an OAuthError instance + */ +async function parseErrorResponse(input) { + const statusCode = input instanceof Response ? input.status : undefined; + const body = input instanceof Response ? await input.text() : input; + try { + const result = auth_js_1.OAuthErrorResponseSchema.parse(JSON.parse(body)); + const { error, error_description, error_uri } = result; + const errorClass = errors_js_1.OAUTH_ERRORS[error] || errors_js_1.ServerError; + return new errorClass(error_description || '', error_uri); + } + catch (error) { + // Not a valid OAuth error response, but try to inform the user of the raw data anyway + const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}Invalid OAuth error response: ${error}. Raw body: ${body}`; + return new errors_js_1.ServerError(errorMessage); + } +} +/** + * Orchestrates the full auth flow with a server. + * + * This can be used as a single entry point for all authorization functionality, + * instead of linking together the other lower-level functions in this module. + */ +async function auth(provider, options) { + var _a, _b; + try { + return await authInternal(provider, options); + } + catch (error) { + // Handle recoverable error types by invalidating credentials and retrying + if (error instanceof errors_js_1.InvalidClientError || error instanceof errors_js_1.UnauthorizedClientError) { + await ((_a = provider.invalidateCredentials) === null || _a === void 0 ? void 0 : _a.call(provider, 'all')); + return await authInternal(provider, options); + } + else if (error instanceof errors_js_1.InvalidGrantError) { + await ((_b = provider.invalidateCredentials) === null || _b === void 0 ? void 0 : _b.call(provider, 'tokens')); + return await authInternal(provider, options); + } + // Throw otherwise + throw error; + } +} +async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) { + var _a, _b; + let resourceMetadata; + let authorizationServerUrl; + try { + resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn); + if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { + authorizationServerUrl = resourceMetadata.authorization_servers[0]; + } + } + catch (_c) { + // Ignore errors and fall back to /.well-known/oauth-authorization-server + } + /** + * If we don't get a valid authorization server metadata from protected resource metadata, + * fallback to the legacy MCP spec's implementation (version 2025-03-26): MCP server base URL acts as the Authorization server. + */ + if (!authorizationServerUrl) { + authorizationServerUrl = new URL('/', serverUrl); + } + const resource = await selectResourceURL(serverUrl, provider, resourceMetadata); + const metadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { + fetchFn + }); + // Handle client registration if needed + let clientInformation = await Promise.resolve(provider.clientInformation()); + if (!clientInformation) { + if (authorizationCode !== undefined) { + throw new Error('Existing OAuth client information is required when exchanging an authorization code'); + } + const supportsUrlBasedClientId = (metadata === null || metadata === void 0 ? void 0 : metadata.client_id_metadata_document_supported) === true; + const clientMetadataUrl = provider.clientMetadataUrl; + if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) { + throw new errors_js_1.InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`); + } + const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl; + if (shouldUseUrlBasedClientId) { + // SEP-991: URL-based Client IDs + clientInformation = { + client_id: clientMetadataUrl + }; + await ((_a = provider.saveClientInformation) === null || _a === void 0 ? void 0 : _a.call(provider, clientInformation)); + } + else { + // Fallback to dynamic registration + if (!provider.saveClientInformation) { + throw new Error('OAuth client information must be saveable for dynamic registration'); + } + const fullInformation = await registerClient(authorizationServerUrl, { + metadata, + clientMetadata: provider.clientMetadata, + fetchFn + }); + await provider.saveClientInformation(fullInformation); + clientInformation = fullInformation; + } + } + // Exchange authorization code for tokens + if (authorizationCode !== undefined) { + const codeVerifier = await provider.codeVerifier(); + const tokens = await exchangeAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + authorizationCode, + codeVerifier, + redirectUri: provider.redirectUrl, + resource, + addClientAuthentication: provider.addClientAuthentication, + fetchFn: fetchFn + }); + await provider.saveTokens(tokens); + return 'AUTHORIZED'; + } + const tokens = await provider.tokens(); + // Handle token refresh or new authorization + if (tokens === null || tokens === void 0 ? void 0 : tokens.refresh_token) { + try { + // Attempt to refresh the token + const newTokens = await refreshAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + refreshToken: tokens.refresh_token, + resource, + addClientAuthentication: provider.addClientAuthentication, + fetchFn + }); + await provider.saveTokens(newTokens); + return 'AUTHORIZED'; + } + catch (error) { + // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry. + if (!(error instanceof errors_js_1.OAuthError) || error instanceof errors_js_1.ServerError) { + // Could not refresh OAuth tokens + } + else { + // Refresh failed for another reason, re-throw + throw error; + } + } + } + const state = provider.state ? await provider.state() : undefined; + // Start new authorization flow + const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + state, + redirectUrl: provider.redirectUrl, + scope: scope || ((_b = resourceMetadata === null || resourceMetadata === void 0 ? void 0 : resourceMetadata.scopes_supported) === null || _b === void 0 ? void 0 : _b.join(' ')) || provider.clientMetadata.scope, + resource + }); + await provider.saveCodeVerifier(codeVerifier); + await provider.redirectToAuthorization(authorizationUrl); + return 'REDIRECT'; +} +/** + * SEP-991: URL-based Client IDs + * Validate that the client_id is a valid URL with https scheme + */ +function isHttpsUrl(value) { + if (!value) + return false; + try { + const url = new URL(value); + return url.protocol === 'https:' && url.pathname !== '/'; + } + catch (_a) { + return false; + } +} +async function selectResourceURL(serverUrl, provider, resourceMetadata) { + const defaultResource = (0, auth_utils_js_1.resourceUrlFromServerUrl)(serverUrl); + // If provider has custom validation, delegate to it + if (provider.validateResourceURL) { + return await provider.validateResourceURL(defaultResource, resourceMetadata === null || resourceMetadata === void 0 ? void 0 : resourceMetadata.resource); + } + // Only include resource parameter when Protected Resource Metadata is present + if (!resourceMetadata) { + return undefined; + } + // Validate that the metadata's resource is compatible with our request + if (!(0, auth_utils_js_1.checkResourceAllowed)({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) { + throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`); + } + // Prefer the resource from metadata since it's what the server is telling us to request + return new URL(resourceMetadata.resource); +} +/** + * Extract resource_metadata, scope, and error from WWW-Authenticate header. + */ +function extractWWWAuthenticateParams(res) { + const authenticateHeader = res.headers.get('WWW-Authenticate'); + if (!authenticateHeader) { + return {}; + } + const [type, scheme] = authenticateHeader.split(' '); + if (type.toLowerCase() !== 'bearer' || !scheme) { + return {}; + } + const resourceMetadataMatch = extractFieldFromWwwAuth(res, 'resource_metadata') || undefined; + let resourceMetadataUrl; + if (resourceMetadataMatch) { + try { + resourceMetadataUrl = new URL(resourceMetadataMatch); + } + catch (_a) { + // Ignore invalid URL + } + } + const scope = extractFieldFromWwwAuth(res, 'scope') || undefined; + const error = extractFieldFromWwwAuth(res, 'error') || undefined; + return { + resourceMetadataUrl, + scope, + error + }; +} +/** + * Extracts a specific field's value from the WWW-Authenticate header string. + * + * @param response The HTTP response object containing the headers. + * @param fieldName The name of the field to extract (e.g., "realm", "nonce"). + * @returns The field value + */ +function extractFieldFromWwwAuth(response, fieldName) { + const wwwAuthHeader = response.headers.get('WWW-Authenticate'); + if (!wwwAuthHeader) { + return null; + } + const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`); + const match = wwwAuthHeader.match(pattern); + if (match) { + // Pattern matches: field_name="value" or field_name=value (unquoted) + return match[1] || match[2]; + } + return null; +} +/** + * Extract resource_metadata from response header. + * @deprecated Use `extractWWWAuthenticateParams` instead. + */ +function extractResourceMetadataUrl(res) { + const authenticateHeader = res.headers.get('WWW-Authenticate'); + if (!authenticateHeader) { + return undefined; + } + const [type, scheme] = authenticateHeader.split(' '); + if (type.toLowerCase() !== 'bearer' || !scheme) { + return undefined; + } + const regex = /resource_metadata="([^"]*)"/; + const match = regex.exec(authenticateHeader); + if (!match) { + return undefined; + } + try { + return new URL(match[1]); + } + catch (_a) { + return undefined; + } +} +/** + * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + */ +async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) { + const response = await discoverMetadataWithFallback(serverUrl, 'oauth-protected-resource', fetchFn, { + protocolVersion: opts === null || opts === void 0 ? void 0 : opts.protocolVersion, + metadataUrl: opts === null || opts === void 0 ? void 0 : opts.resourceMetadataUrl + }); + if (!response || response.status === 404) { + throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`); + } + if (!response.ok) { + throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`); + } + return auth_js_2.OAuthProtectedResourceMetadataSchema.parse(await response.json()); +} +/** + * Helper function to handle fetch with CORS retry logic + */ +async function fetchWithCorsRetry(url, headers, fetchFn = fetch) { + try { + return await fetchFn(url, { headers }); + } + catch (error) { + if (error instanceof TypeError) { + if (headers) { + // CORS errors come back as TypeError, retry without headers + return fetchWithCorsRetry(url, undefined, fetchFn); + } + else { + // We're getting CORS errors on retry too, return undefined + return undefined; + } + } + throw error; + } +} +/** + * Constructs the well-known path for auth-related metadata discovery + */ +function buildWellKnownPath(wellKnownPrefix, pathname = '', options = {}) { + // Strip trailing slash from pathname to avoid double slashes + if (pathname.endsWith('/')) { + pathname = pathname.slice(0, -1); + } + return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`; +} +/** + * Tries to discover OAuth metadata at a specific URL + */ +async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) { + const headers = { + 'MCP-Protocol-Version': protocolVersion + }; + return await fetchWithCorsRetry(url, headers, fetchFn); +} +/** + * Determines if fallback to root discovery should be attempted + */ +function shouldAttemptFallback(response, pathname) { + return !response || (response.status >= 400 && response.status < 500 && pathname !== '/'); +} +/** + * Generic function for discovering OAuth metadata with fallback support + */ +async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) { + var _a, _b; + const issuer = new URL(serverUrl); + const protocolVersion = (_a = opts === null || opts === void 0 ? void 0 : opts.protocolVersion) !== null && _a !== void 0 ? _a : types_js_1.LATEST_PROTOCOL_VERSION; + let url; + if (opts === null || opts === void 0 ? void 0 : opts.metadataUrl) { + url = new URL(opts.metadataUrl); + } + else { + // Try path-aware discovery first + const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname); + url = new URL(wellKnownPath, (_b = opts === null || opts === void 0 ? void 0 : opts.metadataServerUrl) !== null && _b !== void 0 ? _b : issuer); + url.search = issuer.search; + } + let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn); + // If path-aware discovery fails with 404 and we're not already at root, try fallback to root discovery + if (!(opts === null || opts === void 0 ? void 0 : opts.metadataUrl) && shouldAttemptFallback(response, issuer.pathname)) { + const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer); + response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn); + } + return response; +} +/** + * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + * + * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`. + */ +async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) { + if (typeof issuer === 'string') { + issuer = new URL(issuer); + } + if (!authorizationServerUrl) { + authorizationServerUrl = issuer; + } + if (typeof authorizationServerUrl === 'string') { + authorizationServerUrl = new URL(authorizationServerUrl); + } + protocolVersion !== null && protocolVersion !== void 0 ? protocolVersion : (protocolVersion = types_js_1.LATEST_PROTOCOL_VERSION); + const response = await discoverMetadataWithFallback(authorizationServerUrl, 'oauth-authorization-server', fetchFn, { + protocolVersion, + metadataServerUrl: authorizationServerUrl + }); + if (!response || response.status === 404) { + return undefined; + } + if (!response.ok) { + throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`); + } + return auth_js_2.OAuthMetadataSchema.parse(await response.json()); +} +/** + * Builds a list of discovery URLs to try for authorization server metadata. + * URLs are returned in priority order: + * 1. OAuth metadata at the given URL + * 2. OIDC metadata endpoints at the given URL + */ +function buildDiscoveryUrls(authorizationServerUrl) { + const url = typeof authorizationServerUrl === 'string' ? new URL(authorizationServerUrl) : authorizationServerUrl; + const hasPath = url.pathname !== '/'; + const urlsToTry = []; + if (!hasPath) { + // Root path: https://example.com/.well-known/oauth-authorization-server + urlsToTry.push({ + url: new URL('/.well-known/oauth-authorization-server', url.origin), + type: 'oauth' + }); + // OIDC: https://example.com/.well-known/openid-configuration + urlsToTry.push({ + url: new URL(`/.well-known/openid-configuration`, url.origin), + type: 'oidc' + }); + return urlsToTry; + } + // Strip trailing slash from pathname to avoid double slashes + let pathname = url.pathname; + if (pathname.endsWith('/')) { + pathname = pathname.slice(0, -1); + } + // 1. OAuth metadata at the given URL + // Insert well-known before the path: https://example.com/.well-known/oauth-authorization-server/tenant1 + urlsToTry.push({ + url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin), + type: 'oauth' + }); + // 2. OIDC metadata endpoints + // RFC 8414 style: Insert /.well-known/openid-configuration before the path + urlsToTry.push({ + url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin), + type: 'oidc' + }); + // OIDC Discovery 1.0 style: Append /.well-known/openid-configuration after the path + urlsToTry.push({ + url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin), + type: 'oidc' + }); + return urlsToTry; +} +/** + * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata + * and OpenID Connect Discovery 1.0 specifications. + * + * This function implements a fallback strategy for authorization server discovery: + * 1. Attempts RFC 8414 OAuth metadata discovery first + * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery + * + * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's + * protected resource metadata, or the MCP server's URL if the + * metadata was not found. + * @param options - Configuration options + * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch + * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION + * @returns Promise resolving to authorization server metadata, or undefined if discovery fails + */ +async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = types_js_1.LATEST_PROTOCOL_VERSION } = {}) { + const headers = { + 'MCP-Protocol-Version': protocolVersion, + Accept: 'application/json' + }; + // Get the list of URLs to try + const urlsToTry = buildDiscoveryUrls(authorizationServerUrl); + // Try each URL in order + for (const { url: endpointUrl, type } of urlsToTry) { + const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn); + if (!response) { + /** + * CORS error occurred - don't throw as the endpoint may not allow CORS, + * continue trying other possible endpoints + */ + continue; + } + if (!response.ok) { + // Continue looking for any 4xx response code. + if (response.status >= 400 && response.status < 500) { + continue; // Try next URL + } + throw new Error(`HTTP ${response.status} trying to load ${type === 'oauth' ? 'OAuth' : 'OpenID provider'} metadata from ${endpointUrl}`); + } + // Parse and validate based on type + if (type === 'oauth') { + return auth_js_2.OAuthMetadataSchema.parse(await response.json()); + } + else { + return auth_js_1.OpenIdProviderDiscoveryMetadataSchema.parse(await response.json()); + } + } + return undefined; +} +/** + * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL. + */ +async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) { + let authorizationUrl; + if (metadata) { + authorizationUrl = new URL(metadata.authorization_endpoint); + if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) { + throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`); + } + if (metadata.code_challenge_methods_supported && + !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) { + throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`); + } + } + else { + authorizationUrl = new URL('/authorize', authorizationServerUrl); + } + // Generate PKCE challenge + const challenge = await (0, pkce_challenge_1.default)(); + const codeVerifier = challenge.code_verifier; + const codeChallenge = challenge.code_challenge; + authorizationUrl.searchParams.set('response_type', AUTHORIZATION_CODE_RESPONSE_TYPE); + authorizationUrl.searchParams.set('client_id', clientInformation.client_id); + authorizationUrl.searchParams.set('code_challenge', codeChallenge); + authorizationUrl.searchParams.set('code_challenge_method', AUTHORIZATION_CODE_CHALLENGE_METHOD); + authorizationUrl.searchParams.set('redirect_uri', String(redirectUrl)); + if (state) { + authorizationUrl.searchParams.set('state', state); + } + if (scope) { + authorizationUrl.searchParams.set('scope', scope); + } + if (scope === null || scope === void 0 ? void 0 : scope.includes('offline_access')) { + // if the request includes the OIDC-only "offline_access" scope, + // we need to set the prompt to "consent" to ensure the user is prompted to grant offline access + // https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess + authorizationUrl.searchParams.append('prompt', 'consent'); + } + if (resource) { + authorizationUrl.searchParams.set('resource', resource.href); + } + return { authorizationUrl, codeVerifier }; +} +/** + * Exchanges an authorization code for an access token with the given server. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Falls back to appropriate defaults when server metadata is unavailable + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, auth code, etc. + * @returns Promise resolving to OAuth tokens + * @throws {Error} When token exchange fails or authentication is invalid + */ +async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) { + var _a; + const grantType = 'authorization_code'; + const tokenUrl = (metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL('/token', authorizationServerUrl); + if ((metadata === null || metadata === void 0 ? void 0 : metadata.grant_types_supported) && !metadata.grant_types_supported.includes(grantType)) { + throw new Error(`Incompatible auth server: does not support grant type ${grantType}`); + } + // Exchange code for tokens + const headers = new Headers({ + 'Content-Type': 'application/x-www-form-urlencoded', + Accept: 'application/json' + }); + const params = new URLSearchParams({ + grant_type: grantType, + code: authorizationCode, + code_verifier: codeVerifier, + redirect_uri: String(redirectUri) + }); + if (addClientAuthentication) { + addClientAuthentication(headers, params, authorizationServerUrl, metadata); + } + else { + // Determine and apply client authentication method + const supportedMethods = (_a = metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint_auth_methods_supported) !== null && _a !== void 0 ? _a : []; + const authMethod = selectClientAuthMethod(clientInformation, supportedMethods); + applyClientAuthentication(authMethod, clientInformation, headers, params); + } + if (resource) { + params.set('resource', resource.href); + } + const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, { + method: 'POST', + headers, + body: params + }); + if (!response.ok) { + throw await parseErrorResponse(response); + } + return auth_js_2.OAuthTokensSchema.parse(await response.json()); +} +/** + * Exchange a refresh token for an updated access token. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Preserves the original refresh token if a new one is not returned + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, refresh token, etc. + * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced) + * @throws {Error} When token refresh fails or authentication is invalid + */ +async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) { + var _a; + const grantType = 'refresh_token'; + let tokenUrl; + if (metadata) { + tokenUrl = new URL(metadata.token_endpoint); + if (metadata.grant_types_supported && !metadata.grant_types_supported.includes(grantType)) { + throw new Error(`Incompatible auth server: does not support grant type ${grantType}`); + } + } + else { + tokenUrl = new URL('/token', authorizationServerUrl); + } + // Exchange refresh token + const headers = new Headers({ + 'Content-Type': 'application/x-www-form-urlencoded' + }); + const params = new URLSearchParams({ + grant_type: grantType, + refresh_token: refreshToken + }); + if (addClientAuthentication) { + addClientAuthentication(headers, params, authorizationServerUrl, metadata); + } + else { + // Determine and apply client authentication method + const supportedMethods = (_a = metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint_auth_methods_supported) !== null && _a !== void 0 ? _a : []; + const authMethod = selectClientAuthMethod(clientInformation, supportedMethods); + applyClientAuthentication(authMethod, clientInformation, headers, params); + } + if (resource) { + params.set('resource', resource.href); + } + const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, { + method: 'POST', + headers, + body: params + }); + if (!response.ok) { + throw await parseErrorResponse(response); + } + return auth_js_2.OAuthTokensSchema.parse({ refresh_token: refreshToken, ...(await response.json()) }); +} +/** + * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. + */ +async function registerClient(authorizationServerUrl, { metadata, clientMetadata, fetchFn }) { + let registrationUrl; + if (metadata) { + if (!metadata.registration_endpoint) { + throw new Error('Incompatible auth server: does not support dynamic client registration'); + } + registrationUrl = new URL(metadata.registration_endpoint); + } + else { + registrationUrl = new URL('/register', authorizationServerUrl); + } + const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(registrationUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(clientMetadata) + }); + if (!response.ok) { + throw await parseErrorResponse(response); + } + return auth_js_2.OAuthClientInformationFullSchema.parse(await response.json()); +} +//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/dist/cjs/client/auth.js.map b/dist/cjs/client/auth.js.map new file mode 100644 index 0000000000..8d17a404c8 --- /dev/null +++ b/dist/cjs/client/auth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/client/auth.ts"],"names":[],"mappings":";;;;;;AAiLA,wDAi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,sBAAsB,CAAC,CAAC;IACnE,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,KAAK,CAAC,CAAC,eAAe,EAAE;QACvD,MAAM,EAAE,MAAM;QACd,OAAO,EAAE;YACL,cAAc,EAAE,kBAAkB;SACrC;QACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC;KACvC,CAAC,CAAC;IAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACf,MAAM,MAAM,kBAAkB,CAAC,QAAQ,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,0CAAgC,CAAC,KAAK,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;AACzE,CAAC"} \ No newline at end of file diff --git a/dist/cjs/client/index.d.ts b/dist/cjs/client/index.d.ts new file mode 100644 index 0000000000..03148dd89b --- /dev/null +++ b/dist/cjs/client/index.d.ts @@ -0,0 +1,379 @@ +import { Protocol, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; +import type { Transport } from '../shared/transport.js'; +import { type CallToolRequest, CallToolResultSchema, type ClientCapabilities, type ClientNotification, type ClientRequest, type ClientResult, type CompatibilityCallToolResultSchema, type CompleteRequest, type GetPromptRequest, type Implementation, type ListPromptsRequest, type ListResourcesRequest, type ListResourceTemplatesRequest, type ListToolsRequest, type LoggingLevel, type Notification, type ReadResourceRequest, type Request, type Result, type ServerCapabilities, type SubscribeRequest, type UnsubscribeRequest } from '../types.js'; +import type { jsonSchemaValidator } from '../validation/types.js'; +import { AnyObjectSchema, SchemaOutput } from '../server/zod-compat.js'; +import type { RequestHandlerExtra } from '../shared/protocol.js'; +/** + * Determines which elicitation modes are supported based on declared client capabilities. + * + * According to the spec: + * - An empty elicitation capability object defaults to form mode support (backwards compatibility) + * - URL mode is only supported if explicitly declared + * + * @param capabilities - The client's elicitation capabilities + * @returns An object indicating which modes are supported + */ +export declare function getSupportedElicitationModes(capabilities: ClientCapabilities['elicitation']): { + supportsFormMode: boolean; + supportsUrlMode: boolean; +}; +export type ClientOptions = ProtocolOptions & { + /** + * Capabilities to advertise as being supported by this client. + */ + capabilities?: ClientCapabilities; + /** + * JSON Schema validator for tool output validation. + * + * The validator is used to validate structured content returned by tools + * against their declared output schemas. + * + * @default AjvJsonSchemaValidator + * + * @example + * ```typescript + * // ajv + * const client = new Client( + * { name: 'my-client', version: '1.0.0' }, + * { + * capabilities: {}, + * jsonSchemaValidator: new AjvJsonSchemaValidator() + * } + * ); + * + * // @cfworker/json-schema + * const client = new Client( + * { name: 'my-client', version: '1.0.0' }, + * { + * capabilities: {}, + * jsonSchemaValidator: new CfWorkerJsonSchemaValidator() + * } + * ); + * ``` + */ + jsonSchemaValidator?: jsonSchemaValidator; +}; +/** + * An MCP client on top of a pluggable transport. + * + * The client will automatically begin the initialization flow with the server when connect() is called. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed client + * const client = new Client({ + * name: "CustomClient", + * version: "1.0.0" + * }) + * ``` + */ +export declare class Client extends Protocol { + private _clientInfo; + private _serverCapabilities?; + private _serverVersion?; + private _capabilities; + private _instructions?; + private _jsonSchemaValidator; + private _cachedToolOutputValidators; + /** + * Initializes this client with the given name and version information. + */ + constructor(_clientInfo: Implementation, options?: ClientOptions); + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities: ClientCapabilities): void; + /** + * Override request handler registration to enforce client-side validation for elicitation. + */ + setRequestHandler(requestSchema: T, handler: (request: SchemaOutput, extra: RequestHandlerExtra) => ClientResult | ResultT | Promise): void; + protected assertCapability(capability: keyof ServerCapabilities, method: string): void; + connect(transport: Transport, options?: RequestOptions): Promise; + /** + * After initialization has completed, this will be populated with the server's reported capabilities. + */ + getServerCapabilities(): ServerCapabilities | undefined; + /** + * After initialization has completed, this will be populated with information about the server's name and version. + */ + getServerVersion(): Implementation | undefined; + /** + * After initialization has completed, this may be populated with information about the server's instructions. + */ + getInstructions(): string | undefined; + protected assertCapabilityForMethod(method: RequestT['method']): void; + protected assertNotificationCapability(method: NotificationT['method']): void; + protected assertRequestHandlerCapability(method: string): void; + ping(options?: RequestOptions): Promise<{ + _meta?: Record | undefined; + }>; + complete(params: CompleteRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + completion: { + [x: string]: unknown; + values: string[]; + total?: number | undefined; + hasMore?: boolean | undefined; + }; + _meta?: Record | undefined; + }>; + setLoggingLevel(level: LoggingLevel, options?: RequestOptions): Promise<{ + _meta?: Record | undefined; + }>; + getPrompt(params: GetPromptRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + messages: { + role: "user" | "assistant"; + content: { + type: "text"; + text: string; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "resource"; + resource: { + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + }; + _meta?: Record | undefined; + } | { + uri: string; + name: string; + type: "resource_link"; + description?: string | undefined; + mimeType?: string | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + }; + }[]; + _meta?: Record | undefined; + description?: string | undefined; + }>; + listPrompts(params?: ListPromptsRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + prompts: { + name: string; + description?: string | undefined; + arguments?: { + name: string; + description?: string | undefined; + required?: boolean | undefined; + }[] | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: Record | undefined; + nextCursor?: string | undefined; + }>; + listResources(params?: ListResourcesRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + resources: { + uri: string; + name: string; + description?: string | undefined; + mimeType?: string | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: Record | undefined; + nextCursor?: string | undefined; + }>; + listResourceTemplates(params?: ListResourceTemplatesRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + resourceTemplates: { + uriTemplate: string; + name: string; + description?: string | undefined; + mimeType?: string | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: Record | undefined; + nextCursor?: string | undefined; + }>; + readResource(params: ReadResourceRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + contents: ({ + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + })[]; + _meta?: Record | undefined; + }>; + subscribeResource(params: SubscribeRequest['params'], options?: RequestOptions): Promise<{ + _meta?: Record | undefined; + }>; + unsubscribeResource(params: UnsubscribeRequest['params'], options?: RequestOptions): Promise<{ + _meta?: Record | undefined; + }>; + callTool(params: CallToolRequest['params'], resultSchema?: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options?: RequestOptions): Promise<{ + [x: string]: unknown; + content: ({ + type: "text"; + text: string; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "resource"; + resource: { + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + }; + _meta?: Record | undefined; + } | { + uri: string; + name: string; + type: "resource_link"; + description?: string | undefined; + mimeType?: string | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + })[]; + _meta?: Record | undefined; + structuredContent?: Record | undefined; + isError?: boolean | undefined; + } | { + [x: string]: unknown; + toolResult: unknown; + _meta?: Record | undefined; + }>; + /** + * Cache validators for tool output schemas. + * Called after listTools() to pre-compile validators for better performance. + */ + private cacheToolOutputSchemas; + /** + * Get cached validator for a tool + */ + private getToolOutputValidator; + listTools(params?: ListToolsRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + tools: { + inputSchema: { + [x: string]: unknown; + type: "object"; + properties?: Record | undefined; + required?: string[] | undefined; + }; + name: string; + description?: string | undefined; + outputSchema?: { + [x: string]: unknown; + type: "object"; + properties?: Record | undefined; + required?: string[] | undefined; + } | undefined; + annotations?: { + title?: string | undefined; + readOnlyHint?: boolean | undefined; + destructiveHint?: boolean | undefined; + idempotentHint?: boolean | undefined; + openWorldHint?: boolean | undefined; + } | undefined; + securitySchemes?: ({ + type: "noauth"; + } | { + type: "oauth2"; + scopes?: string[] | undefined; + })[] | undefined; + _meta?: Record | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: Record | undefined; + nextCursor?: string | undefined; + }>; + sendRootsListChanged(): Promise; +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/cjs/client/index.d.ts.map b/dist/cjs/client/index.d.ts.map new file mode 100644 index 0000000000..c19d4ef588 --- /dev/null +++ b/dist/cjs/client/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","s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AAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;IAIlF,QAAQ,CACV,MAAM,EAAE,eAAe,CAAC,QAAQ,CAAC,EACjC,YAAY,GAAE,OAAO,oBAAoB,GAAG,OAAO,iCAAwD,EAC3G,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA0C5B;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IAY9B;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAIxB,SAAS,CAAC,MAAM,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IASvE,oBAAoB;CAG7B"} \ No newline at end of file diff --git a/dist/cjs/client/index.js b/dist/cjs/client/index.js new file mode 100644 index 0000000000..511a2d7d35 --- /dev/null +++ b/dist/cjs/client/index.js @@ -0,0 +1,423 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Client = void 0; +exports.getSupportedElicitationModes = getSupportedElicitationModes; +const protocol_js_1 = require("../shared/protocol.js"); +const types_js_1 = require("../types.js"); +const ajv_provider_js_1 = require("../validation/ajv-provider.js"); +const zod_compat_js_1 = require("../server/zod-compat.js"); +/** + * Elicitation default application helper. Applies defaults to the data based on the schema. + * + * @param schema - The schema to apply defaults to. + * @param data - The data to apply defaults to. + */ +function applyElicitationDefaults(schema, data) { + if (!schema || data === null || typeof data !== 'object') + return; + // Handle object properties + if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') { + const obj = data; + const props = schema.properties; + for (const key of Object.keys(props)) { + const propSchema = props[key]; + // If missing or explicitly undefined, apply default if present + if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) { + obj[key] = propSchema.default; + } + // Recurse into existing nested objects/arrays + if (obj[key] !== undefined) { + applyElicitationDefaults(propSchema, obj[key]); + } + } + } + if (Array.isArray(schema.anyOf)) { + for (const sub of schema.anyOf) { + applyElicitationDefaults(sub, data); + } + } + // Combine schemas + if (Array.isArray(schema.oneOf)) { + for (const sub of schema.oneOf) { + applyElicitationDefaults(sub, data); + } + } +} +/** + * Determines which elicitation modes are supported based on declared client capabilities. + * + * According to the spec: + * - An empty elicitation capability object defaults to form mode support (backwards compatibility) + * - URL mode is only supported if explicitly declared + * + * @param capabilities - The client's elicitation capabilities + * @returns An object indicating which modes are supported + */ +function getSupportedElicitationModes(capabilities) { + if (!capabilities) { + return { supportsFormMode: false, supportsUrlMode: false }; + } + const hasFormCapability = capabilities.form !== undefined; + const hasUrlCapability = capabilities.url !== undefined; + // If neither form nor url are explicitly declared, form mode is supported (backwards compatibility) + const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability); + const supportsUrlMode = hasUrlCapability; + return { supportsFormMode, supportsUrlMode }; +} +/** + * An MCP client on top of a pluggable transport. + * + * The client will automatically begin the initialization flow with the server when connect() is called. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed client + * const client = new Client({ + * name: "CustomClient", + * version: "1.0.0" + * }) + * ``` + */ +class Client extends protocol_js_1.Protocol { + /** + * Initializes this client with the given name and version information. + */ + constructor(_clientInfo, options) { + var _a, _b; + super(options); + this._clientInfo = _clientInfo; + this._cachedToolOutputValidators = new Map(); + this._capabilities = (_a = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a !== void 0 ? _a : {}; + this._jsonSchemaValidator = (_b = options === null || options === void 0 ? void 0 : options.jsonSchemaValidator) !== null && _b !== void 0 ? _b : new ajv_provider_js_1.AjvJsonSchemaValidator(); + } + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) { + throw new Error('Cannot register capabilities after connecting to transport'); + } + this._capabilities = (0, protocol_js_1.mergeCapabilities)(this._capabilities, capabilities); + } + /** + * Override request handler registration to enforce client-side validation for elicitation. + */ + setRequestHandler(requestSchema, handler) { + var _a, _b, _c; + const shape = (0, zod_compat_js_1.getObjectShape)(requestSchema); + const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + // Extract literal value using type-safe property access + let methodValue; + if ((0, zod_compat_js_1.isZ4Schema)(methodSchema)) { + const v4Schema = methodSchema; + const v4Def = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def; + methodValue = (_b = v4Def === null || v4Def === void 0 ? void 0 : v4Def.value) !== null && _b !== void 0 ? _b : v4Schema.value; + } + else { + const v3Schema = methodSchema; + const legacyDef = v3Schema._def; + methodValue = (_c = legacyDef === null || legacyDef === void 0 ? void 0 : legacyDef.value) !== null && _c !== void 0 ? _c : v3Schema.value; + } + if (typeof methodValue !== 'string') { + throw new Error('Schema method literal must be a string'); + } + const method = methodValue; + if (method === 'elicitation/create') { + const wrappedHandler = async (request, extra) => { + var _a, _b; + const validatedRequest = (0, zod_compat_js_1.safeParse)(types_js_1.ElicitRequestSchema, request); + if (!validatedRequest.success) { + // Type guard: if success is false, error is guaranteed to exist + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation); + if (params.mode === 'form' && !supportsFormMode) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests'); + } + if (params.mode === 'url' && !supportsUrlMode) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests'); + } + const result = await Promise.resolve(handler(request, extra)); + const validationResult = (0, zod_compat_js_1.safeParse)(types_js_1.ElicitResultSchema, result); + if (!validationResult.success) { + // Type guard: if success is false, error is guaranteed to exist + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`); + } + const validatedResult = validationResult.data; + const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined; + if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) { + if ((_b = (_a = this._capabilities.elicitation) === null || _a === void 0 ? void 0 : _a.form) === null || _b === void 0 ? void 0 : _b.applyDefaults) { + try { + applyElicitationDefaults(requestedSchema, validatedResult.content); + } + catch (_c) { + // gracefully ignore errors in default application + } + } + } + return validatedResult; + }; + // Install the wrapped handler + return super.setRequestHandler(requestSchema, wrappedHandler); + } + // Non-elicitation handlers use default behavior + return super.setRequestHandler(requestSchema, handler); + } + assertCapability(capability, method) { + var _a; + if (!((_a = this._serverCapabilities) === null || _a === void 0 ? void 0 : _a[capability])) { + throw new Error(`Server does not support ${capability} (required for ${method})`); + } + } + async connect(transport, options) { + await super.connect(transport); + // When transport sessionId is already set this means we are trying to reconnect. + // In this case we don't need to initialize again. + if (transport.sessionId !== undefined) { + return; + } + try { + const result = await this.request({ + method: 'initialize', + params: { + protocolVersion: types_js_1.LATEST_PROTOCOL_VERSION, + capabilities: this._capabilities, + clientInfo: this._clientInfo + } + }, types_js_1.InitializeResultSchema, options); + if (result === undefined) { + throw new Error(`Server sent invalid initialize result: ${result}`); + } + if (!types_js_1.SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) { + throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`); + } + this._serverCapabilities = result.capabilities; + this._serverVersion = result.serverInfo; + // HTTP transports must set the protocol version in each header after initialization. + if (transport.setProtocolVersion) { + transport.setProtocolVersion(result.protocolVersion); + } + this._instructions = result.instructions; + await this.notification({ + method: 'notifications/initialized' + }); + } + catch (error) { + // Disconnect if initialization fails. + void this.close(); + throw error; + } + } + /** + * After initialization has completed, this will be populated with the server's reported capabilities. + */ + getServerCapabilities() { + return this._serverCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the server's name and version. + */ + getServerVersion() { + return this._serverVersion; + } + /** + * After initialization has completed, this may be populated with information about the server's instructions. + */ + getInstructions() { + return this._instructions; + } + assertCapabilityForMethod(method) { + var _a, _b, _c, _d, _e; + switch (method) { + case 'logging/setLevel': + if (!((_a = this._serverCapabilities) === null || _a === void 0 ? void 0 : _a.logging)) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case 'prompts/get': + case 'prompts/list': + if (!((_b = this._serverCapabilities) === null || _b === void 0 ? void 0 : _b.prompts)) { + throw new Error(`Server does not support prompts (required for ${method})`); + } + break; + case 'resources/list': + case 'resources/templates/list': + case 'resources/read': + case 'resources/subscribe': + case 'resources/unsubscribe': + if (!((_c = this._serverCapabilities) === null || _c === void 0 ? void 0 : _c.resources)) { + throw new Error(`Server does not support resources (required for ${method})`); + } + if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) { + throw new Error(`Server does not support resource subscriptions (required for ${method})`); + } + break; + case 'tools/call': + case 'tools/list': + if (!((_d = this._serverCapabilities) === null || _d === void 0 ? void 0 : _d.tools)) { + throw new Error(`Server does not support tools (required for ${method})`); + } + break; + case 'completion/complete': + if (!((_e = this._serverCapabilities) === null || _e === void 0 ? void 0 : _e.completions)) { + throw new Error(`Server does not support completions (required for ${method})`); + } + break; + case 'initialize': + // No specific capability required for initialize + break; + case 'ping': + // No specific capability required for ping + break; + } + } + assertNotificationCapability(method) { + var _a; + switch (method) { + case 'notifications/roots/list_changed': + if (!((_a = this._capabilities.roots) === null || _a === void 0 ? void 0 : _a.listChanged)) { + throw new Error(`Client does not support roots list changed notifications (required for ${method})`); + } + break; + case 'notifications/initialized': + // No specific capability required for initialized + break; + case 'notifications/cancelled': + // Cancellation notifications are always allowed + break; + case 'notifications/progress': + // Progress notifications are always allowed + break; + } + } + assertRequestHandlerCapability(method) { + switch (method) { + case 'sampling/createMessage': + if (!this._capabilities.sampling) { + throw new Error(`Client does not support sampling capability (required for ${method})`); + } + break; + case 'elicitation/create': + if (!this._capabilities.elicitation) { + throw new Error(`Client does not support elicitation capability (required for ${method})`); + } + break; + case 'roots/list': + if (!this._capabilities.roots) { + throw new Error(`Client does not support roots capability (required for ${method})`); + } + break; + case 'ping': + // No specific capability required for ping + break; + } + } + async ping(options) { + return this.request({ method: 'ping' }, types_js_1.EmptyResultSchema, options); + } + async complete(params, options) { + return this.request({ method: 'completion/complete', params }, types_js_1.CompleteResultSchema, options); + } + async setLoggingLevel(level, options) { + return this.request({ method: 'logging/setLevel', params: { level } }, types_js_1.EmptyResultSchema, options); + } + async getPrompt(params, options) { + return this.request({ method: 'prompts/get', params }, types_js_1.GetPromptResultSchema, options); + } + async listPrompts(params, options) { + return this.request({ method: 'prompts/list', params }, types_js_1.ListPromptsResultSchema, options); + } + async listResources(params, options) { + return this.request({ method: 'resources/list', params }, types_js_1.ListResourcesResultSchema, options); + } + async listResourceTemplates(params, options) { + return this.request({ method: 'resources/templates/list', params }, types_js_1.ListResourceTemplatesResultSchema, options); + } + async readResource(params, options) { + return this.request({ method: 'resources/read', params }, types_js_1.ReadResourceResultSchema, options); + } + async subscribeResource(params, options) { + return this.request({ method: 'resources/subscribe', params }, types_js_1.EmptyResultSchema, options); + } + async unsubscribeResource(params, options) { + return this.request({ method: 'resources/unsubscribe', params }, types_js_1.EmptyResultSchema, options); + } + async callTool(params, resultSchema = types_js_1.CallToolResultSchema, options) { + const result = await this.request({ method: 'tools/call', params }, resultSchema, options); + // Check if the tool has an outputSchema + const validator = this.getToolOutputValidator(params.name); + if (validator) { + // If tool has outputSchema, it MUST return structuredContent (unless it's an error) + if (!result.structuredContent && !result.isError) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`); + } + // Only validate structured content if present (not when there's an error) + if (result.structuredContent) { + try { + // Validate the structured content against the schema + const validationResult = validator(result.structuredContent); + if (!validationResult.valid) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`); + } + } + catch (error) { + if (error instanceof types_js_1.McpError) { + throw error; + } + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`); + } + } + } + return result; + } + /** + * Cache validators for tool output schemas. + * Called after listTools() to pre-compile validators for better performance. + */ + cacheToolOutputSchemas(tools) { + this._cachedToolOutputValidators.clear(); + for (const tool of tools) { + // If the tool has an outputSchema, create and cache the validator + if (tool.outputSchema) { + const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema); + this._cachedToolOutputValidators.set(tool.name, toolValidator); + } + } + } + /** + * Get cached validator for a tool + */ + getToolOutputValidator(toolName) { + return this._cachedToolOutputValidators.get(toolName); + } + async listTools(params, options) { + const result = await this.request({ method: 'tools/list', params }, types_js_1.ListToolsResultSchema, options); + // Cache the tools and their output schemas for future validation + this.cacheToolOutputSchemas(result.tools); + return result; + } + async sendRootsListChanged() { + return this.notification({ method: 'notifications/roots/list_changed' }); + } +} +exports.Client = Client; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/cjs/client/index.js.map b/dist/cjs/client/index.js.map new file mode 100644 index 0000000000..5a2d96c9ee --- /dev/null +++ b/dist/cjs/client/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":";;;AAyGA,oEAgBC;AAzHD,uDAA+G;AAE/G,0CAuCqB;AACrB,mEAAuE;AAEvE,2DAQiC;AAGjC;;;;;GAKG;AACH,SAAS,wBAAwB,CAAC,MAAkC,EAAE,IAAa;IAC/E,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,CAAC,IAAI,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;YACnE,CAAC;QACL,CAAC;IACL,CAAC;IAED;;OAEG;IACK,sBAAsB,CAAC,QAAgB;QAC3C,OAAO,IAAI,CAAC,2BAA2B,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC1D,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,MAAmC,EAAE,OAAwB;QACzE,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,EAAE,gCAAqB,EAAE,OAAO,CAAC,CAAC;QAEpG,iEAAiE;QACjE,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAE1C,OAAO,MAAM,CAAC;IAClB,CAAC;IAED,KAAK,CAAC,oBAAoB;QACtB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,kCAAkC,EAAE,CAAC,CAAC;IAC7E,CAAC;CACJ;AAvaD,wBAuaC"} \ No newline at end of file diff --git a/dist/cjs/client/middleware.d.ts b/dist/cjs/client/middleware.d.ts new file mode 100644 index 0000000000..726ac578ae --- /dev/null +++ b/dist/cjs/client/middleware.d.ts @@ -0,0 +1,169 @@ +import { OAuthClientProvider } from './auth.js'; +import { FetchLike } from '../shared/transport.js'; +/** + * Middleware function that wraps and enhances fetch functionality. + * Takes a fetch handler and returns an enhanced fetch handler. + */ +export type Middleware = (next: FetchLike) => FetchLike; +/** + * Creates a fetch wrapper that handles OAuth authentication automatically. + * + * This wrapper will: + * - Add Authorization headers with access tokens + * - Handle 401 responses by attempting re-authentication + * - Retry the original request after successful auth + * - Handle OAuth errors appropriately (InvalidClientError, etc.) + * + * The baseUrl parameter is optional and defaults to using the domain from the request URL. + * However, you should explicitly provide baseUrl when: + * - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com) + * - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /) + * - The OAuth server is on a different domain than your API requests + * - You want to ensure consistent OAuth behavior regardless of request URLs + * + * For MCP transports, set baseUrl to the same URL you pass to the transport constructor. + * + * Note: This wrapper is designed for general-purpose fetch operations. + * MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling + * and should not need this wrapper. + * + * @param provider - OAuth client provider for authentication + * @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain) + * @returns A fetch middleware function + */ +export declare const withOAuth: (provider: OAuthClientProvider, baseUrl?: string | URL) => Middleware; +/** + * Logger function type for HTTP requests + */ +export type RequestLogger = (input: { + method: string; + url: string | URL; + status: number; + statusText: string; + duration: number; + requestHeaders?: Headers; + responseHeaders?: Headers; + error?: Error; +}) => void; +/** + * Configuration options for the logging middleware + */ +export type LoggingOptions = { + /** + * Custom logger function, defaults to console logging + */ + logger?: RequestLogger; + /** + * Whether to include request headers in logs + * @default false + */ + includeRequestHeaders?: boolean; + /** + * Whether to include response headers in logs + * @default false + */ + includeResponseHeaders?: boolean; + /** + * Status level filter - only log requests with status >= this value + * Set to 0 to log all requests, 400 to log only errors + * @default 0 + */ + statusLevel?: number; +}; +/** + * Creates a fetch middleware that logs HTTP requests and responses. + * + * When called without arguments `withLogging()`, it uses the default logger that: + * - Logs successful requests (2xx) to `console.log` + * - Logs error responses (4xx/5xx) and network errors to `console.error` + * - Logs all requests regardless of status (statusLevel: 0) + * - Does not include request or response headers in logs + * - Measures and displays request duration in milliseconds + * + * Important: the default logger uses both `console.log` and `console.error` so it should not be used with + * `stdio` transports and applications. + * + * @param options - Logging configuration options + * @returns A fetch middleware function + */ +export declare const withLogging: (options?: LoggingOptions) => Middleware; +/** + * Composes multiple fetch middleware functions into a single middleware pipeline. + * Middleware are applied in the order they appear, creating a chain of handlers. + * + * @example + * ```typescript + * // Create a middleware pipeline that handles both OAuth and logging + * const enhancedFetch = applyMiddlewares( + * withOAuth(oauthProvider, 'https://api.example.com'), + * withLogging({ statusLevel: 400 }) + * )(fetch); + * + * // Use the enhanced fetch - it will handle auth and log errors + * const response = await enhancedFetch('https://api.example.com/data'); + * ``` + * + * @param middleware - Array of fetch middleware to compose into a pipeline + * @returns A single composed middleware function + */ +export declare const applyMiddlewares: (...middleware: Middleware[]) => Middleware; +/** + * Helper function to create custom fetch middleware with cleaner syntax. + * Provides the next handler and request details as separate parameters for easier access. + * + * @example + * ```typescript + * // Create custom authentication middleware + * const customAuthMiddleware = createMiddleware(async (next, input, init) => { + * const headers = new Headers(init?.headers); + * headers.set('X-Custom-Auth', 'my-token'); + * + * const response = await next(input, { ...init, headers }); + * + * if (response.status === 401) { + * console.log('Authentication failed'); + * } + * + * return response; + * }); + * + * // Create conditional middleware + * const conditionalMiddleware = createMiddleware(async (next, input, init) => { + * const url = typeof input === 'string' ? input : input.toString(); + * + * // Only add headers for API routes + * if (url.includes('/api/')) { + * const headers = new Headers(init?.headers); + * headers.set('X-API-Version', 'v2'); + * return next(input, { ...init, headers }); + * } + * + * // Pass through for non-API routes + * return next(input, init); + * }); + * + * // Create caching middleware + * const cacheMiddleware = createMiddleware(async (next, input, init) => { + * const cacheKey = typeof input === 'string' ? input : input.toString(); + * + * // Check cache first + * const cached = await getFromCache(cacheKey); + * if (cached) { + * return new Response(cached, { status: 200 }); + * } + * + * // Make request and cache result + * const response = await next(input, init); + * if (response.ok) { + * await saveToCache(cacheKey, await response.clone().text()); + * } + * + * return response; + * }); + * ``` + * + * @param handler - Function that receives the next handler and request parameters + * @returns A fetch middleware function + */ +export declare const createMiddleware: (handler: (next: FetchLike, input: string | URL, init?: RequestInit) => Promise) => Middleware; +//# sourceMappingURL=middleware.d.ts.map \ No newline at end of file diff --git a/dist/cjs/client/middleware.d.ts.map b/dist/cjs/client/middleware.d.ts.map new file mode 100644 index 0000000000..88ac77806d --- /dev/null +++ b/dist/cjs/client/middleware.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../../src/client/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsC,m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,KAAK,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,KAAG,UAE3H,CAAC"} \ No newline at end of file diff --git a/dist/cjs/client/middleware.js b/dist/cjs/client/middleware.js new file mode 100644 index 0000000000..f5d9dc3aea --- /dev/null +++ b/dist/cjs/client/middleware.js @@ -0,0 +1,252 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createMiddleware = exports.applyMiddlewares = exports.withLogging = exports.withOAuth = void 0; +const auth_js_1 = require("./auth.js"); +/** + * Creates a fetch wrapper that handles OAuth authentication automatically. + * + * This wrapper will: + * - Add Authorization headers with access tokens + * - Handle 401 responses by attempting re-authentication + * - Retry the original request after successful auth + * - Handle OAuth errors appropriately (InvalidClientError, etc.) + * + * The baseUrl parameter is optional and defaults to using the domain from the request URL. + * However, you should explicitly provide baseUrl when: + * - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com) + * - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /) + * - The OAuth server is on a different domain than your API requests + * - You want to ensure consistent OAuth behavior regardless of request URLs + * + * For MCP transports, set baseUrl to the same URL you pass to the transport constructor. + * + * Note: This wrapper is designed for general-purpose fetch operations. + * MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling + * and should not need this wrapper. + * + * @param provider - OAuth client provider for authentication + * @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain) + * @returns A fetch middleware function + */ +const withOAuth = (provider, baseUrl) => next => { + return async (input, init) => { + const makeRequest = async () => { + const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers); + // Add authorization header if tokens are available + const tokens = await provider.tokens(); + if (tokens) { + headers.set('Authorization', `Bearer ${tokens.access_token}`); + } + return await next(input, { ...init, headers }); + }; + let response = await makeRequest(); + // Handle 401 responses by attempting re-authentication + if (response.status === 401) { + try { + const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response); + // Use provided baseUrl or extract from request URL + const serverUrl = baseUrl || (typeof input === 'string' ? new URL(input).origin : input.origin); + const result = await (0, auth_js_1.auth)(provider, { + serverUrl, + resourceMetadataUrl, + scope, + fetchFn: next + }); + if (result === 'REDIRECT') { + throw new auth_js_1.UnauthorizedError('Authentication requires user authorization - redirect initiated'); + } + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError(`Authentication failed with result: ${result}`); + } + // Retry the request with fresh tokens + response = await makeRequest(); + } + catch (error) { + if (error instanceof auth_js_1.UnauthorizedError) { + throw error; + } + throw new auth_js_1.UnauthorizedError(`Failed to re-authenticate: ${error instanceof Error ? error.message : String(error)}`); + } + } + // If we still have a 401 after re-auth attempt, throw an error + if (response.status === 401) { + const url = typeof input === 'string' ? input : input.toString(); + throw new auth_js_1.UnauthorizedError(`Authentication failed for ${url}`); + } + return response; + }; +}; +exports.withOAuth = withOAuth; +/** + * Creates a fetch middleware that logs HTTP requests and responses. + * + * When called without arguments `withLogging()`, it uses the default logger that: + * - Logs successful requests (2xx) to `console.log` + * - Logs error responses (4xx/5xx) and network errors to `console.error` + * - Logs all requests regardless of status (statusLevel: 0) + * - Does not include request or response headers in logs + * - Measures and displays request duration in milliseconds + * + * Important: the default logger uses both `console.log` and `console.error` so it should not be used with + * `stdio` transports and applications. + * + * @param options - Logging configuration options + * @returns A fetch middleware function + */ +const withLogging = (options = {}) => { + const { logger, includeRequestHeaders = false, includeResponseHeaders = false, statusLevel = 0 } = options; + const defaultLogger = input => { + const { method, url, status, statusText, duration, requestHeaders, responseHeaders, error } = input; + let message = error + ? `HTTP ${method} ${url} failed: ${error.message} (${duration}ms)` + : `HTTP ${method} ${url} ${status} ${statusText} (${duration}ms)`; + // Add headers to message if requested + if (includeRequestHeaders && requestHeaders) { + const reqHeaders = Array.from(requestHeaders.entries()) + .map(([key, value]) => `${key}: ${value}`) + .join(', '); + message += `\n Request Headers: {${reqHeaders}}`; + } + if (includeResponseHeaders && responseHeaders) { + const resHeaders = Array.from(responseHeaders.entries()) + .map(([key, value]) => `${key}: ${value}`) + .join(', '); + message += `\n Response Headers: {${resHeaders}}`; + } + if (error || status >= 400) { + // eslint-disable-next-line no-console + console.error(message); + } + else { + // eslint-disable-next-line no-console + console.log(message); + } + }; + const logFn = logger || defaultLogger; + return next => async (input, init) => { + const startTime = performance.now(); + const method = (init === null || init === void 0 ? void 0 : init.method) || 'GET'; + const url = typeof input === 'string' ? input : input.toString(); + const requestHeaders = includeRequestHeaders ? new Headers(init === null || init === void 0 ? void 0 : init.headers) : undefined; + try { + const response = await next(input, init); + const duration = performance.now() - startTime; + // Only log if status meets the log level threshold + if (response.status >= statusLevel) { + logFn({ + method, + url, + status: response.status, + statusText: response.statusText, + duration, + requestHeaders, + responseHeaders: includeResponseHeaders ? response.headers : undefined + }); + } + return response; + } + catch (error) { + const duration = performance.now() - startTime; + // Always log errors regardless of log level + logFn({ + method, + url, + status: 0, + statusText: 'Network Error', + duration, + requestHeaders, + error: error + }); + throw error; + } + }; +}; +exports.withLogging = withLogging; +/** + * Composes multiple fetch middleware functions into a single middleware pipeline. + * Middleware are applied in the order they appear, creating a chain of handlers. + * + * @example + * ```typescript + * // Create a middleware pipeline that handles both OAuth and logging + * const enhancedFetch = applyMiddlewares( + * withOAuth(oauthProvider, 'https://api.example.com'), + * withLogging({ statusLevel: 400 }) + * )(fetch); + * + * // Use the enhanced fetch - it will handle auth and log errors + * const response = await enhancedFetch('https://api.example.com/data'); + * ``` + * + * @param middleware - Array of fetch middleware to compose into a pipeline + * @returns A single composed middleware function + */ +const applyMiddlewares = (...middleware) => { + return next => { + return middleware.reduce((handler, mw) => mw(handler), next); + }; +}; +exports.applyMiddlewares = applyMiddlewares; +/** + * Helper function to create custom fetch middleware with cleaner syntax. + * Provides the next handler and request details as separate parameters for easier access. + * + * @example + * ```typescript + * // Create custom authentication middleware + * const customAuthMiddleware = createMiddleware(async (next, input, init) => { + * const headers = new Headers(init?.headers); + * headers.set('X-Custom-Auth', 'my-token'); + * + * const response = await next(input, { ...init, headers }); + * + * if (response.status === 401) { + * console.log('Authentication failed'); + * } + * + * return response; + * }); + * + * // Create conditional middleware + * const conditionalMiddleware = createMiddleware(async (next, input, init) => { + * const url = typeof input === 'string' ? input : input.toString(); + * + * // Only add headers for API routes + * if (url.includes('/api/')) { + * const headers = new Headers(init?.headers); + * headers.set('X-API-Version', 'v2'); + * return next(input, { ...init, headers }); + * } + * + * // Pass through for non-API routes + * return next(input, init); + * }); + * + * // Create caching middleware + * const cacheMiddleware = createMiddleware(async (next, input, init) => { + * const cacheKey = typeof input === 'string' ? input : input.toString(); + * + * // Check cache first + * const cached = await getFromCache(cacheKey); + * if (cached) { + * return new Response(cached, { status: 200 }); + * } + * + * // Make request and cache result + * const response = await next(input, init); + * if (response.ok) { + * await saveToCache(cacheKey, await response.clone().text()); + * } + * + * return response; + * }); + * ``` + * + * @param handler - Function that receives the next handler and request parameters + * @returns A fetch middleware function + */ +const createMiddleware = (handler) => { + return next => (input, init) => handler(next, input, init); +}; +exports.createMiddleware = createMiddleware; +//# sourceMappingURL=middleware.js.map \ No newline at end of file diff --git a/dist/cjs/client/middleware.js.map b/dist/cjs/client/middleware.js.map new file mode 100644 index 0000000000..e68b40c98f --- /dev/null +++ b/dist/cjs/client/middleware.js.map @@ -0,0 +1 @@ +{"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../../src/client/middleware.ts"],"names":[],"mappings":";;;AAAA,uCAAuG;AASvG;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACI,MAAM,SAAS,GAClB,CAAC,QAA6B,EAAE,OAAsB,EAAc,EAAE,CACtE,IAAI,CAAC,EAAE;IACH,OAAO,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE;QACzB,MAAM,WAAW,GAAG,KAAK,IAAuB,EAAE;YAC9C,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,CAAC,CAAC;YAE3C,mDA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AAC,OAAO,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,CAAC;IACjE,CAAC,CAAC;AACN,CAAC,CAAC;AAJW,QAAA,gBAAgB,oBAI3B;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AACI,MAAM,gBAAgB,GAAG,CAAC,OAAwF,EAAc,EAAE;IACrI,OAAO,IAAI,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,KAAqB,EAAE,IAAI,CAAC,CAAC;AAC/E,CAAC,CAAC;AAFW,QAAA,gBAAgB,oBAE3B"} \ No newline at end of file diff --git a/dist/cjs/client/sse.d.ts b/dist/cjs/client/sse.d.ts new file mode 100644 index 0000000000..acf99f1ea6 --- /dev/null +++ b/dist/cjs/client/sse.d.ts @@ -0,0 +1,81 @@ +import { type ErrorEvent, type EventSourceInit } from 'eventsource'; +import { Transport, FetchLike } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +import { OAuthClientProvider } from './auth.js'; +export declare class SseError extends Error { + readonly code: number | undefined; + readonly event: ErrorEvent; + constructor(code: number | undefined, message: string | undefined, event: ErrorEvent); +} +/** + * Configuration options for the `SSEClientTransport`. + */ +export type SSEClientTransportOptions = { + /** + * An OAuth client provider to use for authentication. + * + * When an `authProvider` is specified and the SSE connection is started: + * 1. The connection is attempted with any existing access token from the `authProvider`. + * 2. If the access token has expired, the `authProvider` is used to refresh the token. + * 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`. + * + * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `SSEClientTransport.finishAuth` with the authorization code before retrying the connection. + * + * If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown. + * + * `UnauthorizedError` might also be thrown when sending any message over the SSE transport, indicating that the session has expired, and needs to be re-authed and reconnected. + */ + authProvider?: OAuthClientProvider; + /** + * Customizes the initial SSE request to the server (the request that begins the stream). + * + * NOTE: Setting this property will prevent an `Authorization` header from + * being automatically attached to the SSE request, if an `authProvider` is + * also given. This can be worked around by setting the `Authorization` header + * manually. + */ + eventSourceInit?: EventSourceInit; + /** + * Customizes recurring POST requests to the server. + */ + requestInit?: RequestInit; + /** + * Custom fetch implementation used for all network requests. + */ + fetch?: FetchLike; +}; +/** + * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving + * messages and make separate POST requests for sending messages. + * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period. + */ +export declare class SSEClientTransport implements Transport { + private _eventSource?; + private _endpoint?; + private _abortController?; + private _url; + private _resourceMetadataUrl?; + private _scope?; + private _eventSourceInit?; + private _requestInit?; + private _authProvider?; + private _fetch?; + private _fetchWithInit; + private _protocolVersion?; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(url: URL, opts?: SSEClientTransportOptions); + private _authThenStart; + private _commonHeaders; + private _startOrAuth; + start(): Promise; + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + finishAuth(authorizationCode: string): Promise; + close(): Promise; + send(message: JSONRPCMessage): Promise; + setProtocolVersion(version: string): void; +} +//# sourceMappingURL=sse.d.ts.map \ No newline at end of file diff --git a/dist/cjs/client/sse.d.ts.map b/dist/cjs/client/sse.d.ts.map new file mode 100644 index 0000000000..3a0053cfc6 --- /dev/null +++ b/dist/cjs/client/sse.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../../src/client/sse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,KAAK,UAAU,EAAE,KAAK,eAAe,EAAE,MAAM,aAAa,CAAC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;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,yBAAyB;YAWxC,cAAc;YAyBd,cAAc;IAe5B,OAAO,CAAC,YAAY;IAyEd,KAAK;IAQX;;OAEG;IACG,UAAU,CAAC,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiBpD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAMtB,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IA8ClD,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;CAG5C"} \ No newline at end of file diff --git a/dist/cjs/client/sse.js b/dist/cjs/client/sse.js new file mode 100644 index 0000000000..7206b6412a --- /dev/null +++ b/dist/cjs/client/sse.js @@ -0,0 +1,213 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SSEClientTransport = exports.SseError = void 0; +const eventsource_1 = require("eventsource"); +const transport_js_1 = require("../shared/transport.js"); +const types_js_1 = require("../types.js"); +const auth_js_1 = require("./auth.js"); +class SseError extends Error { + constructor(code, message, event) { + super(`SSE error: ${message}`); + this.code = code; + this.event = event; + } +} +exports.SseError = SseError; +/** + * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving + * messages and make separate POST requests for sending messages. + * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period. + */ +class SSEClientTransport { + constructor(url, opts) { + this._url = url; + this._resourceMetadataUrl = undefined; + this._scope = undefined; + this._eventSourceInit = opts === null || opts === void 0 ? void 0 : opts.eventSourceInit; + this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit; + this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider; + this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch; + this._fetchWithInit = (0, transport_js_1.createFetchWithInit)(opts === null || opts === void 0 ? void 0 : opts.fetch, opts === null || opts === void 0 ? void 0 : opts.requestInit); + } + async _authThenStart() { + var _a; + if (!this._authProvider) { + throw new auth_js_1.UnauthorizedError('No auth provider'); + } + let result; + try { + result = await (0, auth_js_1.auth)(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + } + catch (error) { + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + throw error; + } + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError(); + } + return await this._startOrAuth(); + } + async _commonHeaders() { + var _a; + const headers = {}; + if (this._authProvider) { + const tokens = await this._authProvider.tokens(); + if (tokens) { + headers['Authorization'] = `Bearer ${tokens.access_token}`; + } + } + if (this._protocolVersion) { + headers['mcp-protocol-version'] = this._protocolVersion; + } + return new Headers({ ...headers, ...(_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers }); + } + _startOrAuth() { + var _a, _b, _c; + const fetchImpl = ((_c = (_b = (_a = this === null || this === void 0 ? void 0 : this._eventSourceInit) === null || _a === void 0 ? void 0 : _a.fetch) !== null && _b !== void 0 ? _b : this._fetch) !== null && _c !== void 0 ? _c : fetch); + return new Promise((resolve, reject) => { + this._eventSource = new eventsource_1.EventSource(this._url.href, { + ...this._eventSourceInit, + fetch: async (url, init) => { + const headers = await this._commonHeaders(); + headers.set('Accept', 'text/event-stream'); + const response = await fetchImpl(url, { + ...init, + headers + }); + if (response.status === 401 && response.headers.has('www-authenticate')) { + const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + } + return response; + } + }); + this._abortController = new AbortController(); + this._eventSource.onerror = event => { + var _a; + if (event.code === 401 && this._authProvider) { + this._authThenStart().then(resolve, reject); + return; + } + const error = new SseError(event.code, event.message, event); + reject(error); + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }; + this._eventSource.onopen = () => { + // The connection is open, but we need to wait for the endpoint to be received. + }; + this._eventSource.addEventListener('endpoint', (event) => { + var _a; + const messageEvent = event; + try { + this._endpoint = new URL(messageEvent.data, this._url); + if (this._endpoint.origin !== this._url.origin) { + throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`); + } + } + catch (error) { + reject(error); + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + void this.close(); + return; + } + resolve(); + }); + this._eventSource.onmessage = (event) => { + var _a, _b; + const messageEvent = event; + let message; + try { + message = types_js_1.JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data)); + } + catch (error) { + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + return; + } + (_b = this.onmessage) === null || _b === void 0 ? void 0 : _b.call(this, message); + }; + }); + } + async start() { + if (this._eventSource) { + throw new Error('SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + return await this._startOrAuth(); + } + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + async finishAuth(authorizationCode) { + if (!this._authProvider) { + throw new auth_js_1.UnauthorizedError('No auth provider'); + } + const result = await (0, auth_js_1.auth)(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError('Failed to authorize'); + } + } + async close() { + var _a, _b, _c; + (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + (_b = this._eventSource) === null || _b === void 0 ? void 0 : _b.close(); + (_c = this.onclose) === null || _c === void 0 ? void 0 : _c.call(this); + } + async send(message) { + var _a, _b, _c; + if (!this._endpoint) { + throw new Error('Not connected'); + } + try { + const headers = await this._commonHeaders(); + headers.set('content-type', 'application/json'); + const init = { + ...this._requestInit, + method: 'POST', + headers, + body: JSON.stringify(message), + signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal + }; + const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._endpoint, init); + if (!response.ok) { + if (response.status === 401 && this._authProvider) { + const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + const result = await (0, auth_js_1.auth)(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError(); + } + // Purposely _not_ awaited, so we don't call onerror twice + return this.send(message); + } + const text = await response.text().catch(() => null); + throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); + } + } + catch (error) { + (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error); + throw error; + } + } + setProtocolVersion(version) { + this._protocolVersion = version; + } +} +exports.SSEClientTransport = SSEClientTransport; +//# sourceMappingURL=sse.js.map \ No newline at end of file diff --git a/dist/cjs/client/sse.js.map b/dist/cjs/client/sse.js.map new file mode 100644 index 0000000000..a3c4180507 --- /dev/null +++ b/dist/cjs/client/sse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sse.js","sourceRoot":"","sources":["../../../src/client/sse.ts"],"names":[],"mappings":";;;AAAA,6CAAiF;AACjF,yDAAmF;AACnF,0CAAmE;AACnE,uCAAmH;AAEnH,MAAa,QAAS,SAAQ,KAAK;IAC/B,YACoB,IAAwB,EACxC,OAA2B,EACX,KAAiB;QAEjC,KAAK,CAAC,cAAc,OAAO,EAAE,CAAC,CAAC;QAJf,SAAI,GAAJ,IAAI,CAAoB;QAExB,UAAK,GAAL,KAAK,CAAY;IAGrC,CAAC;CACJ;AARD,4BAQC;AA2CD;;;;GAIG;AACH,MAAa,kBAAkB;IAkB3B,YAAY,GAAQ,EAAE,IAAgC;QAClD,IAAI,CAAC,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AgB,GAAG,OAAO,CAAC;IACpC,CAAC;CACJ;AAjOD,gDAiOC"} \ No newline at end of file diff --git a/dist/cjs/client/stdio.d.ts b/dist/cjs/client/stdio.d.ts new file mode 100644 index 0000000000..58d0b6ccba --- /dev/null +++ b/dist/cjs/client/stdio.d.ts @@ -0,0 +1,78 @@ +import { IOType } from 'node:child_process'; +import { Stream } from 'node:stream'; +import { Transport } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +export type StdioServerParameters = { + /** + * The executable to run to start the server. + */ + command: string; + /** + * Command line arguments to pass to the executable. + */ + args?: string[]; + /** + * The environment to use when spawning the process. + * + * If not specified, the result of getDefaultEnvironment() will be used. + */ + env?: Record; + /** + * How to handle stderr of the child process. This matches the semantics of Node's `child_process.spawn`. + * + * The default is "inherit", meaning messages to stderr will be printed to the parent process's stderr. + */ + stderr?: IOType | Stream | number; + /** + * The working directory to use when spawning the process. + * + * If not specified, the current working directory will be inherited. + */ + cwd?: string; +}; +/** + * Environment variables to inherit by default, if an environment is not explicitly given. + */ +export declare const DEFAULT_INHERITED_ENV_VARS: string[]; +/** + * Returns a default environment object including only environment variables deemed safe to inherit. + */ +export declare function getDefaultEnvironment(): Record; +/** + * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout. + * + * This transport is only available in Node.js environments. + */ +export declare class StdioClientTransport implements Transport { + private _process?; + private _abortController; + private _readBuffer; + private _serverParams; + private _stderrStream; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(server: StdioServerParameters); + /** + * Starts the server process and prepares to communicate with it. + */ + start(): Promise; + /** + * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". + * + * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to + * attach listeners before the start method is invoked. This prevents loss of any early + * error output emitted by the child process. + */ + get stderr(): Stream | null; + /** + * The child process pid spawned by this transport. + * + * This is only available after the transport has been started. + */ + get pid(): number | null; + private processReadBuffer; + close(): Promise; + send(message: JSONRPCMessage): Promise; +} +//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/dist/cjs/client/stdio.d.ts.map b/dist/cjs/client/stdio.d.ts.map new file mode 100644 index 0000000000..44f6de451b --- /dev/null +++ b/dist/cjs/client/stdio.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/client/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAG1D,OAAO,EAAE,MAAM,EAAe,MAAM,aAAa,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE7C,MAAM,MAAM,qBAAqB,GAAG;IAChC;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAEhB;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAE7B;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IAElC;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,0BAA0B,UAiBuB,CAAC;AAE/D;;GAEG;AACH,wBAAgB,qBAAqB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAkB9D;AAED;;;;GAIG;AACH,qBAAa,oBAAqB,YAAW,SAAS;IAClD,OAAO,CAAC,QAAQ,CAAC,CAAe;IAChC,OAAO,CAAC,gBAAgB,CAA0C;IAClE,OAAO,CAAC,WAAW,CAAgC;IACnD,OAAO,CAAC,aAAa,CAAwB;IAC7C,OAAO,CAAC,aAAa,CAA4B;IAEjD,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,MAAM,EAAE,qBAAqB;IAOzC;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IA4D5B;;;;;;OAMG;IACH,IAAI,MAAM,IAAI,MAAM,GAAG,IAAI,CAM1B;IAED;;;;OAIG;IACH,IAAI,GAAG,IAAI,MAAM,GAAG,IAAI,CAEvB;IAED,OAAO,CAAC,iBAAiB;IAenB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAM5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAc/C"} \ No newline at end of file diff --git a/dist/cjs/client/stdio.js b/dist/cjs/client/stdio.js new file mode 100644 index 0000000000..95d6f94f30 --- /dev/null +++ b/dist/cjs/client/stdio.js @@ -0,0 +1,184 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StdioClientTransport = exports.DEFAULT_INHERITED_ENV_VARS = void 0; +exports.getDefaultEnvironment = getDefaultEnvironment; +const cross_spawn_1 = __importDefault(require("cross-spawn")); +const node_process_1 = __importDefault(require("node:process")); +const node_stream_1 = require("node:stream"); +const stdio_js_1 = require("../shared/stdio.js"); +/** + * Environment variables to inherit by default, if an environment is not explicitly given. + */ +exports.DEFAULT_INHERITED_ENV_VARS = node_process_1.default.platform === 'win32' + ? [ + 'APPDATA', + 'HOMEDRIVE', + 'HOMEPATH', + 'LOCALAPPDATA', + 'PATH', + 'PROCESSOR_ARCHITECTURE', + 'SYSTEMDRIVE', + 'SYSTEMROOT', + 'TEMP', + 'USERNAME', + 'USERPROFILE', + 'PROGRAMFILES' + ] + : /* list inspired by the default env inheritance of sudo */ + ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER']; +/** + * Returns a default environment object including only environment variables deemed safe to inherit. + */ +function getDefaultEnvironment() { + const env = {}; + for (const key of exports.DEFAULT_INHERITED_ENV_VARS) { + const value = node_process_1.default.env[key]; + if (value === undefined) { + continue; + } + if (value.startsWith('()')) { + // Skip functions, which are a security risk. + continue; + } + env[key] = value; + } + return env; +} +/** + * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout. + * + * This transport is only available in Node.js environments. + */ +class StdioClientTransport { + constructor(server) { + this._abortController = new AbortController(); + this._readBuffer = new stdio_js_1.ReadBuffer(); + this._stderrStream = null; + this._serverParams = server; + if (server.stderr === 'pipe' || server.stderr === 'overlapped') { + this._stderrStream = new node_stream_1.PassThrough(); + } + } + /** + * Starts the server process and prepares to communicate with it. + */ + async start() { + if (this._process) { + throw new Error('StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + return new Promise((resolve, reject) => { + var _a, _b, _c, _d, _e; + this._process = (0, cross_spawn_1.default)(this._serverParams.command, (_a = this._serverParams.args) !== null && _a !== void 0 ? _a : [], { + // merge default env with server env because mcp server needs some env vars + env: { + ...getDefaultEnvironment(), + ...this._serverParams.env + }, + stdio: ['pipe', 'pipe', (_b = this._serverParams.stderr) !== null && _b !== void 0 ? _b : 'inherit'], + shell: false, + signal: this._abortController.signal, + windowsHide: node_process_1.default.platform === 'win32' && isElectron(), + cwd: this._serverParams.cwd + }); + this._process.on('error', error => { + var _a, _b; + if (error.name === 'AbortError') { + // Expected when close() is called. + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + return; + } + reject(error); + (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); + }); + this._process.on('spawn', () => { + resolve(); + }); + this._process.on('close', _code => { + var _a; + this._process = undefined; + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + }); + (_c = this._process.stdin) === null || _c === void 0 ? void 0 : _c.on('error', error => { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }); + (_d = this._process.stdout) === null || _d === void 0 ? void 0 : _d.on('data', chunk => { + this._readBuffer.append(chunk); + this.processReadBuffer(); + }); + (_e = this._process.stdout) === null || _e === void 0 ? void 0 : _e.on('error', error => { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }); + if (this._stderrStream && this._process.stderr) { + this._process.stderr.pipe(this._stderrStream); + } + }); + } + /** + * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". + * + * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to + * attach listeners before the start method is invoked. This prevents loss of any early + * error output emitted by the child process. + */ + get stderr() { + var _a, _b; + if (this._stderrStream) { + return this._stderrStream; + } + return (_b = (_a = this._process) === null || _a === void 0 ? void 0 : _a.stderr) !== null && _b !== void 0 ? _b : null; + } + /** + * The child process pid spawned by this transport. + * + * This is only available after the transport has been started. + */ + get pid() { + var _a, _b; + return (_b = (_a = this._process) === null || _a === void 0 ? void 0 : _a.pid) !== null && _b !== void 0 ? _b : null; + } + processReadBuffer() { + var _a, _b; + while (true) { + try { + const message = this._readBuffer.readMessage(); + if (message === null) { + break; + } + (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message); + } + catch (error) { + (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); + } + } + } + async close() { + this._abortController.abort(); + this._process = undefined; + this._readBuffer.clear(); + } + send(message) { + return new Promise(resolve => { + var _a; + if (!((_a = this._process) === null || _a === void 0 ? void 0 : _a.stdin)) { + throw new Error('Not connected'); + } + const json = (0, stdio_js_1.serializeMessage)(message); + if (this._process.stdin.write(json)) { + resolve(); + } + else { + this._process.stdin.once('drain', resolve); + } + }); + } +} +exports.StdioClientTransport = StdioClientTransport; +function isElectron() { + return 'type' in node_process_1.default; +} +//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/dist/cjs/client/stdio.js.map b/dist/cjs/client/stdio.js.map new file mode 100644 index 0000000000..3b84737a12 --- /dev/null +++ b/dist/cjs/client/stdio.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/client/stdio.ts"],"names":[],"mappings":";;;;;;AAkEA,sDAkBC;AAnFD,8DAAgC;AAChC,gEAAmC;AACnC,6CAAkD;AAClD,iDAAkE;AAqClE;;GAEG;AACU,QAAA,0BAA0B,GACnC,sBAAO,CAAC,QAAQ,KAAK,OAAO;IACxB,CAAC,CAAC;QACI,SAAS;QACT,WAAW;QACX,UAAU;QACV,cAAc;QACd,MAAM;QACN,wBAAwB;QACxB,aAAa;QACb,YAAY;QACZ,MAAM;QACN,UAAU;QACV,aAAa;QACb,cAAc;KACjB;IACH,CAAC,CAAC,0DAA0D;QAC1D,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAE/D;;GAEG;AACH,SAAgB,qBAAqB;IACjC,MAAM,GAAG,GAA2B,EAAE,CAAC;IAEvC,KAAK,MAAM,GAAG,IAAI,kCAA0B,EAAE,CAAC;QAC3C,MAAM,KAAK,GAAG,sBAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC/B,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACtB,SAAS;QACb,CAAC;QAED,IAAI,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;YACzB,6CAA6C;YAC7C,SAAS;QACb,CAAC;QAED,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,OAAO,GAAG,CAAC;AACf,CAAC;AAED;;;;GAIG;AACH,MAAa,oBAAoB;IAW7B,YAAY,MAA6B;QATjC,qBAAgB,GAAoB,IAAI,eAAe,EAAE,CAAC;QAC1D,gBAAW,GAAe,IAAI,qBAAU,EAAE,CAAC;QAE3C,kBAAa,GAAuB,IAAI,CAAC;QAO7C,IAAI,CAAC,aAAa,GAAG,MA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;gBACJ,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC/C,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AA5ID,oDA4IC;AAED,SAAS,UAAU;IACf,OAAO,MAAM,IAAI,sBAAO,CAAC;AAC7B,CAAC"} \ No newline at end of file diff --git a/dist/cjs/client/streamableHttp.d.ts b/dist/cjs/client/streamableHttp.d.ts new file mode 100644 index 0000000000..6c6a32f473 --- /dev/null +++ b/dist/cjs/client/streamableHttp.d.ts @@ -0,0 +1,159 @@ +import { Transport, FetchLike } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +import { OAuthClientProvider } from './auth.js'; +export declare class StreamableHTTPError extends Error { + readonly code: number | undefined; + constructor(code: number | undefined, message: string | undefined); +} +/** + * Options for starting or authenticating an SSE connection + */ +export interface StartSSEOptions { + /** + * The resumption token used to continue long-running requests that were interrupted. + * + * This allows clients to reconnect and continue from where they left off. + */ + resumptionToken?: string; + /** + * A callback that is invoked when the resumption token changes. + * + * This allows clients to persist the latest token for potential reconnection. + */ + onresumptiontoken?: (token: string) => void; + /** + * Override Message ID to associate with the replay message + * so that response can be associate with the new resumed request. + */ + replayMessageId?: string | number; +} +/** + * Configuration options for reconnection behavior of the StreamableHTTPClientTransport. + */ +export interface StreamableHTTPReconnectionOptions { + /** + * Maximum backoff time between reconnection attempts in milliseconds. + * Default is 30000 (30 seconds). + */ + maxReconnectionDelay: number; + /** + * Initial backoff time between reconnection attempts in milliseconds. + * Default is 1000 (1 second). + */ + initialReconnectionDelay: number; + /** + * The factor by which the reconnection delay increases after each attempt. + * Default is 1.5. + */ + reconnectionDelayGrowFactor: number; + /** + * Maximum number of reconnection attempts before giving up. + * Default is 2. + */ + maxRetries: number; +} +/** + * Configuration options for the `StreamableHTTPClientTransport`. + */ +export type StreamableHTTPClientTransportOptions = { + /** + * An OAuth client provider to use for authentication. + * + * When an `authProvider` is specified and the connection is started: + * 1. The connection is attempted with any existing access token from the `authProvider`. + * 2. If the access token has expired, the `authProvider` is used to refresh the token. + * 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`. + * + * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `StreamableHTTPClientTransport.finishAuth` with the authorization code before retrying the connection. + * + * If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown. + * + * `UnauthorizedError` might also be thrown when sending any message over the transport, indicating that the session has expired, and needs to be re-authed and reconnected. + */ + authProvider?: OAuthClientProvider; + /** + * Customizes HTTP requests to the server. + */ + requestInit?: RequestInit; + /** + * Custom fetch implementation used for all network requests. + */ + fetch?: FetchLike; + /** + * Options to configure the reconnection behavior. + */ + reconnectionOptions?: StreamableHTTPReconnectionOptions; + /** + * Session ID for the connection. This is used to identify the session on the server. + * When not provided and connecting to a server that supports session IDs, the server will generate a new session ID. + */ + sessionId?: string; +}; +/** + * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events + * for receiving messages. + */ +export declare class StreamableHTTPClientTransport implements Transport { + private _abortController?; + private _url; + private _resourceMetadataUrl?; + private _scope?; + private _requestInit?; + private _authProvider?; + private _fetch?; + private _fetchWithInit; + private _sessionId?; + private _reconnectionOptions; + private _protocolVersion?; + private _hasCompletedAuthFlow; + private _lastUpscopingHeader?; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(url: URL, opts?: StreamableHTTPClientTransportOptions); + private _authThenStart; + private _commonHeaders; + private _startOrAuthSse; + /** + * Calculates the next reconnection delay using backoff algorithm + * + * @param attempt Current reconnection attempt count for the specific stream + * @returns Time to wait in milliseconds before next reconnection attempt + */ + private _getNextReconnectionDelay; + /** + * Schedule a reconnection attempt with exponential backoff + * + * @param lastEventId The ID of the last received event for resumability + * @param attemptCount Current reconnection attempt count for this specific stream + */ + private _scheduleReconnection; + private _handleSseStream; + start(): Promise; + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + finishAuth(authorizationCode: string): Promise; + close(): Promise; + send(message: JSONRPCMessage | JSONRPCMessage[], options?: { + resumptionToken?: string; + onresumptiontoken?: (token: string) => void; + }): Promise; + get sessionId(): string | undefined; + /** + * Terminates the current session by sending a DELETE request to the server. + * + * Clients that no longer need a particular session + * (e.g., because the user is leaving the client application) SHOULD send an + * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly + * terminate the session. + * + * The server MAY respond with HTTP 405 Method Not Allowed, indicating that + * the server does not allow clients to terminate sessions. + */ + terminateSession(): Promise; + setProtocolVersion(version: string): void; + get protocolVersion(): string | undefined; +} +//# sourceMappingURL=streamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/client/streamableHttp.d.ts.map b/dist/cjs/client/streamableHttp.d.ts.map new file mode 100644 index 0000000000..cbca11957b --- /dev/null +++ b/dist/cjs/client/streamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.d.ts","sourceRoot":"","sources":["../../../src/client/streamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAyC,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAkE,cAAc,EAAwB,MAAM,aAAa,CAAC;AACnI,OAAO,EAAkD,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AAWnH,qBAAa,mBAAoB,SAAQ,KAAK;aAEtB,IAAI,EAAE,MAAM,GAAG,SAAS;gBAAxB,IAAI,EAAE,MAAM,GAAG,SAAS,EACxC,OAAO,EAAE,MAAM,GAAG,SAAS;CAIlC;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC5B;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;OAIG;IACH,iBAAiB,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;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,oCAAoC;YAYnD,cAAc;YAyBd,cAAc;YAwBd,eAAe;IAyC7B;;;;;OAKG;IACH,OAAO,CAAC,yBAAyB;IAUjC;;;;;OAKG;IACH,OAAO,CAAC,qBAAqB;IAwB7B,OAAO,CAAC,gBAAgB;IAkElB,KAAK;IAUX;;OAEG;IACG,UAAU,CAAC,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiBpD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAOtB,IAAI,CACN,OAAO,EAAE,cAAc,GAAG,cAAc,EAAE,EAC1C,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,MAAM,CAAC;QAAC,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;KAAE,GACpF,OAAO,CAAC,IAAI,CAAC;IAoJhB,IAAI,SAAS,IAAI,MAAM,GAAG,SAAS,CAElC;IAED;;;;;;;;;;OAUG;IACG,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;IA8BvC,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAGzC,IAAI,eAAe,IAAI,MAAM,GAAG,SAAS,CAExC;CACJ"} \ No newline at end of file diff --git a/dist/cjs/client/streamableHttp.js b/dist/cjs/client/streamableHttp.js new file mode 100644 index 0000000000..63c17b8c86 --- /dev/null +++ b/dist/cjs/client/streamableHttp.js @@ -0,0 +1,426 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamableHTTPClientTransport = exports.StreamableHTTPError = void 0; +const transport_js_1 = require("../shared/transport.js"); +const types_js_1 = require("../types.js"); +const auth_js_1 = require("./auth.js"); +const stream_1 = require("eventsource-parser/stream"); +// Default reconnection options for StreamableHTTP connections +const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = { + initialReconnectionDelay: 1000, + maxReconnectionDelay: 30000, + reconnectionDelayGrowFactor: 1.5, + maxRetries: 2 +}; +class StreamableHTTPError extends Error { + constructor(code, message) { + super(`Streamable HTTP error: ${message}`); + this.code = code; + } +} +exports.StreamableHTTPError = StreamableHTTPError; +/** + * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events + * for receiving messages. + */ +class StreamableHTTPClientTransport { + constructor(url, opts) { + var _a; + this._hasCompletedAuthFlow = false; // Circuit breaker: detect auth success followed by immediate 401 + this._url = url; + this._resourceMetadataUrl = undefined; + this._scope = undefined; + this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit; + this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider; + this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch; + this._fetchWithInit = (0, transport_js_1.createFetchWithInit)(opts === null || opts === void 0 ? void 0 : opts.fetch, opts === null || opts === void 0 ? void 0 : opts.requestInit); + this._sessionId = opts === null || opts === void 0 ? void 0 : opts.sessionId; + this._reconnectionOptions = (_a = opts === null || opts === void 0 ? void 0 : opts.reconnectionOptions) !== null && _a !== void 0 ? _a : DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS; + } + async _authThenStart() { + var _a; + if (!this._authProvider) { + throw new auth_js_1.UnauthorizedError('No auth provider'); + } + let result; + try { + result = await (0, auth_js_1.auth)(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + } + catch (error) { + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + throw error; + } + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError(); + } + return await this._startOrAuthSse({ resumptionToken: undefined }); + } + async _commonHeaders() { + var _a; + const headers = {}; + if (this._authProvider) { + const tokens = await this._authProvider.tokens(); + if (tokens) { + headers['Authorization'] = `Bearer ${tokens.access_token}`; + } + } + if (this._sessionId) { + headers['mcp-session-id'] = this._sessionId; + } + if (this._protocolVersion) { + headers['mcp-protocol-version'] = this._protocolVersion; + } + const extraHeaders = (0, transport_js_1.normalizeHeaders)((_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers); + return new Headers({ + ...headers, + ...extraHeaders + }); + } + async _startOrAuthSse(options) { + var _a, _b, _c; + const { resumptionToken } = options; + try { + // Try to open an initial SSE stream with GET to listen for server messages + // This is optional according to the spec - server may not support it + const headers = await this._commonHeaders(); + headers.set('Accept', 'text/event-stream'); + // Include Last-Event-ID header for resumable streams if provided + if (resumptionToken) { + headers.set('last-event-id', resumptionToken); + } + const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(this._url, { + method: 'GET', + headers, + signal: (_b = this._abortController) === null || _b === void 0 ? void 0 : _b.signal + }); + if (!response.ok) { + if (response.status === 401 && this._authProvider) { + // Need to authenticate + return await this._authThenStart(); + } + // 405 indicates that the server does not offer an SSE stream at GET endpoint + // This is an expected case that should not trigger an error + if (response.status === 405) { + return; + } + throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`); + } + this._handleSseStream(response.body, options, true); + } + catch (error) { + (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error); + throw error; + } + } + /** + * Calculates the next reconnection delay using backoff algorithm + * + * @param attempt Current reconnection attempt count for the specific stream + * @returns Time to wait in milliseconds before next reconnection attempt + */ + _getNextReconnectionDelay(attempt) { + // Access default values directly, ensuring they're never undefined + const initialDelay = this._reconnectionOptions.initialReconnectionDelay; + const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor; + const maxDelay = this._reconnectionOptions.maxReconnectionDelay; + // Cap at maximum delay + return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay); + } + /** + * Schedule a reconnection attempt with exponential backoff + * + * @param lastEventId The ID of the last received event for resumability + * @param attemptCount Current reconnection attempt count for this specific stream + */ + _scheduleReconnection(options, attemptCount = 0) { + var _a; + // Use provided options or default options + const maxRetries = this._reconnectionOptions.maxRetries; + // Check if we've exceeded maximum retry attempts + if (maxRetries > 0 && attemptCount >= maxRetries) { + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`)); + return; + } + // Calculate next delay based on current attempt count + const delay = this._getNextReconnectionDelay(attemptCount); + // Schedule the reconnection + setTimeout(() => { + // Use the last event ID to resume where we left off + this._startOrAuthSse(options).catch(error => { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`)); + // Schedule another attempt if this one failed, incrementing the attempt counter + this._scheduleReconnection(options, attemptCount + 1); + }); + }, delay); + } + _handleSseStream(stream, options, isReconnectable) { + if (!stream) { + return; + } + const { onresumptiontoken, replayMessageId } = options; + let lastEventId; + const processStream = async () => { + var _a, _b, _c, _d; + // this is the closest we can get to trying to catch network errors + // if something happens reader will throw + try { + // Create a pipeline: binary stream -> text decoder -> SSE parser + const reader = stream + .pipeThrough(new TextDecoderStream()) + .pipeThrough(new stream_1.EventSourceParserStream()) + .getReader(); + while (true) { + const { value: event, done } = await reader.read(); + if (done) { + break; + } + // Update last event ID if provided + if (event.id) { + lastEventId = event.id; + onresumptiontoken === null || onresumptiontoken === void 0 ? void 0 : onresumptiontoken(event.id); + } + if (!event.event || event.event === 'message') { + try { + const message = types_js_1.JSONRPCMessageSchema.parse(JSON.parse(event.data)); + if (replayMessageId !== undefined && (0, types_js_1.isJSONRPCResponse)(message)) { + message.id = replayMessageId; + } + (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message); + } + catch (error) { + (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); + } + } + } + } + catch (error) { + // Handle stream errors - likely a network disconnect + (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, new Error(`SSE stream disconnected: ${error}`)); + // Attempt to reconnect if the stream disconnects unexpectedly and we aren't closing + if (isReconnectable && this._abortController && !this._abortController.signal.aborted) { + // Use the exponential backoff reconnection strategy + try { + this._scheduleReconnection({ + resumptionToken: lastEventId, + onresumptiontoken, + replayMessageId + }, 0); + } + catch (error) { + (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`)); + } + } + } + }; + processStream(); + } + async start() { + if (this._abortController) { + throw new Error('StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + this._abortController = new AbortController(); + } + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + async finishAuth(authorizationCode) { + if (!this._authProvider) { + throw new auth_js_1.UnauthorizedError('No auth provider'); + } + const result = await (0, auth_js_1.auth)(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError('Failed to authorize'); + } + } + async close() { + var _a, _b; + // Abort any pending requests + (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + (_b = this.onclose) === null || _b === void 0 ? void 0 : _b.call(this); + } + async send(message, options) { + var _a, _b, _c, _d; + try { + const { resumptionToken, onresumptiontoken } = options || {}; + if (resumptionToken) { + // If we have at last event ID, we need to reconnect the SSE stream + this._startOrAuthSse({ resumptionToken, replayMessageId: (0, types_js_1.isJSONRPCRequest)(message) ? message.id : undefined }).catch(err => { var _a; return (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, err); }); + return; + } + const headers = await this._commonHeaders(); + headers.set('content-type', 'application/json'); + headers.set('accept', 'application/json, text/event-stream'); + const init = { + ...this._requestInit, + method: 'POST', + headers, + body: JSON.stringify(message), + signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal + }; + const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._url, init); + // Handle session ID received during initialization + const sessionId = response.headers.get('mcp-session-id'); + if (sessionId) { + this._sessionId = sessionId; + } + if (!response.ok) { + if (response.status === 401 && this._authProvider) { + // Prevent infinite recursion when server returns 401 after successful auth + if (this._hasCompletedAuthFlow) { + throw new StreamableHTTPError(401, 'Server returned 401 after successful authentication'); + } + const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + const result = await (0, auth_js_1.auth)(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError(); + } + // Mark that we completed auth flow + this._hasCompletedAuthFlow = true; + // Purposely _not_ awaited, so we don't call onerror twice + return this.send(message); + } + if (response.status === 403 && this._authProvider) { + const { resourceMetadataUrl, scope, error } = (0, auth_js_1.extractWWWAuthenticateParams)(response); + if (error === 'insufficient_scope') { + const wwwAuthHeader = response.headers.get('WWW-Authenticate'); + // Check if we've already tried upscoping with this header to prevent infinite loops. + if (this._lastUpscopingHeader === wwwAuthHeader) { + throw new StreamableHTTPError(403, 'Server returned 403 after trying upscoping'); + } + if (scope) { + this._scope = scope; + } + if (resourceMetadataUrl) { + this._resourceMetadataUrl = resourceMetadataUrl; + } + // Mark that upscoping was tried. + this._lastUpscopingHeader = wwwAuthHeader !== null && wwwAuthHeader !== void 0 ? wwwAuthHeader : undefined; + const result = await (0, auth_js_1.auth)(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetch + }); + if (result !== 'AUTHORIZED') { + throw new auth_js_1.UnauthorizedError(); + } + return this.send(message); + } + } + const text = await response.text().catch(() => null); + throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); + } + // Reset auth loop flag on successful response + this._hasCompletedAuthFlow = false; + this._lastUpscopingHeader = undefined; + // If the response is 202 Accepted, there's no body to process + if (response.status === 202) { + // if the accepted notification is initialized, we start the SSE stream + // if it's supported by the server + if ((0, types_js_1.isInitializedNotification)(message)) { + // Start without a lastEventId since this is a fresh connection + this._startOrAuthSse({ resumptionToken: undefined }).catch(err => { var _a; return (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, err); }); + } + return; + } + // Get original message(s) for detecting request IDs + const messages = Array.isArray(message) ? message : [message]; + const hasRequests = messages.filter(msg => 'method' in msg && 'id' in msg && msg.id !== undefined).length > 0; + // Check the response type + const contentType = response.headers.get('content-type'); + if (hasRequests) { + if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('text/event-stream')) { + // Handle SSE stream responses for requests + // We use the same handler as standalone streams, which now supports + // reconnection with the last event ID + this._handleSseStream(response.body, { onresumptiontoken }, false); + } + else if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) { + // For non-streaming servers, we might get direct JSON responses + const data = await response.json(); + const responseMessages = Array.isArray(data) + ? data.map(msg => types_js_1.JSONRPCMessageSchema.parse(msg)) + : [types_js_1.JSONRPCMessageSchema.parse(data)]; + for (const msg of responseMessages) { + (_c = this.onmessage) === null || _c === void 0 ? void 0 : _c.call(this, msg); + } + } + else { + throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`); + } + } + } + catch (error) { + (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error); + throw error; + } + } + get sessionId() { + return this._sessionId; + } + /** + * Terminates the current session by sending a DELETE request to the server. + * + * Clients that no longer need a particular session + * (e.g., because the user is leaving the client application) SHOULD send an + * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly + * terminate the session. + * + * The server MAY respond with HTTP 405 Method Not Allowed, indicating that + * the server does not allow clients to terminate sessions. + */ + async terminateSession() { + var _a, _b, _c; + if (!this._sessionId) { + return; // No session to terminate + } + try { + const headers = await this._commonHeaders(); + const init = { + ...this._requestInit, + method: 'DELETE', + headers, + signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal + }; + const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._url, init); + // We specifically handle 405 as a valid response according to the spec, + // meaning the server does not support explicit session termination + if (!response.ok && response.status !== 405) { + throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`); + } + this._sessionId = undefined; + } + catch (error) { + (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error); + throw error; + } + } + setProtocolVersion(version) { + this._protocolVersion = version; + } + get protocolVersion() { + return this._protocolVersion; + } +} +exports.StreamableHTTPClientTransport = StreamableHTTPClientTransport; +//# sourceMappingURL=streamableHttp.js.map \ No newline at end of file diff --git a/dist/cjs/client/streamableHttp.js.map b/dist/cjs/client/streamableHttp.js.map new file mode 100644 index 0000000000..d48b32683f --- /dev/null +++ b/dist/cjs/client/streamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.js","sourceRoot":"","sources":["../../../src/client/streamableHttp.ts"],"names":[],"mappings":";;;AAAA,yDAAqG;AACrG,0CAAmI;AACnI,uCAAmH;AACnH,sDAAoE;AAEpE,8DAA8D;AAC9D,MAAM,4CAA4C,GAAsC;IACpF,wBAAwB,EAAE,IAAI;IAC9B,oBAAoB,EAAE,KAAK;IAC3B,2BAA2B,EAAE,GAAG;IAChC,UAAU,EAAE,CAAC;CAChB,CAAC;AAEF,MAAa,mBAAoB,SAAQ,KAAK;IAC1C,YACoB,IAAwB,EACxC,OAA2B;QAE3B,KAAK,CAAC,0BAA0B,OAAO,EAAE,CAAC,CAAC;QAH3B,SAAI,GAAJ,IAAI,CAAoB;IAI5C,CAAC;CACJ;AAPD,kDAOC;AAkGD;;;;GAIG;AACH,MAAa,6BAA6B;IAmBtC,YAAY,GAAQ,EAAE,IAA2C;;QAPzD,0BAAqB,G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IAAI,CAAC,UAAU,EAAE,CAAC;YACnB,OAAO,CAAC,0BAA0B;QACtC,CAAC;QAED,IAAI,CAAC;YACD,MAAM,OAAO,GAAG,MAAM,IAAI,CAAC,cAAc,EAAE,CAAC;YAE5C,MAAM,IAAI,GAAG;gBACT,GAAG,IAAI,CAAC,YAAY;gBACpB,MAAM,EAAE,QAAQ;gBAChB,OAAO;gBACP,MAAM,EAAE,MAAA,IAAI,CAAC,gBAAgB,0CAAE,MAAM;aACxC,CAAC;YAEF,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAA,IAAI,CAAC,MAAM,mCAAI,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAE/D,wEAAwE;YACxE,mEAAmE;YACnE,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;gBAC1C,MAAM,IAAI,mBAAmB,CAAC,QAAQ,CAAC,MAAM,EAAE,gCAAgC,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC;YAC1G,CAAC;YAED,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAChC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,MAAA,IAAI,CAAC,OAAO,qDAAG,KAAc,CAAC,CAAC;YAC/B,MAAM,KAAK,CAAC;QAChB,CAAC;IACL,CAAC;IAED,kBAAkB,CAAC,OAAe;QAC9B,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;IACpC,CAAC;IACD,IAAI,eAAe;QACf,OAAO,IAAI,CAAC,gBAAgB,CAAC;IACjC,CAAC;CACJ;AAxdD,sEAwdC"} \ No newline at end of file diff --git a/dist/cjs/client/websocket.d.ts b/dist/cjs/client/websocket.d.ts new file mode 100644 index 0000000000..78f95de3b9 --- /dev/null +++ b/dist/cjs/client/websocket.d.ts @@ -0,0 +1,17 @@ +import { Transport } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +/** + * Client transport for WebSocket: this will connect to a server over the WebSocket protocol. + */ +export declare class WebSocketClientTransport implements Transport { + private _socket?; + private _url; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(url: URL); + start(): Promise; + close(): Promise; + send(message: JSONRPCMessage): Promise; +} +//# sourceMappingURL=websocket.d.ts.map \ No newline at end of file diff --git a/dist/cjs/client/websocket.d.ts.map b/dist/cjs/client/websocket.d.ts.map new file mode 100644 index 0000000000..2882d98226 --- /dev/null +++ b/dist/cjs/client/websocket.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../../../src/client/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AAInE;;GAEG;AACH,qBAAa,wBAAyB,YAAW,SAAS;IACtD,OAAO,CAAC,OAAO,CAAC,CAAY;IAC5B,OAAO,CAAC,IAAI,CAAM;IAElB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,GAAG,EAAE,GAAG;IAIpB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAsChB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAW/C"} \ No newline at end of file diff --git a/dist/cjs/client/websocket.js b/dist/cjs/client/websocket.js new file mode 100644 index 0000000000..e2c94d0651 --- /dev/null +++ b/dist/cjs/client/websocket.js @@ -0,0 +1,63 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WebSocketClientTransport = void 0; +const types_js_1 = require("../types.js"); +const SUBPROTOCOL = 'mcp'; +/** + * Client transport for WebSocket: this will connect to a server over the WebSocket protocol. + */ +class WebSocketClientTransport { + constructor(url) { + this._url = url; + } + start() { + if (this._socket) { + throw new Error('WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + return new Promise((resolve, reject) => { + this._socket = new WebSocket(this._url, SUBPROTOCOL); + this._socket.onerror = event => { + var _a; + const error = 'error' in event ? event.error : new Error(`WebSocket error: ${JSON.stringify(event)}`); + reject(error); + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }; + this._socket.onopen = () => { + resolve(); + }; + this._socket.onclose = () => { + var _a; + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + }; + this._socket.onmessage = (event) => { + var _a, _b; + let message; + try { + message = types_js_1.JSONRPCMessageSchema.parse(JSON.parse(event.data)); + } + catch (error) { + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + return; + } + (_b = this.onmessage) === null || _b === void 0 ? void 0 : _b.call(this, message); + }; + }); + } + async close() { + var _a; + (_a = this._socket) === null || _a === void 0 ? void 0 : _a.close(); + } + send(message) { + return new Promise((resolve, reject) => { + var _a; + if (!this._socket) { + reject(new Error('Not connected')); + return; + } + (_a = this._socket) === null || _a === void 0 ? void 0 : _a.send(JSON.stringify(message)); + resolve(); + }); + } +} +exports.WebSocketClientTransport = WebSocketClientTransport; +//# sourceMappingURL=websocket.js.map \ No newline at end of file diff --git a/dist/cjs/client/websocket.js.map b/dist/cjs/client/websocket.js.map new file mode 100644 index 0000000000..4094d2a22b --- /dev/null +++ b/dist/cjs/client/websocket.js.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket.js","sourceRoot":"","sources":["../../../src/client/websocket.ts"],"names":[],"mappings":";;;AACA,0CAAmE;AAEnE,MAAM,WAAW,GAAG,KAAK,CAAC;AAE1B;;GAEG;AACH,MAAa,wBAAwB;IAQjC,YAAY,GAAQ;QAChB,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;I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O,CAAC,CAAC;YAC9B,CAAC,CAAC;QACN,CAAC,CAAC,CAAC;IACP,CAAC;IAED,KAAK,CAAC,KAAK;;QACP,MAAA,IAAI,CAAC,OAAO,0CAAE,KAAK,EAAE,CAAC;IAC1B,CAAC;IAED,IAAI,CAAC,OAAuB;QACxB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;;YACnC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;gBAChB,MAAM,CAAC,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC,CAAC;gBACnC,OAAO;YACX,CAAC;YAED,MAAA,IAAI,CAAC,OAAO,0CAAE,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;YAC5C,OAAO,EAAE,CAAC;QACd,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAjED,4DAiEC"} \ No newline at end of file diff --git a/dist/cjs/examples/client/elicitationUrlExample.d.ts b/dist/cjs/examples/client/elicitationUrlExample.d.ts new file mode 100644 index 0000000000..611f6eba22 --- /dev/null +++ b/dist/cjs/examples/client/elicitationUrlExample.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=elicitationUrlExample.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/client/elicitationUrlExample.d.ts.map b/dist/cjs/examples/client/elicitationUrlExample.d.ts.map new file mode 100644 index 0000000000..e749adfb95 --- /dev/null +++ b/dist/cjs/examples/client/elicitationUrlExample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/elicitationUrlExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/client/elicitationUrlExample.js b/dist/cjs/examples/client/elicitationUrlExample.js new file mode 100644 index 0000000000..fac53f0489 --- /dev/null +++ b/dist/cjs/examples/client/elicitationUrlExample.js @@ -0,0 +1,693 @@ +"use strict"; +// Run with: npx tsx src/examples/client/elicitationUrlExample.ts +// +// This example demonstrates how to use URL elicitation to securely +// collect user input in a remote (HTTP) server. +// URL elicitation allows servers to prompt the end-user to open a URL in their browser +// to collect sensitive information. +Object.defineProperty(exports, "__esModule", { value: true }); +const index_js_1 = require("../../client/index.js"); +const streamableHttp_js_1 = require("../../client/streamableHttp.js"); +const node_readline_1 = require("node:readline"); +const types_js_1 = require("../../types.js"); +const metadataUtils_js_1 = require("../../shared/metadataUtils.js"); +const node_child_process_1 = require("node:child_process"); +const simpleOAuthClientProvider_js_1 = require("./simpleOAuthClientProvider.js"); +const auth_js_1 = require("../../client/auth.js"); +const node_http_1 = require("node:http"); +// Set up OAuth (required for this example) +const OAUTH_CALLBACK_PORT = 8090; // Use different port than auth server (3001) +const OAUTH_CALLBACK_URL = `http://localhost:${OAUTH_CALLBACK_PORT}/callback`; +let oauthProvider = undefined; +console.log('Getting OAuth token...'); +const clientMetadata = { + client_name: 'Elicitation MCP Client', + redirect_uris: [OAUTH_CALLBACK_URL], + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + token_endpoint_auth_method: 'client_secret_post', + scope: 'mcp:tools' +}; +oauthProvider = new simpleOAuthClientProvider_js_1.InMemoryOAuthClientProvider(OAUTH_CALLBACK_URL, clientMetadata, (redirectUrl) => { + console.log(`🌐 Opening browser for OAuth redirect: ${redirectUrl.toString()}`); + openBrowser(redirectUrl.toString()); +}); +// Create readline interface for user input +const readline = (0, node_readline_1.createInterface)({ + input: process.stdin, + output: process.stdout +}); +let abortCommand = new AbortController(); +// Global client and transport for interactive commands +let client = null; +let transport = null; +let serverUrl = 'http://localhost:3000/mcp'; +let sessionId = undefined; +let isProcessingCommand = false; +let isProcessingElicitations = false; +const elicitationQueue = []; +let elicitationQueueSignal = null; +let elicitationsCompleteSignal = null; +// Map to track pending URL elicitations waiting for completion notifications +const pendingURLElicitations = new Map(); +async function main() { + console.log('MCP Interactive Client'); + console.log('====================='); + // Connect to server immediately with default settings + await connect(); + // Start the elicitation loop in the background + elicitationLoop().catch(error => { + console.error('Unexpected error in elicitation loop:', error); + process.exit(1); + }); + // Short delay allowing the server to send any SSE elicitations on connection + await new Promise(resolve => setTimeout(resolve, 200)); + // Wait until we are done processing any initial elicitations + await waitForElicitationsToComplete(); + // Print help and start the command loop + printHelp(); + await commandLoop(); +} +async function waitForElicitationsToComplete() { + // Wait until the queue is empty and nothing is being processed + while (elicitationQueue.length > 0 || isProcessingElicitations) { + await new Promise(resolve => setTimeout(resolve, 100)); + } +} +function printHelp() { + console.log('\nAvailable commands:'); + console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)'); + console.log(' disconnect - Disconnect from server'); + console.log(' terminate-session - Terminate the current session'); + console.log(' reconnect - Reconnect to the server'); + console.log(' list-tools - List available tools'); + console.log(' call-tool [args] - Call a tool with optional JSON arguments'); + console.log(' payment-confirm - Test URL elicitation via error response with payment-confirm tool'); + console.log(' third-party-auth - Test tool that requires third-party OAuth credentials'); + console.log(' help - Show this help'); + console.log(' quit - Exit the program'); +} +async function commandLoop() { + await new Promise(resolve => { + if (!isProcessingElicitations) { + resolve(); + } + else { + elicitationsCompleteSignal = resolve; + } + }); + readline.question('\n> ', { signal: abortCommand.signal }, async (input) => { + var _a; + isProcessingCommand = true; + const args = input.trim().split(/\s+/); + const command = (_a = args[0]) === null || _a === void 0 ? void 0 : _a.toLowerCase(); + try { + switch (command) { + case 'connect': + await connect(args[1]); + break; + case 'disconnect': + await disconnect(); + break; + case 'terminate-session': + await terminateSession(); + break; + case 'reconnect': + await reconnect(); + break; + case 'list-tools': + await listTools(); + break; + case 'call-tool': + if (args.length < 2) { + console.log('Usage: call-tool [args]'); + } + else { + const toolName = args[1]; + let toolArgs = {}; + if (args.length > 2) { + try { + toolArgs = JSON.parse(args.slice(2).join(' ')); + } + catch (_b) { + console.log('Invalid JSON arguments. Using empty args.'); + } + } + await callTool(toolName, toolArgs); + } + break; + case 'payment-confirm': + await callPaymentConfirmTool(); + break; + case 'third-party-auth': + await callThirdPartyAuthTool(); + break; + case 'help': + printHelp(); + break; + case 'quit': + case 'exit': + await cleanup(); + return; + default: + if (command) { + console.log(`Unknown command: ${command}`); + } + break; + } + } + catch (error) { + console.error(`Error executing command: ${error}`); + } + finally { + isProcessingCommand = false; + } + // Process another command after we've processed the this one + await commandLoop(); + }); +} +async function elicitationLoop() { + while (true) { + // Wait until we have elicitations to process + await new Promise(resolve => { + if (elicitationQueue.length > 0) { + resolve(); + } + else { + elicitationQueueSignal = resolve; + } + }); + isProcessingElicitations = true; + abortCommand.abort(); // Abort the command loop if it's running + // Process all queued elicitations + while (elicitationQueue.length > 0) { + const queued = elicitationQueue.shift(); + console.log(`📤 Processing queued elicitation (${elicitationQueue.length} remaining)`); + try { + const result = await handleElicitationRequest(queued.request); + queued.resolve(result); + } + catch (error) { + queued.reject(error instanceof Error ? error : new Error(String(error))); + } + } + console.log('✅ All queued elicitations processed. Resuming command loop...\n'); + isProcessingElicitations = false; + // Reset the abort controller for the next command loop + abortCommand = new AbortController(); + // Resume the command loop + if (elicitationsCompleteSignal) { + elicitationsCompleteSignal(); + elicitationsCompleteSignal = null; + } + } +} +async function openBrowser(url) { + const command = `open "${url}"`; + (0, node_child_process_1.exec)(command, error => { + if (error) { + console.error(`Failed to open browser: ${error.message}`); + console.log(`Please manually open: ${url}`); + } + }); +} +/** + * Enqueues an elicitation request and returns the result. + * + * This function is used so that our CLI (which can only handle one input request at a time) + * can handle elicitation requests and the command loop. + * + * @param request - The elicitation request to be handled + * @returns The elicitation result + */ +async function elicitationRequestHandler(request) { + // If we are processing a command, handle this elicitation immediately + if (isProcessingCommand) { + console.log('📋 Processing elicitation immediately (during command execution)'); + return await handleElicitationRequest(request); + } + // Otherwise, queue the request to be handled by the elicitation loop + console.log(`📥 Queueing elicitation request (queue size will be: ${elicitationQueue.length + 1})`); + return new Promise((resolve, reject) => { + elicitationQueue.push({ + request, + resolve, + reject + }); + // Signal the elicitation loop that there's work to do + if (elicitationQueueSignal) { + elicitationQueueSignal(); + elicitationQueueSignal = null; + } + }); +} +/** + * Handles an elicitation request. + * + * This function is used to handle the elicitation request and return the result. + * + * @param request - The elicitation request to be handled + * @returns The elicitation result + */ +async function handleElicitationRequest(request) { + const mode = request.params.mode; + console.log('\n🔔 Elicitation Request Received:'); + console.log(`Mode: ${mode}`); + if (mode === 'url') { + return { + action: await handleURLElicitation(request.params) + }; + } + else { + // Should not happen because the client declares its capabilities to the server, + // but being defensive is a good practice: + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Unsupported elicitation mode: ${mode}`); + } +} +/** + * Handles a URL elicitation by opening the URL in the browser. + * + * Note: This is a shared code for both request handlers and error handlers. + * As a result of sharing schema, there is no big forking of logic for the client. + * + * @param params - The URL elicitation request parameters + * @returns The action to take (accept, cancel, or decline) + */ +async function handleURLElicitation(params) { + const url = params.url; + const elicitationId = params.elicitationId; + const message = params.message; + console.log(`🆔 Elicitation ID: ${elicitationId}`); // Print for illustration + // Parse URL to show domain for security + let domain = 'unknown domain'; + try { + const parsedUrl = new URL(url); + domain = parsedUrl.hostname; + } + catch (_a) { + console.error('Invalid URL provided by server'); + return 'decline'; + } + // Example security warning to help prevent phishing attacks + console.log('\n⚠️ \x1b[33mSECURITY WARNING\x1b[0m ⚠️'); + console.log('\x1b[33mThe server is requesting you to open an external URL.\x1b[0m'); + console.log('\x1b[33mOnly proceed if you trust this server and understand why it needs this.\x1b[0m\n'); + console.log(`🌐 Target domain: \x1b[36m${domain}\x1b[0m`); + console.log(`🔗 Full URL: \x1b[36m${url}\x1b[0m`); + console.log(`\nℹ️ Server's reason:\n\n\x1b[36m${message}\x1b[0m\n`); + // 1. Ask for user consent to open the URL + const consent = await new Promise(resolve => { + readline.question('\nDo you want to open this URL in your browser? (y/n): ', input => { + resolve(input.trim().toLowerCase()); + }); + }); + // 2. If user did not consent, return appropriate result + if (consent === 'no' || consent === 'n') { + console.log('❌ URL navigation declined.'); + return 'decline'; + } + else if (consent !== 'yes' && consent !== 'y') { + console.log('🚫 Invalid response. Cancelling elicitation.'); + return 'cancel'; + } + // 3. Wait for completion notification in the background + const completionPromise = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + pendingURLElicitations.delete(elicitationId); + console.log(`\x1b[31m❌ Elicitation ${elicitationId} timed out waiting for completion.\x1b[0m`); + reject(new Error('Elicitation completion timeout')); + }, 5 * 60 * 1000); // 5 minute timeout + pendingURLElicitations.set(elicitationId, { + resolve: () => { + clearTimeout(timeout); + resolve(); + }, + reject, + timeout + }); + }); + completionPromise.catch(error => { + console.error('Background completion wait failed:', error); + }); + // 4. Open the URL in the browser + console.log(`\n🚀 Opening browser to: ${url}`); + await openBrowser(url); + console.log('\n⏳ Waiting for you to complete the interaction in your browser...'); + console.log(' The server will send a notification once you complete the action.'); + // 5. Acknowledge the user accepted the elicitation + return 'accept'; +} +/** + * Example OAuth callback handler - in production, use a more robust approach + * for handling callbacks and storing tokens + */ +/** + * Starts a temporary HTTP server to receive the OAuth callback + */ +async function waitForOAuthCallback() { + return new Promise((resolve, reject) => { + const server = (0, node_http_1.createServer)((req, res) => { + // Ignore favicon requests + if (req.url === '/favicon.ico') { + res.writeHead(404); + res.end(); + return; + } + console.log(`📥 Received callback: ${req.url}`); + const parsedUrl = new URL(req.url || '', 'http://localhost'); + const code = parsedUrl.searchParams.get('code'); + const error = parsedUrl.searchParams.get('error'); + if (code) { + console.log(`✅ Authorization code received: ${code === null || code === void 0 ? void 0 : code.substring(0, 10)}...`); + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Successful!

+

This simulates successful authorization of the MCP client, which now has an access token for the MCP server.

+

This window will close automatically in 10 seconds.

+ + + + `); + resolve(code); + setTimeout(() => server.close(), 15000); + } + else if (error) { + console.log(`❌ Authorization error: ${error}`); + res.writeHead(400, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Failed

+

Error: ${error}

+ + + `); + reject(new Error(`OAuth authorization failed: ${error}`)); + } + else { + console.log(`❌ No authorization code or error in callback`); + res.writeHead(400); + res.end('Bad request'); + reject(new Error('No authorization code provided')); + } + }); + server.listen(OAUTH_CALLBACK_PORT, () => { + console.log(`OAuth callback server started on http://localhost:${OAUTH_CALLBACK_PORT}`); + }); + }); +} +/** + * Attempts to connect to the MCP server with OAuth authentication. + * Handles OAuth flow recursively if authorization is required. + */ +async function attemptConnection(oauthProvider) { + console.log('🚢 Creating transport with OAuth provider...'); + const baseUrl = new URL(serverUrl); + transport = new streamableHttp_js_1.StreamableHTTPClientTransport(baseUrl, { + sessionId: sessionId, + authProvider: oauthProvider + }); + console.log('🚢 Transport created'); + try { + console.log('🔌 Attempting connection (this will trigger OAuth redirect if needed)...'); + await client.connect(transport); + sessionId = transport.sessionId; + console.log('Transport created with session ID:', sessionId); + console.log('✅ Connected successfully'); + } + catch (error) { + if (error instanceof auth_js_1.UnauthorizedError) { + console.log('🔐 OAuth required - waiting for authorization...'); + const callbackPromise = waitForOAuthCallback(); + const authCode = await callbackPromise; + await transport.finishAuth(authCode); + console.log('🔐 Authorization code received:', authCode); + console.log('🔌 Reconnecting with authenticated transport...'); + // Recursively retry connection after OAuth completion + await attemptConnection(oauthProvider); + } + else { + console.error('❌ Connection failed with non-auth error:', error); + throw error; + } + } +} +async function connect(url) { + if (client) { + console.log('Already connected. Disconnect first.'); + return; + } + if (url) { + serverUrl = url; + } + console.log(`🔗 Attempting to connect to ${serverUrl}...`); + // Create a new client with elicitation capability + console.log('👤 Creating MCP client...'); + client = new index_js_1.Client({ + name: 'example-client', + version: '1.0.0' + }, { + capabilities: { + elicitation: { + // Only URL elicitation is supported in this demo + // (see server/elicitationExample.ts for a demo of form mode elicitation) + url: {} + } + } + }); + console.log('👤 Client created'); + // Set up elicitation request handler with proper validation + client.setRequestHandler(types_js_1.ElicitRequestSchema, elicitationRequestHandler); + // Set up notification handler for elicitation completion + client.setNotificationHandler(types_js_1.ElicitationCompleteNotificationSchema, notification => { + const { elicitationId } = notification.params; + const pending = pendingURLElicitations.get(elicitationId); + if (pending) { + clearTimeout(pending.timeout); + pendingURLElicitations.delete(elicitationId); + console.log(`\x1b[32m✅ Elicitation ${elicitationId} completed!\x1b[0m`); + pending.resolve(); + } + else { + // Shouldn't happen - discard it! + console.warn(`Received completion notification for unknown elicitation: ${elicitationId}`); + } + }); + try { + console.log('🔐 Starting OAuth flow...'); + await attemptConnection(oauthProvider); + console.log('Connected to MCP server'); + // Set up error handler after connection is established so we don't double log errors + client.onerror = error => { + console.error('\x1b[31mClient error:', error, '\x1b[0m'); + }; + } + catch (error) { + console.error('Failed to connect:', error); + client = null; + transport = null; + return; + } +} +async function disconnect() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + await transport.close(); + console.log('Disconnected from MCP server'); + client = null; + transport = null; + } + catch (error) { + console.error('Error disconnecting:', error); + } +} +async function terminateSession() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + console.log('Terminating session with ID:', transport.sessionId); + await transport.terminateSession(); + console.log('Session terminated successfully'); + // Check if sessionId was cleared after termination + if (!transport.sessionId) { + console.log('Session ID has been cleared'); + sessionId = undefined; + // Also close the transport and clear client objects + await transport.close(); + console.log('Transport closed after session termination'); + client = null; + transport = null; + } + else { + console.log('Server responded with 405 Method Not Allowed (session termination not supported)'); + console.log('Session ID is still active:', transport.sessionId); + } + } + catch (error) { + console.error('Error terminating session:', error); + } +} +async function reconnect() { + if (client) { + await disconnect(); + } + await connect(); +} +async function listTools() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - id: ${tool.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(tool)}, description: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server (${error})`); + } +} +async function callTool(name, args) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const request = { + method: 'tools/call', + params: { + name, + arguments: args + } + }; + console.log(`Calling tool '${name}' with args:`, args); + const result = await client.request(request, types_js_1.CallToolResultSchema); + console.log('Tool result:'); + const resourceLinks = []; + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else if (item.type === 'resource_link') { + const resourceLink = item; + resourceLinks.push(resourceLink); + console.log(` 📁 Resource Link: ${resourceLink.name}`); + console.log(` URI: ${resourceLink.uri}`); + if (resourceLink.mimeType) { + console.log(` Type: ${resourceLink.mimeType}`); + } + if (resourceLink.description) { + console.log(` Description: ${resourceLink.description}`); + } + } + else if (item.type === 'resource') { + console.log(` [Embedded Resource: ${item.resource.uri}]`); + } + else if (item.type === 'image') { + console.log(` [Image: ${item.mimeType}]`); + } + else if (item.type === 'audio') { + console.log(` [Audio: ${item.mimeType}]`); + } + else { + console.log(` [Unknown content type]:`, item); + } + }); + // Offer to read resource links + if (resourceLinks.length > 0) { + console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource ' to read their content.`); + } + } + catch (error) { + if (error instanceof types_js_1.UrlElicitationRequiredError) { + console.log('\n🔔 Elicitation Required Error Received:'); + console.log(`Message: ${error.message}`); + for (const e of error.elicitations) { + await handleURLElicitation(e); // For the error handler, we discard the action result because we don't respond to an error response + } + return; + } + console.log(`Error calling tool ${name}: ${error}`); + } +} +async function cleanup() { + if (client && transport) { + try { + // First try to terminate the session gracefully + if (transport.sessionId) { + try { + console.log('Terminating session before exit...'); + await transport.terminateSession(); + console.log('Session terminated successfully'); + } + catch (error) { + console.error('Error terminating session:', error); + } + } + // Then close the transport + await transport.close(); + } + catch (error) { + console.error('Error closing transport:', error); + } + } + process.stdin.setRawMode(false); + readline.close(); + console.log('\nGoodbye!'); + process.exit(0); +} +async function callPaymentConfirmTool() { + console.log('Calling payment-confirm tool...'); + await callTool('payment-confirm', { cartId: 'cart_123' }); +} +async function callThirdPartyAuthTool() { + console.log('Calling third-party-auth tool...'); + await callTool('third-party-auth', { param1: 'test' }); +} +// Set up raw mode for keyboard input to capture Escape key +process.stdin.setRawMode(true); +process.stdin.on('data', async (data) => { + // Check for Escape key (27) + if (data.length === 1 && data[0] === 27) { + console.log('\nESC key pressed. Disconnecting from server...'); + // Abort current operation and disconnect from server + if (client && transport) { + await disconnect(); + console.log('Disconnected. Press Enter to continue.'); + } + else { + console.log('Not connected to server.'); + } + // Re-display the prompt + process.stdout.write('> '); + } +}); +// Handle Ctrl+C +process.on('SIGINT', async () => { + console.log('\nReceived SIGINT. Cleaning up...'); + await cleanup(); +}); +// Start the interactive client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=elicitationUrlExample.js.map \ No newline at end of file diff --git a/dist/cjs/examples/client/elicitationUrlExample.js.map b/dist/cjs/examples/client/elicitationUrlExample.js.map new file mode 100644 index 0000000000..b17808ca78 --- /dev/null +++ b/dist/cjs/examples/client/elicitationUrlExample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.js","sourceRoot":"","sources":["../../../../src/examples/client/elicitationUrlExample.ts"],"names":[],"mappings":";AAAA,iEAAiE;AACjE,EAAE;AACF,mEAAmE;AACnE,gDAAgD;AAChD,uFAAuF;AACvF,oCAAoC;;AAEpC,oDAA+C;AAC/C,sEAA+E;AAC/E,iDAAgD;AAChD,6CAcwB;AACxB,oEAA+D;AAE/D,2DAA0C;AAC1C,iFAA6E;AAC7E,kDAAyD;AACzD,yCAAyC;AAEzC,2CAA2C;AAC3C,MAAM,mBAAmB,GAAG,IAAI,CAAC,CAAC,6CAA6C;AAC/E,MAAM,kBAAkB,GAAG,oBAAoB,mBAAmB,WAAW,CAAC;AAC9E,IAAI,aAAa,GAA4C,SAAS,CAAC;AAEvE,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;AACtC,MAAM,cAAc,GAAwB;IACxC,WAAW,EAAE,wBAAwB;IACrC,aAAa,EAAE,CAAC,kBAAkB,CAAC;IACnC,W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CAAC,CAAC;AAC3D,CAAC;AAED,2DAA2D;AAC3D,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAC/B,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,EAAC,IAAI,EAAC,EAAE;IAClC,4BAA4B;IAC5B,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;QACtC,OAAO,CAAC,GAAG,CAAC,iDAAiD,CAAC,CAAC;QAE/D,qDAAqD;QACrD,IAAI,MAAM,IAAI,SAAS,EAAE,CAAC;YACtB,MAAM,UAAU,EAAE,CAAC;YACnB,OAAO,CAAC,GAAG,CAAC,wCAAwC,CAAC,CAAC;QAC1D,CAAC;aAAM,CAAC;YACJ,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;QAC5C,CAAC;QAED,wBAAwB;QACxB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,gBAAgB;AAChB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;IACjD,MAAM,OAAO,EAAE,CAAC;AACpB,CAAC,CAAC,CAAC;AAEH,+BAA+B;AAC/B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/client/multipleClientsParallel.d.ts b/dist/cjs/examples/client/multipleClientsParallel.d.ts new file mode 100644 index 0000000000..0ac5af8e56 --- /dev/null +++ b/dist/cjs/examples/client/multipleClientsParallel.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=multipleClientsParallel.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/client/multipleClientsParallel.d.ts.map b/dist/cjs/examples/client/multipleClientsParallel.d.ts.map new file mode 100644 index 0000000000..91051dc946 --- /dev/null +++ b/dist/cjs/examples/client/multipleClientsParallel.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"multipleClientsParallel.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/multipleClientsParallel.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/client/multipleClientsParallel.js b/dist/cjs/examples/client/multipleClientsParallel.js new file mode 100644 index 0000000000..5cfbb2f4d5 --- /dev/null +++ b/dist/cjs/examples/client/multipleClientsParallel.js @@ -0,0 +1,134 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const index_js_1 = require("../../client/index.js"); +const streamableHttp_js_1 = require("../../client/streamableHttp.js"); +const types_js_1 = require("../../types.js"); +/** + * Multiple Clients MCP Example + * + * This client demonstrates how to: + * 1. Create multiple MCP clients in parallel + * 2. Each client calls a single tool + * 3. Track notifications from each client independently + */ +// Command line args processing +const args = process.argv.slice(2); +const serverUrl = args[0] || 'http://localhost:3000/mcp'; +async function createAndRunClient(config) { + console.log(`[${config.id}] Creating client: ${config.name}`); + const client = new index_js_1.Client({ + name: config.name, + version: '1.0.0' + }); + const transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(serverUrl)); + // Set up client-specific error handler + client.onerror = error => { + console.error(`[${config.id}] Client error:`, error); + }; + // Set up client-specific notification handler + client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => { + console.log(`[${config.id}] Notification: ${notification.params.data}`); + }); + try { + // Connect to the server + await client.connect(transport); + console.log(`[${config.id}] Connected to MCP server`); + // Call the specified tool + console.log(`[${config.id}] Calling tool: ${config.toolName}`); + const toolRequest = { + method: 'tools/call', + params: { + name: config.toolName, + arguments: { + ...config.toolArguments, + // Add client ID to arguments for identification in notifications + caller: config.id + } + } + }; + const result = await client.request(toolRequest, types_js_1.CallToolResultSchema); + console.log(`[${config.id}] Tool call completed`); + // Keep the connection open for a bit to receive notifications + await new Promise(resolve => setTimeout(resolve, 5000)); + // Disconnect + await transport.close(); + console.log(`[${config.id}] Disconnected from MCP server`); + return { id: config.id, result }; + } + catch (error) { + console.error(`[${config.id}] Error:`, error); + throw error; + } +} +async function main() { + console.log('MCP Multiple Clients Example'); + console.log('============================'); + console.log(`Server URL: ${serverUrl}`); + console.log(''); + try { + // Define client configurations + const clientConfigs = [ + { + id: 'client1', + name: 'basic-client-1', + toolName: 'start-notification-stream', + toolArguments: { + interval: 3, // 1 second between notifications + count: 5 // Send 5 notifications + } + }, + { + id: 'client2', + name: 'basic-client-2', + toolName: 'start-notification-stream', + toolArguments: { + interval: 2, // 2 seconds between notifications + count: 3 // Send 3 notifications + } + }, + { + id: 'client3', + name: 'basic-client-3', + toolName: 'start-notification-stream', + toolArguments: { + interval: 1, // 0.5 second between notifications + count: 8 // Send 8 notifications + } + } + ]; + // Start all clients in parallel + console.log(`Starting ${clientConfigs.length} clients in parallel...`); + console.log(''); + const clientPromises = clientConfigs.map(config => createAndRunClient(config)); + const results = await Promise.all(clientPromises); + // Display results from all clients + console.log('\n=== Final Results ==='); + results.forEach(({ id, result }) => { + console.log(`\n[${id}] Tool result:`); + if (Array.isArray(result.content)) { + result.content.forEach((item) => { + if (item.type === 'text' && item.text) { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + else { + console.log(` Unexpected result format:`, result); + } + }); + console.log('\n=== All clients completed successfully ==='); + } + catch (error) { + console.error('Error running multiple clients:', error); + process.exit(1); + } +} +// Start the example +main().catch((error) => { + console.error('Error running MCP multiple clients example:', error); + process.exit(1); +}); +//# sourceMappingURL=multipleClientsParallel.js.map \ No newline at end of file diff --git a/dist/cjs/examples/client/multipleClientsParallel.js.map b/dist/cjs/examples/client/multipleClientsParallel.js.map new file mode 100644 index 0000000000..05812d11ad --- /dev/null +++ b/dist/cjs/examples/client/multipleClientsParallel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"multipleClientsParallel.js","sourceRoot":"","sources":["../../../../src/examples/client/multipleClientsParallel.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,sEAA+E;AAC/E,6CAAyH;AAEzH;;;;;;;GAOG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AASzD,KAAK,UAAU,kBAAkB,CAAC,MAAoB;IAClD,OAAO,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,EAAE,sBAAsB,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;IAE9D,MAAM,MAAM,GAAG,IAAI,iBAAM,CAAC;QACtB,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,OAAO,EAAE,OAAO;KACnB,CAAC,CAAC;IAEH,MAAM,SAAS,GAAG,IAAI,iDAA6B,CAAC,IAAI,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC;IAExE,uCAAuC;IACvC,MAAM,CAAC,OAAO,GAAG,KAAK,CAAC,EAAE;QACrB,OAAO,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,EAAE,iBAAiB,EAAE,KAAK,CAAC,CAAC;IACzD,CAAC,CAAC;IAEF,8CAA8C;IAC9C,MAAM,CAAC,sBAAsB,CAAC,2CAAgC,EAAE,YAAY,CAAC,EAAE;QAC3E,OAAO,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,EAAE,mBAAmB,YAAY,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;IAC5E,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC;QACD,wBAAwB;QACxB,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QAChC,OAA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AAM,EAAE,gBAAgB,CAAC,CAAC;YACtC,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC;gBAChC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,IAAqC,EAAE,EAAE;oBAC7D,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;wBACpC,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;oBAClC,CAAC;yBAAM,CAAC;wBACJ,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,WAAW,EAAE,IAAI,CAAC,CAAC;oBACjD,CAAC;gBACL,CAAC,CAAC,CAAC;YACP,CAAC;iBAAM,CAAC;gBACJ,OAAO,CAAC,GAAG,CAAC,6BAA6B,EAAE,MAAM,CAAC,CAAC;YACvD,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,GAAG,CAAC,8CAA8C,CAAC,CAAC;IAChE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;QACxD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;AACL,CAAC;AAED,oBAAoB;AACpB,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,6CAA6C,EAAE,KAAK,CAAC,CAAC;IACpE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/client/parallelToolCallsClient.d.ts b/dist/cjs/examples/client/parallelToolCallsClient.d.ts new file mode 100644 index 0000000000..e93d4d69d2 --- /dev/null +++ b/dist/cjs/examples/client/parallelToolCallsClient.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=parallelToolCallsClient.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/client/parallelToolCallsClient.d.ts.map b/dist/cjs/examples/client/parallelToolCallsClient.d.ts.map new file mode 100644 index 0000000000..25a3b820cf --- /dev/null +++ b/dist/cjs/examples/client/parallelToolCallsClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parallelToolCallsClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/parallelToolCallsClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/client/parallelToolCallsClient.js b/dist/cjs/examples/client/parallelToolCallsClient.js new file mode 100644 index 0000000000..e5a9829e9e --- /dev/null +++ b/dist/cjs/examples/client/parallelToolCallsClient.js @@ -0,0 +1,176 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const index_js_1 = require("../../client/index.js"); +const streamableHttp_js_1 = require("../../client/streamableHttp.js"); +const types_js_1 = require("../../types.js"); +/** + * Parallel Tool Calls MCP Client + * + * This client demonstrates how to: + * 1. Start multiple tool calls in parallel + * 2. Track notifications from each tool call using a caller parameter + */ +// Command line args processing +const args = process.argv.slice(2); +const serverUrl = args[0] || 'http://localhost:3000/mcp'; +async function main() { + console.log('MCP Parallel Tool Calls Client'); + console.log('=============================='); + console.log(`Connecting to server at: ${serverUrl}`); + let client; + let transport; + try { + // Create client with streamable HTTP transport + client = new index_js_1.Client({ + name: 'parallel-tool-calls-client', + version: '1.0.0' + }); + client.onerror = error => { + console.error('Client error:', error); + }; + // Connect to the server + transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(serverUrl)); + await client.connect(transport); + console.log('Successfully connected to MCP server'); + // Set up notification handler with caller identification + client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => { + console.log(`Notification: ${notification.params.data}`); + }); + console.log('List tools'); + const toolsRequest = await listTools(client); + console.log('Tools: ', toolsRequest); + // 2. Start multiple notification tools in parallel + console.log('\n=== Starting Multiple Notification Streams in Parallel ==='); + const toolResults = await startParallelNotificationTools(client); + // Log the results from each tool call + for (const [caller, result] of Object.entries(toolResults)) { + console.log(`\n=== Tool result for ${caller} ===`); + result.content.forEach((item) => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + // 3. Wait for all notifications (10 seconds) + console.log('\n=== Waiting for all notifications ==='); + await new Promise(resolve => setTimeout(resolve, 10000)); + // 4. Disconnect + console.log('\n=== Disconnecting ==='); + await transport.close(); + console.log('Disconnected from MCP server'); + } + catch (error) { + console.error('Error running client:', error); + process.exit(1); + } +} +/** + * List available tools on the server + */ +async function listTools(client) { + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - ${tool.name}: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server: ${error}`); + } +} +/** + * Start multiple notification tools in parallel with different configurations + * Each tool call includes a caller parameter to identify its notifications + */ +async function startParallelNotificationTools(client) { + try { + // Define multiple tool calls with different configurations + const toolCalls = [ + { + caller: 'fast-notifier', + request: { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 2, // 0.5 second between notifications + count: 10, // Send 10 notifications + caller: 'fast-notifier' // Identify this tool call + } + } + } + }, + { + caller: 'slow-notifier', + request: { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 5, // 2 seconds between notifications + count: 5, // Send 5 notifications + caller: 'slow-notifier' // Identify this tool call + } + } + } + }, + { + caller: 'burst-notifier', + request: { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 1, // 0.1 second between notifications + count: 3, // Send just 3 notifications + caller: 'burst-notifier' // Identify this tool call + } + } + } + } + ]; + console.log(`Starting ${toolCalls.length} notification tools in parallel...`); + // Start all tool calls in parallel + const toolPromises = toolCalls.map(({ caller, request }) => { + console.log(`Starting tool call for ${caller}...`); + return client + .request(request, types_js_1.CallToolResultSchema) + .then(result => ({ caller, result })) + .catch(error => { + console.error(`Error in tool call for ${caller}:`, error); + throw error; + }); + }); + // Wait for all tool calls to complete + const results = await Promise.all(toolPromises); + // Organize results by caller + const resultsByTool = {}; + results.forEach(({ caller, result }) => { + resultsByTool[caller] = result; + }); + return resultsByTool; + } + catch (error) { + console.error(`Error starting parallel notification tools:`, error); + throw error; + } +} +// Start the client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=parallelToolCallsClient.js.map \ No newline at end of file diff --git a/dist/cjs/examples/client/parallelToolCallsClient.js.map b/dist/cjs/examples/client/parallelToolCallsClient.js.map new file mode 100644 index 0000000000..dabdf4895b --- /dev/null +++ b/dist/cjs/examples/client/parallelToolCallsClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parallelToolCallsClient.js","sourceRoot":"","sources":["../../../../src/examples/client/parallelToolCallsClient.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,sEAA+E;AAC/E,6CAMwB;AAExB;;;;;;GAMG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AAEzD,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,4BAA4B,SAAS,EAAE,CAAC,CAAC;IAErD,IAAI,MAAc,CAAC;IACnB,IAAI,SAAwC,CAAC;IAE7C,IAAI,CAAC;QACD,+CAA+C;QAC/C,MAAM,GAAG,IAAI,iBAAM,CAAC;YAChB,IAAI,EAAE,4BAA4B;YAClC,OAAO,EAAE,OAAO;SAC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.d.ts new file mode 100644 index 0000000000..e4b43dbc01 --- /dev/null +++ b/dist/cjs/examples/client/simpleOAuthClient.d.ts @@ -0,0 +1,3 @@ +#!/usr/bin/env node +export {}; +//# sourceMappingURL=simpleOAuthClient.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleOAuthClient.d.ts.map b/dist/cjs/examples/client/simpleOAuthClient.d.ts.map new file mode 100644 index 0000000000..c09eef86ea --- /dev/null +++ b/dist/cjs/examples/client/simpleOAuthClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleOAuthClient.js b/dist/cjs/examples/client/simpleOAuthClient.js new file mode 100644 index 0000000000..726201937c --- /dev/null +++ b/dist/cjs/examples/client/simpleOAuthClient.js @@ -0,0 +1,337 @@ +#!/usr/bin/env node +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const node_http_1 = require("node:http"); +const node_readline_1 = require("node:readline"); +const node_url_1 = require("node:url"); +const node_child_process_1 = require("node:child_process"); +const index_js_1 = require("../../client/index.js"); +const streamableHttp_js_1 = require("../../client/streamableHttp.js"); +const types_js_1 = require("../../types.js"); +const auth_js_1 = require("../../client/auth.js"); +const simpleOAuthClientProvider_js_1 = require("./simpleOAuthClientProvider.js"); +// Configuration +const DEFAULT_SERVER_URL = 'http://localhost:3000/mcp'; +const CALLBACK_PORT = 8090; // Use different port than auth server (3001) +const CALLBACK_URL = `http://localhost:${CALLBACK_PORT}/callback`; +/** + * Interactive MCP client with OAuth authentication + * Demonstrates the complete OAuth flow with browser-based authorization + */ +class InteractiveOAuthClient { + constructor(serverUrl, clientMetadataUrl) { + this.serverUrl = serverUrl; + this.clientMetadataUrl = clientMetadataUrl; + this.client = null; + this.rl = (0, node_readline_1.createInterface)({ + input: process.stdin, + output: process.stdout + }); + } + /** + * Prompts user for input via readline + */ + async question(query) { + return new Promise(resolve => { + this.rl.question(query, resolve); + }); + } + /** + * Opens the authorization URL in the user's default browser + */ + async openBrowser(url) { + console.log(`🌐 Opening browser for authorization: ${url}`); + const command = `open "${url}"`; + (0, node_child_process_1.exec)(command, error => { + if (error) { + console.error(`Failed to open browser: ${error.message}`); + console.log(`Please manually open: ${url}`); + } + }); + } + /** + * Example OAuth callback handler - in production, use a more robust approach + * for handling callbacks and storing tokens + */ + /** + * Starts a temporary HTTP server to receive the OAuth callback + */ + async waitForOAuthCallback() { + return new Promise((resolve, reject) => { + const server = (0, node_http_1.createServer)((req, res) => { + // Ignore favicon requests + if (req.url === '/favicon.ico') { + res.writeHead(404); + res.end(); + return; + } + console.log(`📥 Received callback: ${req.url}`); + const parsedUrl = new node_url_1.URL(req.url || '', 'http://localhost'); + const code = parsedUrl.searchParams.get('code'); + const error = parsedUrl.searchParams.get('error'); + if (code) { + console.log(`✅ Authorization code received: ${code === null || code === void 0 ? void 0 : code.substring(0, 10)}...`); + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Successful!

+

You can close this window and return to the terminal.

+ + + + `); + resolve(code); + setTimeout(() => server.close(), 3000); + } + else if (error) { + console.log(`❌ Authorization error: ${error}`); + res.writeHead(400, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Failed

+

Error: ${error}

+ + + `); + reject(new Error(`OAuth authorization failed: ${error}`)); + } + else { + console.log(`❌ No authorization code or error in callback`); + res.writeHead(400); + res.end('Bad request'); + reject(new Error('No authorization code provided')); + } + }); + server.listen(CALLBACK_PORT, () => { + console.log(`OAuth callback server started on http://localhost:${CALLBACK_PORT}`); + }); + }); + } + async attemptConnection(oauthProvider) { + console.log('🚢 Creating transport with OAuth provider...'); + const baseUrl = new node_url_1.URL(this.serverUrl); + const transport = new streamableHttp_js_1.StreamableHTTPClientTransport(baseUrl, { + authProvider: oauthProvider + }); + console.log('🚢 Transport created'); + try { + console.log('🔌 Attempting connection (this will trigger OAuth redirect)...'); + await this.client.connect(transport); + console.log('✅ Connected successfully'); + } + catch (error) { + if (error instanceof auth_js_1.UnauthorizedError) { + console.log('🔐 OAuth required - waiting for authorization...'); + const callbackPromise = this.waitForOAuthCallback(); + const authCode = await callbackPromise; + await transport.finishAuth(authCode); + console.log('🔐 Authorization code received:', authCode); + console.log('🔌 Reconnecting with authenticated transport...'); + await this.attemptConnection(oauthProvider); + } + else { + console.error('❌ Connection failed with non-auth error:', error); + throw error; + } + } + } + /** + * Establishes connection to the MCP server with OAuth authentication + */ + async connect() { + console.log(`🔗 Attempting to connect to ${this.serverUrl}...`); + const clientMetadata = { + client_name: 'Simple OAuth MCP Client', + redirect_uris: [CALLBACK_URL], + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + token_endpoint_auth_method: 'client_secret_post' + }; + console.log('🔐 Creating OAuth provider...'); + const oauthProvider = new simpleOAuthClientProvider_js_1.InMemoryOAuthClientProvider(CALLBACK_URL, clientMetadata, (redirectUrl) => { + console.log(`📌 OAuth redirect handler called - opening browser`); + console.log(`Opening browser to: ${redirectUrl.toString()}`); + this.openBrowser(redirectUrl.toString()); + }, this.clientMetadataUrl); + console.log('🔐 OAuth provider created'); + console.log('👤 Creating MCP client...'); + this.client = new index_js_1.Client({ + name: 'simple-oauth-client', + version: '1.0.0' + }, { capabilities: {} }); + console.log('👤 Client created'); + console.log('🔐 Starting OAuth flow...'); + await this.attemptConnection(oauthProvider); + // Start interactive loop + await this.interactiveLoop(); + } + /** + * Main interactive loop for user commands + */ + async interactiveLoop() { + console.log('\n🎯 Interactive MCP Client with OAuth'); + console.log('Commands:'); + console.log(' list - List available tools'); + console.log(' call [args] - Call a tool'); + console.log(' quit - Exit the client'); + console.log(); + while (true) { + try { + const command = await this.question('mcp> '); + if (!command.trim()) { + continue; + } + if (command === 'quit') { + console.log('\n👋 Goodbye!'); + this.close(); + process.exit(0); + } + else if (command === 'list') { + await this.listTools(); + } + else if (command.startsWith('call ')) { + await this.handleCallTool(command); + } + else { + console.log("❌ Unknown command. Try 'list', 'call ', or 'quit'"); + } + } + catch (error) { + if (error instanceof Error && error.message === 'SIGINT') { + console.log('\n\n👋 Goodbye!'); + break; + } + console.error('❌ Error:', error); + } + } + } + async listTools() { + if (!this.client) { + console.log('❌ Not connected to server'); + return; + } + try { + const request = { + method: 'tools/list', + params: {} + }; + const result = await this.client.request(request, types_js_1.ListToolsResultSchema); + if (result.tools && result.tools.length > 0) { + console.log('\n📋 Available tools:'); + result.tools.forEach((tool, index) => { + console.log(`${index + 1}. ${tool.name}`); + if (tool.description) { + console.log(` Description: ${tool.description}`); + } + console.log(); + }); + } + else { + console.log('No tools available'); + } + } + catch (error) { + console.error('❌ Failed to list tools:', error); + } + } + async handleCallTool(command) { + const parts = command.split(/\s+/); + const toolName = parts[1]; + if (!toolName) { + console.log('❌ Please specify a tool name'); + return; + } + // Parse arguments (simple JSON-like format) + let toolArgs = {}; + if (parts.length > 2) { + const argsString = parts.slice(2).join(' '); + try { + toolArgs = JSON.parse(argsString); + } + catch (_a) { + console.log('❌ Invalid arguments format (expected JSON)'); + return; + } + } + await this.callTool(toolName, toolArgs); + } + async callTool(toolName, toolArgs) { + if (!this.client) { + console.log('❌ Not connected to server'); + return; + } + try { + const request = { + method: 'tools/call', + params: { + name: toolName, + arguments: toolArgs + } + }; + const result = await this.client.request(request, types_js_1.CallToolResultSchema); + console.log(`\n🔧 Tool '${toolName}' result:`); + if (result.content) { + result.content.forEach(content => { + if (content.type === 'text') { + console.log(content.text); + } + else { + console.log(content); + } + }); + } + else { + console.log(result); + } + } + catch (error) { + console.error(`❌ Failed to call tool '${toolName}':`, error); + } + } + close() { + this.rl.close(); + if (this.client) { + // Note: Client doesn't have a close method in the current implementation + // This would typically close the transport connection + } + } +} +/** + * Main entry point + */ +async function main() { + const args = process.argv.slice(2); + const serverUrl = args[0] || DEFAULT_SERVER_URL; + const clientMetadataUrl = args[1]; + console.log('🚀 Simple MCP OAuth Client'); + console.log(`Connecting to: ${serverUrl}`); + if (clientMetadataUrl) { + console.log(`Client Metadata URL: ${clientMetadataUrl}`); + } + console.log(); + const client = new InteractiveOAuthClient(serverUrl, clientMetadataUrl); + // Handle graceful shutdown + process.on('SIGINT', () => { + console.log('\n\n👋 Goodbye!'); + client.close(); + process.exit(0); + }); + try { + await client.connect(); + } + catch (error) { + console.error('Failed to start client:', error); + process.exit(1); + } + finally { + client.close(); + } +} +// Run if this file is executed directly +main().catch(error => { + console.error('Unhandled error:', error); + process.exit(1); +}); +//# sourceMappingURL=simpleOAuthClient.js.map \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleOAuthClient.js.map b/dist/cjs/examples/client/simpleOAuthClient.js.map new file mode 100644 index 0000000000..10f698c529 --- /dev/null +++ b/dist/cjs/examples/client/simpleOAuthClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClient.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClient.ts"],"names":[],"mappings":";;;AAEA,yCAAyC;AACzC,iDAAgD;AAChD,uCAA+B;AAC/B,2DAA0C;AAC1C,oDAA+C;AAC/C,sEAA+E;AAE/E,6CAAgH;AAChH,kDAAyD;AACzD,iFAA6E;AAE7E,gBAAgB;AAChB,MAAM,kBAAkB,GAAG,2BAA2B,CAAC;AACvD,MAAM,aAAa,GAAG,IAAI,CAAC,CAAC,6CAA6C;AACzE,MAAM,YAAY,GAAG,oBAAoB,aAAa,WAAW,CAAC;AAElE;;;GAGG;AACH,MAAM,sBAAsB;IAOxB,YACY,SAAiB,EACjB,iBAA0B;QAD1B,cAAS,GAAT,SAAS,CAAQ;QACjB,sBAAiB,GAAjB,iBAAiB,CAAS;QAR9B,WAAM,GAAkB,IAAI,CAAC;QACpB,OAAE,GAAG,IAAA,+BAAe,EAAC;YAClC,KAAK,EAAE,OAAO,CAAC,KAAK;YACpB,MAAM,EAAE,OAAO,CAAC,MAAM;SACzB,CAAC,CAAC;IAKA,CAAC;IAEJ;;OAEG;IACK,KAAK,CAAC,QA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,EAAE,GAAG,EAAE;QACtB,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC;QACD,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;YAAS,CAAC;QACP,MAAM,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;AACL,CAAC;AAED,wCAAwC;AACxC,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;IACzC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts b/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts new file mode 100644 index 0000000000..092616cf5c --- /dev/null +++ b/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts @@ -0,0 +1,26 @@ +import { OAuthClientProvider } from '../../client/auth.js'; +import { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from '../../shared/auth.js'; +/** + * In-memory OAuth client provider for demonstration purposes + * In production, you should persist tokens securely + */ +export declare class InMemoryOAuthClientProvider implements OAuthClientProvider { + private readonly _redirectUrl; + private readonly _clientMetadata; + readonly clientMetadataUrl?: string | undefined; + private _clientInformation?; + private _tokens?; + private _codeVerifier?; + constructor(_redirectUrl: string | URL, _clientMetadata: OAuthClientMetadata, onRedirect?: (url: URL) => void, clientMetadataUrl?: string | undefined); + private _onRedirect; + get redirectUrl(): string | URL; + get clientMetadata(): OAuthClientMetadata; + clientInformation(): OAuthClientInformationMixed | undefined; + saveClientInformation(clientInformation: OAuthClientInformationMixed): void; + tokens(): OAuthTokens | undefined; + saveTokens(tokens: OAuthTokens): void; + redirectToAuthorization(authorizationUrl: URL): void; + saveCodeVerifier(codeVerifier: string): void; + codeVerifier(): string; +} +//# sourceMappingURL=simpleOAuthClientProvider.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts.map b/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts.map new file mode 100644 index 0000000000..21efe9444a --- /dev/null +++ b/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClientProvider.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClientProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,2BAA2B,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAErG;;;GAGG;AACH,qBAAa,2BAA4B,YAAW,mBAAmB;IAM/D,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,eAAe;aAEhB,iBAAiB,CAAC,EAAE,MAAM;IAR9C,OAAO,CAAC,kBAAkB,CAAC,CAA8B;IACzD,OAAO,CAAC,OAAO,CAAC,CAAc;IAC9B,OAAO,CAAC,aAAa,CAAC,CAAS;gBAGV,YAAY,EAAE,MAAM,GAAG,GAAG,EAC1B,eAAe,EAAE,mBAAmB,EACrD,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,EACf,iBAAiB,CAAC,EAAE,MAAM,YAAA;IAS9C,OAAO,CAAC,WAAW,CAAqB;IAExC,IAAI,WAAW,IAAI,MAAM,GAAG,GAAG,CAE9B;IAED,IAAI,cAAc,IAAI,mBAAmB,CAExC;IAED,iBAAiB,IAAI,2BAA2B,GAAG,SAAS;IAI5D,qBAAqB,CAAC,iBAAiB,EAAE,2BAA2B,GAAG,IAAI;IAI3E,MAAM,IAAI,WAAW,GAAG,SAAS;IAIjC,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI;IAIrC,uBAAuB,CAAC,gBAAgB,EAAE,GAAG,GAAG,IAAI;IAIpD,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI;IAI5C,YAAY,IAAI,MAAM;CAMzB"} \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleOAuthClientProvider.js b/dist/cjs/examples/client/simpleOAuthClientProvider.js new file mode 100644 index 0000000000..58959bbfcc --- /dev/null +++ b/dist/cjs/examples/client/simpleOAuthClientProvider.js @@ -0,0 +1,51 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InMemoryOAuthClientProvider = void 0; +/** + * In-memory OAuth client provider for demonstration purposes + * In production, you should persist tokens securely + */ +class InMemoryOAuthClientProvider { + constructor(_redirectUrl, _clientMetadata, onRedirect, clientMetadataUrl) { + this._redirectUrl = _redirectUrl; + this._clientMetadata = _clientMetadata; + this.clientMetadataUrl = clientMetadataUrl; + this._onRedirect = + onRedirect || + (url => { + console.log(`Redirect to: ${url.toString()}`); + }); + } + get redirectUrl() { + return this._redirectUrl; + } + get clientMetadata() { + return this._clientMetadata; + } + clientInformation() { + return this._clientInformation; + } + saveClientInformation(clientInformation) { + this._clientInformation = clientInformation; + } + tokens() { + return this._tokens; + } + saveTokens(tokens) { + this._tokens = tokens; + } + redirectToAuthorization(authorizationUrl) { + this._onRedirect(authorizationUrl); + } + saveCodeVerifier(codeVerifier) { + this._codeVerifier = codeVerifier; + } + codeVerifier() { + if (!this._codeVerifier) { + throw new Error('No code verifier saved'); + } + return this._codeVerifier; + } +} +exports.InMemoryOAuthClientProvider = InMemoryOAuthClientProvider; +//# sourceMappingURL=simpleOAuthClientProvider.js.map \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleOAuthClientProvider.js.map b/dist/cjs/examples/client/simpleOAuthClientProvider.js.map new file mode 100644 index 0000000000..10771f8e52 --- /dev/null +++ b/dist/cjs/examples/client/simpleOAuthClientProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClientProvider.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClientProvider.ts"],"names":[],"mappings":";;;AAGA;;;GAGG;AACH,MAAa,2BAA2B;IAKpC,YACqB,YAA0B,EAC1B,eAAoC,EACrD,UAA+B,EACf,iBAA0B;QAHzB,iBAAY,GAAZ,YAAY,CAAc;QAC1B,oBAAe,GAAf,eAAe,CAAqB;QAErC,sBAAiB,GAAjB,iBAAiB,CAAS;QAE1C,IAAI,CAAC,WAAW;YACZ,UAAU;gBACV,CAAC,GAAG,CAAC,EAAE;oBACH,OAAO,CAAC,GAAG,CAAC,gBAAgB,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;gBAClD,CAAC,CAAC,CAAC;IACX,CAAC;IAID,IAAI,WAAW;QACX,OAAO,IAAI,CAAC,YAAY,CAAC;IAC7B,CAAC;IAED,IAAI,cAAc;QACd,OAAO,IAAI,CAAC,eAAe,CAAC;IAChC,CAAC;IAED,iBAAiB;QACb,OAAO,IAAI,CAAC,kBAAkB,CAAC;IACnC,CAAC;IAED,qBAAqB,CAAC,iBAA8C;QAChE,IAAI,CAAC,kBAAkB,GAAG,iBAAiB,CAAC;IAChD,CAAC;IAED,MAAM;QACF,OAAO,IAAI,CAAC,OAAO,CAAC;IACxB,CAAC;IAED,UAAU,CAAC,MAAmB;QAC1B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IAC1B,CAAC;IAED,uBAAuB,CAAC,gBAAqB;QACzC,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC;IACvC,CAAC;IAED,gBAAgB,CAAC,YAAoB;QACjC,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;IACtC,CAAC;IAED,YAAY;QACR,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACtB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC9C,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC;IAC9B,CAAC;CACJ;AA1DD,kEA0DC"} \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleStreamableHttp.d.ts b/dist/cjs/examples/client/simpleStreamableHttp.d.ts new file mode 100644 index 0000000000..a20be42ca4 --- /dev/null +++ b/dist/cjs/examples/client/simpleStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleStreamableHttp.d.ts.map b/dist/cjs/examples/client/simpleStreamableHttp.d.ts.map new file mode 100644 index 0000000000..28406b0c1e --- /dev/null +++ b/dist/cjs/examples/client/simpleStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleStreamableHttp.js b/dist/cjs/examples/client/simpleStreamableHttp.js new file mode 100644 index 0000000000..efdff0a125 --- /dev/null +++ b/dist/cjs/examples/client/simpleStreamableHttp.js @@ -0,0 +1,749 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const index_js_1 = require("../../client/index.js"); +const streamableHttp_js_1 = require("../../client/streamableHttp.js"); +const node_readline_1 = require("node:readline"); +const types_js_1 = require("../../types.js"); +const metadataUtils_js_1 = require("../../shared/metadataUtils.js"); +const ajv_1 = require("ajv"); +// Create readline interface for user input +const readline = (0, node_readline_1.createInterface)({ + input: process.stdin, + output: process.stdout +}); +// Track received notifications for debugging resumability +let notificationCount = 0; +// Global client and transport for interactive commands +let client = null; +let transport = null; +let serverUrl = 'http://localhost:3000/mcp'; +let notificationsToolLastEventId = undefined; +let sessionId = undefined; +async function main() { + console.log('MCP Interactive Client'); + console.log('====================='); + // Connect to server immediately with default settings + await connect(); + // Print help and start the command loop + printHelp(); + commandLoop(); +} +function printHelp() { + console.log('\nAvailable commands:'); + console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)'); + console.log(' disconnect - Disconnect from server'); + console.log(' terminate-session - Terminate the current session'); + console.log(' reconnect - Reconnect to the server'); + console.log(' list-tools - List available tools'); + console.log(' call-tool [args] - Call a tool with optional JSON arguments'); + console.log(' greet [name] - Call the greet tool'); + console.log(' multi-greet [name] - Call the multi-greet tool with notifications'); + console.log(' collect-info [type] - Test form elicitation with collect-user-info tool (contact/preferences/feedback)'); + console.log(' start-notifications [interval] [count] - Start periodic notifications'); + console.log(' run-notifications-tool-with-resumability [interval] [count] - Run notification tool with resumability'); + console.log(' list-prompts - List available prompts'); + console.log(' get-prompt [name] [args] - Get a prompt with optional JSON arguments'); + console.log(' list-resources - List available resources'); + console.log(' read-resource - Read a specific resource by URI'); + console.log(' help - Show this help'); + console.log(' quit - Exit the program'); +} +function commandLoop() { + readline.question('\n> ', async (input) => { + var _a; + const args = input.trim().split(/\s+/); + const command = (_a = args[0]) === null || _a === void 0 ? void 0 : _a.toLowerCase(); + try { + switch (command) { + case 'connect': + await connect(args[1]); + break; + case 'disconnect': + await disconnect(); + break; + case 'terminate-session': + await terminateSession(); + break; + case 'reconnect': + await reconnect(); + break; + case 'list-tools': + await listTools(); + break; + case 'call-tool': + if (args.length < 2) { + console.log('Usage: call-tool [args]'); + } + else { + const toolName = args[1]; + let toolArgs = {}; + if (args.length > 2) { + try { + toolArgs = JSON.parse(args.slice(2).join(' ')); + } + catch (_b) { + console.log('Invalid JSON arguments. Using empty args.'); + } + } + await callTool(toolName, toolArgs); + } + break; + case 'greet': + await callGreetTool(args[1] || 'MCP User'); + break; + case 'multi-greet': + await callMultiGreetTool(args[1] || 'MCP User'); + break; + case 'collect-info': + await callCollectInfoTool(args[1] || 'contact'); + break; + case 'start-notifications': { + const interval = args[1] ? parseInt(args[1], 10) : 2000; + const count = args[2] ? parseInt(args[2], 10) : 10; + await startNotifications(interval, count); + break; + } + case 'run-notifications-tool-with-resumability': { + const interval = args[1] ? parseInt(args[1], 10) : 2000; + const count = args[2] ? parseInt(args[2], 10) : 10; + await runNotificationsToolWithResumability(interval, count); + break; + } + case 'list-prompts': + await listPrompts(); + break; + case 'get-prompt': + if (args.length < 2) { + console.log('Usage: get-prompt [args]'); + } + else { + const promptName = args[1]; + let promptArgs = {}; + if (args.length > 2) { + try { + promptArgs = JSON.parse(args.slice(2).join(' ')); + } + catch (_c) { + console.log('Invalid JSON arguments. Using empty args.'); + } + } + await getPrompt(promptName, promptArgs); + } + break; + case 'list-resources': + await listResources(); + break; + case 'read-resource': + if (args.length < 2) { + console.log('Usage: read-resource '); + } + else { + await readResource(args[1]); + } + break; + case 'help': + printHelp(); + break; + case 'quit': + case 'exit': + await cleanup(); + return; + default: + if (command) { + console.log(`Unknown command: ${command}`); + } + break; + } + } + catch (error) { + console.error(`Error executing command: ${error}`); + } + // Continue the command loop + commandLoop(); + }); +} +async function connect(url) { + if (client) { + console.log('Already connected. Disconnect first.'); + return; + } + if (url) { + serverUrl = url; + } + console.log(`Connecting to ${serverUrl}...`); + try { + // Create a new client with form elicitation capability + client = new index_js_1.Client({ + name: 'example-client', + version: '1.0.0' + }, { + capabilities: { + elicitation: { + form: {} + } + } + }); + client.onerror = error => { + console.error('\x1b[31mClient error:', error, '\x1b[0m'); + }; + // Set up elicitation request handler with proper validation + client.setRequestHandler(types_js_1.ElicitRequestSchema, async (request) => { + var _a; + if (request.params.mode !== 'form') { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Unsupported elicitation mode: ${request.params.mode}`); + } + console.log('\n🔔 Elicitation (form) Request Received:'); + console.log(`Message: ${request.params.message}`); + console.log('Requested Schema:'); + console.log(JSON.stringify(request.params.requestedSchema, null, 2)); + const schema = request.params.requestedSchema; + const properties = schema.properties; + const required = schema.required || []; + // Set up AJV validator for the requested schema + const ajv = new ajv_1.Ajv(); + const validate = ajv.compile(schema); + let attempts = 0; + const maxAttempts = 3; + while (attempts < maxAttempts) { + attempts++; + console.log(`\nPlease provide the following information (attempt ${attempts}/${maxAttempts}):`); + const content = {}; + let inputCancelled = false; + // Collect input for each field + for (const [fieldName, fieldSchema] of Object.entries(properties)) { + const field = fieldSchema; + const isRequired = required.includes(fieldName); + let prompt = `${field.title || fieldName}`; + // Add helpful information to the prompt + if (field.description) { + prompt += ` (${field.description})`; + } + if (field.enum) { + prompt += ` [options: ${field.enum.join(', ')}]`; + } + if (field.type === 'number' || field.type === 'integer') { + if (field.minimum !== undefined && field.maximum !== undefined) { + prompt += ` [${field.minimum}-${field.maximum}]`; + } + else if (field.minimum !== undefined) { + prompt += ` [min: ${field.minimum}]`; + } + else if (field.maximum !== undefined) { + prompt += ` [max: ${field.maximum}]`; + } + } + if (field.type === 'string' && field.format) { + prompt += ` [format: ${field.format}]`; + } + if (isRequired) { + prompt += ' *required*'; + } + if (field.default !== undefined) { + prompt += ` [default: ${field.default}]`; + } + prompt += ': '; + const answer = await new Promise(resolve => { + readline.question(prompt, input => { + resolve(input.trim()); + }); + }); + // Check for cancellation + if (answer.toLowerCase() === 'cancel' || answer.toLowerCase() === 'c') { + inputCancelled = true; + break; + } + // Parse and validate the input + try { + if (answer === '' && field.default !== undefined) { + content[fieldName] = field.default; + } + else if (answer === '' && !isRequired) { + // Skip optional empty fields + continue; + } + else if (answer === '') { + throw new Error(`${fieldName} is required`); + } + else { + // Parse the value based on type + let parsedValue; + if (field.type === 'boolean') { + parsedValue = answer.toLowerCase() === 'true' || answer.toLowerCase() === 'yes' || answer === '1'; + } + else if (field.type === 'number') { + parsedValue = parseFloat(answer); + if (isNaN(parsedValue)) { + throw new Error(`${fieldName} must be a valid number`); + } + } + else if (field.type === 'integer') { + parsedValue = parseInt(answer, 10); + if (isNaN(parsedValue)) { + throw new Error(`${fieldName} must be a valid integer`); + } + } + else if (field.enum) { + if (!field.enum.includes(answer)) { + throw new Error(`${fieldName} must be one of: ${field.enum.join(', ')}`); + } + parsedValue = answer; + } + else { + parsedValue = answer; + } + content[fieldName] = parsedValue; + } + } + catch (error) { + console.log(`❌ Error: ${error}`); + // Continue to next attempt + break; + } + } + if (inputCancelled) { + return { action: 'cancel' }; + } + // If we didn't complete all fields due to an error, try again + if (Object.keys(content).length !== + Object.keys(properties).filter(name => required.includes(name) || content[name] !== undefined).length) { + if (attempts < maxAttempts) { + console.log('Please try again...'); + continue; + } + else { + console.log('Maximum attempts reached. Declining request.'); + return { action: 'decline' }; + } + } + // Validate the complete object against the schema + const isValid = validate(content); + if (!isValid) { + console.log('❌ Validation errors:'); + (_a = validate.errors) === null || _a === void 0 ? void 0 : _a.forEach(error => { + console.log(` - ${error.instancePath || 'root'}: ${error.message}`); + }); + if (attempts < maxAttempts) { + console.log('Please correct the errors and try again...'); + continue; + } + else { + console.log('Maximum attempts reached. Declining request.'); + return { action: 'decline' }; + } + } + // Show the collected data and ask for confirmation + console.log('\n✅ Collected data:'); + console.log(JSON.stringify(content, null, 2)); + const confirmAnswer = await new Promise(resolve => { + readline.question('\nSubmit this information? (yes/no/cancel): ', input => { + resolve(input.trim().toLowerCase()); + }); + }); + if (confirmAnswer === 'yes' || confirmAnswer === 'y') { + return { + action: 'accept', + content + }; + } + else if (confirmAnswer === 'cancel' || confirmAnswer === 'c') { + return { action: 'cancel' }; + } + else if (confirmAnswer === 'no' || confirmAnswer === 'n') { + if (attempts < maxAttempts) { + console.log('Please re-enter the information...'); + continue; + } + else { + return { action: 'decline' }; + } + } + } + console.log('Maximum attempts reached. Declining request.'); + return { action: 'decline' }; + }); + transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(serverUrl), { + sessionId: sessionId + }); + // Set up notification handlers + client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => { + notificationCount++; + console.log(`\nNotification #${notificationCount}: ${notification.params.level} - ${notification.params.data}`); + // Re-display the prompt + process.stdout.write('> '); + }); + client.setNotificationHandler(types_js_1.ResourceListChangedNotificationSchema, async (_) => { + console.log(`\nResource list changed notification received!`); + try { + if (!client) { + console.log('Client disconnected, cannot fetch resources'); + return; + } + const resourcesResult = await client.request({ + method: 'resources/list', + params: {} + }, types_js_1.ListResourcesResultSchema); + console.log('Available resources count:', resourcesResult.resources.length); + } + catch (_a) { + console.log('Failed to list resources after change notification'); + } + // Re-display the prompt + process.stdout.write('> '); + }); + // Connect the client + await client.connect(transport); + sessionId = transport.sessionId; + console.log('Transport created with session ID:', sessionId); + console.log('Connected to MCP server'); + } + catch (error) { + console.error('Failed to connect:', error); + client = null; + transport = null; + } +} +async function disconnect() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + await transport.close(); + console.log('Disconnected from MCP server'); + client = null; + transport = null; + } + catch (error) { + console.error('Error disconnecting:', error); + } +} +async function terminateSession() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + console.log('Terminating session with ID:', transport.sessionId); + await transport.terminateSession(); + console.log('Session terminated successfully'); + // Check if sessionId was cleared after termination + if (!transport.sessionId) { + console.log('Session ID has been cleared'); + sessionId = undefined; + // Also close the transport and clear client objects + await transport.close(); + console.log('Transport closed after session termination'); + client = null; + transport = null; + } + else { + console.log('Server responded with 405 Method Not Allowed (session termination not supported)'); + console.log('Session ID is still active:', transport.sessionId); + } + } + catch (error) { + console.error('Error terminating session:', error); + } +} +async function reconnect() { + if (client) { + await disconnect(); + } + await connect(); +} +async function listTools() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - id: ${tool.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(tool)}, description: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server (${error})`); + } +} +async function callTool(name, args) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const request = { + method: 'tools/call', + params: { + name, + arguments: args + } + }; + console.log(`Calling tool '${name}' with args:`, args); + const result = await client.request(request, types_js_1.CallToolResultSchema); + console.log('Tool result:'); + const resourceLinks = []; + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else if (item.type === 'resource_link') { + const resourceLink = item; + resourceLinks.push(resourceLink); + console.log(` 📁 Resource Link: ${resourceLink.name}`); + console.log(` URI: ${resourceLink.uri}`); + if (resourceLink.mimeType) { + console.log(` Type: ${resourceLink.mimeType}`); + } + if (resourceLink.description) { + console.log(` Description: ${resourceLink.description}`); + } + } + else if (item.type === 'resource') { + console.log(` [Embedded Resource: ${item.resource.uri}]`); + } + else if (item.type === 'image') { + console.log(` [Image: ${item.mimeType}]`); + } + else if (item.type === 'audio') { + console.log(` [Audio: ${item.mimeType}]`); + } + else { + console.log(` [Unknown content type]:`, item); + } + }); + // Offer to read resource links + if (resourceLinks.length > 0) { + console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource ' to read their content.`); + } + } + catch (error) { + console.log(`Error calling tool ${name}: ${error}`); + } +} +async function callGreetTool(name) { + await callTool('greet', { name }); +} +async function callMultiGreetTool(name) { + console.log('Calling multi-greet tool with notifications...'); + await callTool('multi-greet', { name }); +} +async function callCollectInfoTool(infoType) { + console.log(`Testing form elicitation with collect-user-info tool (${infoType})...`); + await callTool('collect-user-info', { infoType }); +} +async function startNotifications(interval, count) { + console.log(`Starting notification stream: interval=${interval}ms, count=${count || 'unlimited'}`); + await callTool('start-notification-stream', { interval, count }); +} +async function runNotificationsToolWithResumability(interval, count) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + console.log(`Starting notification stream with resumability: interval=${interval}ms, count=${count || 'unlimited'}`); + console.log(`Using resumption token: ${notificationsToolLastEventId || 'none'}`); + const request = { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { interval, count } + } + }; + const onLastEventIdUpdate = (event) => { + notificationsToolLastEventId = event; + console.log(`Updated resumption token: ${event}`); + }; + const result = await client.request(request, types_js_1.CallToolResultSchema, { + resumptionToken: notificationsToolLastEventId, + onresumptiontoken: onLastEventIdUpdate + }); + console.log('Tool result:'); + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + catch (error) { + console.log(`Error starting notification stream: ${error}`); + } +} +async function listPrompts() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const promptsRequest = { + method: 'prompts/list', + params: {} + }; + const promptsResult = await client.request(promptsRequest, types_js_1.ListPromptsResultSchema); + console.log('Available prompts:'); + if (promptsResult.prompts.length === 0) { + console.log(' No prompts available'); + } + else { + for (const prompt of promptsResult.prompts) { + console.log(` - id: ${prompt.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(prompt)}, description: ${prompt.description}`); + } + } + } + catch (error) { + console.log(`Prompts not supported by this server (${error})`); + } +} +async function getPrompt(name, args) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const promptRequest = { + method: 'prompts/get', + params: { + name, + arguments: args + } + }; + const promptResult = await client.request(promptRequest, types_js_1.GetPromptResultSchema); + console.log('Prompt template:'); + promptResult.messages.forEach((msg, index) => { + console.log(` [${index + 1}] ${msg.role}: ${msg.content.type === 'text' ? msg.content.text : JSON.stringify(msg.content)}`); + }); + } + catch (error) { + console.log(`Error getting prompt ${name}: ${error}`); + } +} +async function listResources() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const resourcesRequest = { + method: 'resources/list', + params: {} + }; + const resourcesResult = await client.request(resourcesRequest, types_js_1.ListResourcesResultSchema); + console.log('Available resources:'); + if (resourcesResult.resources.length === 0) { + console.log(' No resources available'); + } + else { + for (const resource of resourcesResult.resources) { + console.log(` - id: ${resource.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(resource)}, description: ${resource.uri}`); + } + } + } + catch (error) { + console.log(`Resources not supported by this server (${error})`); + } +} +async function readResource(uri) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const request = { + method: 'resources/read', + params: { uri } + }; + console.log(`Reading resource: ${uri}`); + const result = await client.request(request, types_js_1.ReadResourceResultSchema); + console.log('Resource contents:'); + for (const content of result.contents) { + console.log(` URI: ${content.uri}`); + if (content.mimeType) { + console.log(` Type: ${content.mimeType}`); + } + if ('text' in content && typeof content.text === 'string') { + console.log(' Content:'); + console.log(' ---'); + console.log(content.text + .split('\n') + .map((line) => ' ' + line) + .join('\n')); + console.log(' ---'); + } + else if ('blob' in content && typeof content.blob === 'string') { + console.log(` [Binary data: ${content.blob.length} bytes]`); + } + } + } + catch (error) { + console.log(`Error reading resource ${uri}: ${error}`); + } +} +async function cleanup() { + if (client && transport) { + try { + // First try to terminate the session gracefully + if (transport.sessionId) { + try { + console.log('Terminating session before exit...'); + await transport.terminateSession(); + console.log('Session terminated successfully'); + } + catch (error) { + console.error('Error terminating session:', error); + } + } + // Then close the transport + await transport.close(); + } + catch (error) { + console.error('Error closing transport:', error); + } + } + process.stdin.setRawMode(false); + readline.close(); + console.log('\nGoodbye!'); + process.exit(0); +} +// Set up raw mode for keyboard input to capture Escape key +process.stdin.setRawMode(true); +process.stdin.on('data', async (data) => { + // Check for Escape key (27) + if (data.length === 1 && data[0] === 27) { + console.log('\nESC key pressed. Disconnecting from server...'); + // Abort current operation and disconnect from server + if (client && transport) { + await disconnect(); + console.log('Disconnected. Press Enter to continue.'); + } + else { + console.log('Not connected to server.'); + } + // Re-display the prompt + process.stdout.write('> '); + } +}); +// Handle Ctrl+C +process.on('SIGINT', async () => { + console.log('\nReceived SIGINT. Cleaning up...'); + await cleanup(); +}); +// Start the interactive client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=simpleStreamableHttp.js.map \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleStreamableHttp.js.map b/dist/cjs/examples/client/simpleStreamableHttp.js.map new file mode 100644 index 0000000000..699665c84d --- /dev/null +++ b/dist/cjs/examples/client/simpleStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleStreamableHttp.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,sEAA+E;AAC/E,iDAAgD;AAChD,6CAmBwB;AACxB,oEAA+D;AAC/D,6BAA0B;AAE1B,2CAA2C;AAC3C,MAAM,QAAQ,GAAG,IAAA,+BAAe,EAAC;IAC7B,KAAK,EAAE,OAAO,CAAC,KAAK;IACpB,MAAM,EAAE,OAAO,CAAC,MAAM;CACzB,CAAC,CAAC;AAEH,0DAA0D;AAC1D,IAAI,iBAAiB,GAAG,CAAC,CAAC;AAE1B,uDAAuD;AACvD,IAAI,MAAM,GAAkB,IAAI,CAAC;AACjC,IAAI,SAAS,GAAyC,IAAI,CAAC;AAC3D,IAAI,SAAS,GAAG,2BAA2B,CAAC;AAC5C,IAAI,4BAA4B,GAAuB,SAAS,CAAC;AACjE,IAAI,SAAS,GAAuB,SAAS,CAAC;AAE9C,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;IACtC,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;IAErC,sDAAsD;IACtD,MAAM,OAAO,EAAE,CAAC;IAEhB,wCAAwC;IACxC,SAAS,EAAE,CAAC;IACZ,WAAW,EAAE,CAAC;AAClB,CAAC;AAED,SAAS,SAAS;IACd,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;IACrC,OAAO,CAAC,GAAG,CAAC,2FAA2F,CAAC,CAAC;IACzG,OAAO,CAAC,GAAG,CAAC,uDAAuD,CAAC,CAAC;IACrE,OAAO,CAAC,GAAG,CAAC,8DAA8D,CAAC,CAAC;IAC5E,OAAO,CAAC,GAAG,CAAC,wDAAwD,CAAC,CAAC;IACtE,OAAO,CAAC,GAAG,CAAC,qDAAqD,CAAC,C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C,CAAC;QAE/D,qDAAqD;QACrD,IAAI,MAAM,IAAI,SAAS,EAAE,CAAC;YACtB,MAAM,UAAU,EAAE,CAAC;YACnB,OAAO,CAAC,GAAG,CAAC,wCAAwC,CAAC,CAAC;QAC1D,CAAC;aAAM,CAAC;YACJ,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;QAC5C,CAAC;QAED,wBAAwB;QACxB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,gBAAgB;AAChB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;IACjD,MAAM,OAAO,EAAE,CAAC;AACpB,CAAC,CAAC,CAAC;AAEH,+BAA+B;AAC/B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts b/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts new file mode 100644 index 0000000000..c2679e6694 --- /dev/null +++ b/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=streamableHttpWithSseFallbackClient.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts.map b/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts.map new file mode 100644 index 0000000000..b79ae2a72c --- /dev/null +++ b/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttpWithSseFallbackClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/streamableHttpWithSseFallbackClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js b/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js new file mode 100644 index 0000000000..bf3e9a885c --- /dev/null +++ b/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js @@ -0,0 +1,168 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +const index_js_1 = require("../../client/index.js"); +const streamableHttp_js_1 = require("../../client/streamableHttp.js"); +const sse_js_1 = require("../../client/sse.js"); +const types_js_1 = require("../../types.js"); +/** + * Simplified Backwards Compatible MCP Client + * + * This client demonstrates backward compatibility with both: + * 1. Modern servers using Streamable HTTP transport (protocol version 2025-03-26) + * 2. Older servers using HTTP+SSE transport (protocol version 2024-11-05) + * + * Following the MCP specification for backwards compatibility: + * - Attempts to POST an initialize request to the server URL first (modern transport) + * - If that fails with 4xx status, falls back to GET request for SSE stream (older transport) + */ +// Command line args processing +const args = process.argv.slice(2); +const serverUrl = args[0] || 'http://localhost:3000/mcp'; +async function main() { + console.log('MCP Backwards Compatible Client'); + console.log('==============================='); + console.log(`Connecting to server at: ${serverUrl}`); + let client; + let transport; + try { + // Try connecting with automatic transport detection + const connection = await connectWithBackwardsCompatibility(serverUrl); + client = connection.client; + transport = connection.transport; + // Set up notification handler + client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => { + console.log(`Notification: ${notification.params.level} - ${notification.params.data}`); + }); + // DEMO WORKFLOW: + // 1. List available tools + console.log('\n=== Listing Available Tools ==='); + await listTools(client); + // 2. Call the notification tool + console.log('\n=== Starting Notification Stream ==='); + await startNotificationTool(client); + // 3. Wait for all notifications (5 seconds) + console.log('\n=== Waiting for all notifications ==='); + await new Promise(resolve => setTimeout(resolve, 5000)); + // 4. Disconnect + console.log('\n=== Disconnecting ==='); + await transport.close(); + console.log('Disconnected from MCP server'); + } + catch (error) { + console.error('Error running client:', error); + process.exit(1); + } +} +/** + * Connect to an MCP server with backwards compatibility + * Following the spec for client backward compatibility + */ +async function connectWithBackwardsCompatibility(url) { + console.log('1. Trying Streamable HTTP transport first...'); + // Step 1: Try Streamable HTTP transport first + const client = new index_js_1.Client({ + name: 'backwards-compatible-client', + version: '1.0.0' + }); + client.onerror = error => { + console.error('Client error:', error); + }; + const baseUrl = new URL(url); + try { + // Create modern transport + const streamableTransport = new streamableHttp_js_1.StreamableHTTPClientTransport(baseUrl); + await client.connect(streamableTransport); + console.log('Successfully connected using modern Streamable HTTP transport.'); + return { + client, + transport: streamableTransport, + transportType: 'streamable-http' + }; + } + catch (error) { + // Step 2: If transport fails, try the older SSE transport + console.log(`StreamableHttp transport connection failed: ${error}`); + console.log('2. Falling back to deprecated HTTP+SSE transport...'); + try { + // Create SSE transport pointing to /sse endpoint + const sseTransport = new sse_js_1.SSEClientTransport(baseUrl); + const sseClient = new index_js_1.Client({ + name: 'backwards-compatible-client', + version: '1.0.0' + }); + await sseClient.connect(sseTransport); + console.log('Successfully connected using deprecated HTTP+SSE transport.'); + return { + client: sseClient, + transport: sseTransport, + transportType: 'sse' + }; + } + catch (sseError) { + console.error(`Failed to connect with either transport method:\n1. Streamable HTTP error: ${error}\n2. SSE error: ${sseError}`); + throw new Error('Could not connect to server with any available transport'); + } + } +} +/** + * List available tools on the server + */ +async function listTools(client) { + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - ${tool.name}: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server: ${error}`); + } +} +/** + * Start a notification stream by calling the notification tool + */ +async function startNotificationTool(client) { + try { + // Call the notification tool using reasonable defaults + const request = { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 1000, // 1 second between notifications + count: 5 // Send 5 notifications + } + } + }; + console.log('Calling notification tool...'); + const result = await client.request(request, types_js_1.CallToolResultSchema); + console.log('Tool result:'); + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + catch (error) { + console.log(`Error calling notification tool: ${error}`); + } +} +// Start the client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=streamableHttpWithSseFallbackClient.js.map \ No newline at end of file diff --git a/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js.map b/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js.map new file mode 100644 index 0000000000..f3bec99c5f --- /dev/null +++ b/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttpWithSseFallbackClient.js","sourceRoot":"","sources":["../../../../src/examples/client/streamableHttpWithSseFallbackClient.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,sEAA+E;AAC/E,gDAAyD;AACzD,6CAMwB;AAExB;;;;;;;;;;GAUG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AAEzD,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,CAAC,4BAA4B,SAAS,EAAE,CAAC,CAAC;IAErD,IAAI,MAAc,CAAC;IACnB,IAAI,SAA6D,CAAC;IAElE,IAAI,CAAC;QACD,oDAAoD;QACpD,MAAM,UAAU,GAAG,MAAM,iCAAiC,CAAC,SAAS,CAAC,CAAC;QACtE,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC;QAC3B,SAA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CAAC,cAAc,CAAC,CAAC;QAC5B,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;YAC1B,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gBACvB,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;YAClC,CAAC;iBAAM,CAAC;gBACJ,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,WAAW,EAAE,IAAI,CAAC,CAAC;YACjD,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,GAAG,CAAC,oCAAoC,KAAK,EAAE,CAAC,CAAC;IAC7D,CAAC;AACL,CAAC;AAED,mBAAmB;AACnB,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts b/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts new file mode 100644 index 0000000000..218aeac8b2 --- /dev/null +++ b/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts @@ -0,0 +1,78 @@ +import { AuthorizationParams, OAuthServerProvider } from '../../server/auth/provider.js'; +import { OAuthRegisteredClientsStore } from '../../server/auth/clients.js'; +import { OAuthClientInformationFull, OAuthMetadata, OAuthTokens } from '../../shared/auth.js'; +import { Response } from 'express'; +import { AuthInfo } from '../../server/auth/types.js'; +export declare class DemoInMemoryClientsStore implements OAuthRegisteredClientsStore { + private clients; + getClient(clientId: string): Promise<{ + redirect_uris: string[]; + client_id: string; + token_endpoint_auth_method?: string | undefined; + grant_types?: string[] | undefined; + response_types?: string[] | undefined; + client_name?: string | undefined; + client_uri?: string | undefined; + logo_uri?: string | undefined; + scope?: string | undefined; + contacts?: string[] | undefined; + tos_uri?: string | undefined; + policy_uri?: string | undefined; + jwks_uri?: string | undefined; + jwks?: any; + software_id?: string | undefined; + software_version?: string | undefined; + software_statement?: string | undefined; + client_secret?: string | undefined; + client_id_issued_at?: number | undefined; + client_secret_expires_at?: number | undefined; + } | undefined>; + registerClient(clientMetadata: OAuthClientInformationFull): Promise<{ + redirect_uris: string[]; + client_id: string; + token_endpoint_auth_method?: string | undefined; + grant_types?: string[] | undefined; + response_types?: string[] | undefined; + client_name?: string | undefined; + client_uri?: string | undefined; + logo_uri?: string | undefined; + scope?: string | undefined; + contacts?: string[] | undefined; + tos_uri?: string | undefined; + policy_uri?: string | undefined; + jwks_uri?: string | undefined; + jwks?: any; + software_id?: string | undefined; + software_version?: string | undefined; + software_statement?: string | undefined; + client_secret?: string | undefined; + client_id_issued_at?: number | undefined; + client_secret_expires_at?: number | undefined; + }>; +} +/** + * 🚨 DEMO ONLY - NOT FOR PRODUCTION + * + * This example demonstrates MCP OAuth flow but lacks some of the features required for production use, + * for example: + * - Persistent token storage + * - Rate limiting + */ +export declare class DemoInMemoryAuthProvider implements OAuthServerProvider { + private validateResource?; + clientsStore: DemoInMemoryClientsStore; + private codes; + private tokens; + constructor(validateResource?: ((resource?: URL) => boolean) | undefined); + authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; + challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise; + exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, _codeVerifier?: string): Promise; + exchangeRefreshToken(_client: OAuthClientInformationFull, _refreshToken: string, _scopes?: string[], _resource?: URL): Promise; + verifyAccessToken(token: string): Promise; +} +export declare const setupAuthServer: ({ authServerUrl, mcpServerUrl, strictResource }: { + authServerUrl: URL; + mcpServerUrl: URL; + strictResource: boolean; +}) => OAuthMetadata; +//# sourceMappingURL=demoInMemoryOAuthProvider.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts.map b/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts.map new file mode 100644 index 0000000000..8a4a43fe8d --- /dev/null +++ b/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"demoInMemoryOAuthProvider.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/demoInMemoryOAuthProvider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACzF,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAgB,EAAW,QAAQ,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAKtD,qBAAa,wBAAyB,YAAW,2BAA2B;IACxE,OAAO,CAAC,OAAO,CAAiD;IAE1D,SAAS,CAAC,QAAQ,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;IAI1B,cAAc,CAAC,cAAc,EAAE,0BAA0B;;;;;;;;;;;;;;;;;;;;;;CAIlE;AAED;;;;;;;GAOG;AACH,qBAAa,wBAAyB,YAAW,mBAAmB;IAWpD,OAAO,CAAC,gBAAgB,CAAC;IAVrC,YAAY,2BAAkC;IAC9C,OAAO,CAAC,KAAK,CAMT;IACJ,OAAO,CAAC,MAAM,CAA+B;gBAEzB,gBAAgB,CAAC,GAAE,CAAC,QAAQ,CAAC,EAAE,GAAG,KAAK,OAAO,aAAA;IAE5D,SAAS,CAAC,MAAM,EAAE,0BAA0B,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAwCxG,6BAA6B,CAAC,MAAM,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAU7G,yBAAyB,CAC3B,MAAM,EAAE,0BAA0B,EAClC,iBAAiB,EAAE,MAAM,EAGzB,aAAa,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,WAAW,CAAC;IAoCjB,oBAAoB,CACtB,OAAO,EAAE,0BAA0B,EACnC,aAAa,EAAE,MAAM,EACrB,OAAO,CAAC,EAAE,MAAM,EAAE,EAClB,SAAS,CAAC,EAAE,GAAG,GAChB,OAAO,CAAC,WAAW,CAAC;IAIjB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;CAc5D;AAED,eAAO,MAAM,eAAe,oDAIzB;IACC,aAAa,EAAE,GAAG,CAAC;IACnB,YAAY,EAAE,GAAG,CAAC;IAClB,cAAc,EAAE,OAAO,CAAC;CAC3B,KAAG,aA+EH,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/demoInMemoryOAuthProvider.js b/dist/cjs/examples/server/demoInMemoryOAuthProvider.js new file mode 100644 index 0000000000..c439a34039 --- /dev/null +++ b/dist/cjs/examples/server/demoInMemoryOAuthProvider.js @@ -0,0 +1,205 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setupAuthServer = exports.DemoInMemoryAuthProvider = exports.DemoInMemoryClientsStore = void 0; +const node_crypto_1 = require("node:crypto"); +const express_1 = __importDefault(require("express")); +const router_js_1 = require("../../server/auth/router.js"); +const auth_utils_js_1 = require("../../shared/auth-utils.js"); +const errors_js_1 = require("../../server/auth/errors.js"); +class DemoInMemoryClientsStore { + constructor() { + this.clients = new Map(); + } + async getClient(clientId) { + return this.clients.get(clientId); + } + async registerClient(clientMetadata) { + this.clients.set(clientMetadata.client_id, clientMetadata); + return clientMetadata; + } +} +exports.DemoInMemoryClientsStore = DemoInMemoryClientsStore; +/** + * 🚨 DEMO ONLY - NOT FOR PRODUCTION + * + * This example demonstrates MCP OAuth flow but lacks some of the features required for production use, + * for example: + * - Persistent token storage + * - Rate limiting + */ +class DemoInMemoryAuthProvider { + constructor(validateResource) { + this.validateResource = validateResource; + this.clientsStore = new DemoInMemoryClientsStore(); + this.codes = new Map(); + this.tokens = new Map(); + } + async authorize(client, params, res) { + const code = (0, node_crypto_1.randomUUID)(); + const searchParams = new URLSearchParams({ + code + }); + if (params.state !== undefined) { + searchParams.set('state', params.state); + } + this.codes.set(code, { + client, + params + }); + // Simulate a user login + // Set a secure HTTP-only session cookie with authorization info + if (res.cookie) { + const authCookieData = { + userId: 'demo_user', + name: 'Demo User', + timestamp: Date.now() + }; + res.cookie('demo_session', JSON.stringify(authCookieData), { + httpOnly: true, + secure: false, // In production, this should be true + sameSite: 'lax', + maxAge: 24 * 60 * 60 * 1000, // 24 hours - for demo purposes + path: '/' // Available to all routes + }); + } + if (!client.redirect_uris.includes(params.redirectUri)) { + throw new errors_js_1.InvalidRequestError('Unregistered redirect_uri'); + } + const targetUrl = new URL(params.redirectUri); + targetUrl.search = searchParams.toString(); + res.redirect(targetUrl.toString()); + } + async challengeForAuthorizationCode(client, authorizationCode) { + // Store the challenge with the code data + const codeData = this.codes.get(authorizationCode); + if (!codeData) { + throw new Error('Invalid authorization code'); + } + return codeData.params.codeChallenge; + } + async exchangeAuthorizationCode(client, authorizationCode, + // Note: code verifier is checked in token.ts by default + // it's unused here for that reason. + _codeVerifier) { + const codeData = this.codes.get(authorizationCode); + if (!codeData) { + throw new Error('Invalid authorization code'); + } + if (codeData.client.client_id !== client.client_id) { + throw new Error(`Authorization code was not issued to this client, ${codeData.client.client_id} != ${client.client_id}`); + } + if (this.validateResource && !this.validateResource(codeData.params.resource)) { + throw new Error(`Invalid resource: ${codeData.params.resource}`); + } + this.codes.delete(authorizationCode); + const token = (0, node_crypto_1.randomUUID)(); + const tokenData = { + token, + clientId: client.client_id, + scopes: codeData.params.scopes || [], + expiresAt: Date.now() + 3600000, // 1 hour + resource: codeData.params.resource, + type: 'access' + }; + this.tokens.set(token, tokenData); + return { + access_token: token, + token_type: 'bearer', + expires_in: 3600, + scope: (codeData.params.scopes || []).join(' ') + }; + } + async exchangeRefreshToken(_client, _refreshToken, _scopes, _resource) { + throw new Error('Not implemented for example demo'); + } + async verifyAccessToken(token) { + const tokenData = this.tokens.get(token); + if (!tokenData || !tokenData.expiresAt || tokenData.expiresAt < Date.now()) { + throw new Error('Invalid or expired token'); + } + return { + token, + clientId: tokenData.clientId, + scopes: tokenData.scopes, + expiresAt: Math.floor(tokenData.expiresAt / 1000), + resource: tokenData.resource + }; + } +} +exports.DemoInMemoryAuthProvider = DemoInMemoryAuthProvider; +const setupAuthServer = ({ authServerUrl, mcpServerUrl, strictResource }) => { + // Create separate auth server app + // NOTE: This is a separate app on a separate port to illustrate + // how to separate an OAuth Authorization Server from a Resource + // server in the SDK. The SDK is not intended to be provide a standalone + // authorization server. + const validateResource = strictResource + ? (resource) => { + if (!resource) + return false; + const expectedResource = (0, auth_utils_js_1.resourceUrlFromServerUrl)(mcpServerUrl); + return resource.toString() === expectedResource.toString(); + } + : undefined; + const provider = new DemoInMemoryAuthProvider(validateResource); + const authApp = (0, express_1.default)(); + authApp.use(express_1.default.json()); + // For introspection requests + authApp.use(express_1.default.urlencoded()); + // Add OAuth routes to the auth server + // NOTE: this will also add a protected resource metadata route, + // but it won't be used, so leave it. + authApp.use((0, router_js_1.mcpAuthRouter)({ + provider, + issuerUrl: authServerUrl, + scopesSupported: ['mcp:tools'] + })); + authApp.post('/introspect', async (req, res) => { + try { + const { token } = req.body; + if (!token) { + res.status(400).json({ error: 'Token is required' }); + return; + } + const tokenInfo = await provider.verifyAccessToken(token); + res.json({ + active: true, + client_id: tokenInfo.clientId, + scope: tokenInfo.scopes.join(' '), + exp: tokenInfo.expiresAt, + aud: tokenInfo.resource + }); + return; + } + catch (error) { + res.status(401).json({ + active: false, + error: 'Unauthorized', + error_description: `Invalid token: ${error}` + }); + } + }); + const auth_port = authServerUrl.port; + // Start the auth server + authApp.listen(auth_port, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`OAuth Authorization Server listening on port ${auth_port}`); + }); + // Note: we could fetch this from the server, but then we end up + // with some top level async which gets annoying. + const oauthMetadata = (0, router_js_1.createOAuthMetadata)({ + provider, + issuerUrl: authServerUrl, + scopesSupported: ['mcp:tools'] + }); + oauthMetadata.introspection_endpoint = new URL('/introspect', authServerUrl).href; + return oauthMetadata; +}; +exports.setupAuthServer = setupAuthServer; +//# sourceMappingURL=demoInMemoryOAuthProvider.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/demoInMemoryOAuthProvider.js.map b/dist/cjs/examples/server/demoInMemoryOAuthProvider.js.map new file mode 100644 index 0000000000..e19a20db90 --- /dev/null +++ b/dist/cjs/examples/server/demoInMemoryOAuthProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"demoInMemoryOAuthProvider.js","sourceRoot":"","sources":["../../../../src/examples/server/demoInMemoryOAuthProvider.ts"],"names":[],"mappings":";;;;;;AAAA,6CAAyC;AAIzC,sDAAqD;AAErD,2DAAiF;AACjF,8DAAsE;AACtE,2DAAkE;AAElE,MAAa,wBAAwB;IAArC;QACY,YAAO,GAAG,IAAI,GAAG,EAAsC,CAAC;IAUpE,CAAC;IARG,KAAK,CAAC,SAAS,CAAC,QAAgB;QAC5B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACtC,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,cAA0C;QAC3D,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;QAC3D,OAAO,cAAc,CAAC;IAC1B,CAAC;CACJ;AAXD,4DAWC;AAED;;;;;;;GAOG;AACH,MAAa,wBAAwB;IAWjC,YAAoB,gBAA8C;QAA9C,qBAAgB,GAAhB,gBAAgB,CAA8B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Aa;QACxB,eAAe,EAAE,CAAC,WAAW,CAAC;KACjC,CAAC,CAAC;IAEH,aAAa,CAAC,sBAAsB,GAAG,IAAI,GAAG,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC,IAAI,CAAC;IAElF,OAAO,aAAa,CAAC;AACzB,CAAC,CAAC;AAvFW,QAAA,eAAe,mBAuF1B"} \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationFormExample.d.ts b/dist/cjs/examples/server/elicitationFormExample.d.ts new file mode 100644 index 0000000000..e4b736e0f2 --- /dev/null +++ b/dist/cjs/examples/server/elicitationFormExample.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=elicitationFormExample.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationFormExample.d.ts.map b/dist/cjs/examples/server/elicitationFormExample.d.ts.map new file mode 100644 index 0000000000..c569df428d --- /dev/null +++ b/dist/cjs/examples/server/elicitationFormExample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationFormExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/elicitationFormExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationFormExample.js b/dist/cjs/examples/server/elicitationFormExample.js new file mode 100644 index 0000000000..e25ac92059 --- /dev/null +++ b/dist/cjs/examples/server/elicitationFormExample.js @@ -0,0 +1,441 @@ +"use strict"; +// Run with: npx tsx src/examples/server/elicitationFormExample.ts +// +// This example demonstrates how to use form elicitation to collect structured user input +// with JSON Schema validation via a local HTTP server with SSE streaming. +// Form elicitation allows servers to request *non-sensitive* user input through the client +// with schema-based validation. +// Note: See also elicitationUrlExample.ts for an example of using URL elicitation +// to collect *sensitive* user input via a browser. +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const node_crypto_1 = require("node:crypto"); +const cors_1 = __importDefault(require("cors")); +const express_1 = __importDefault(require("express")); +const mcp_js_1 = require("../../server/mcp.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const types_js_1 = require("../../types.js"); +// Create MCP server - it will automatically use AjvJsonSchemaValidator with sensible defaults +// The validator supports format validation (email, date, etc.) if ajv-formats is installed +const mcpServer = new mcp_js_1.McpServer({ + name: 'form-elicitation-example-server', + version: '1.0.0' +}, { + capabilities: {} +}); +/** + * Example 1: Simple user registration tool + * Collects username, email, and password from the user + */ +mcpServer.registerTool('register_user', { + description: 'Register a new user account by collecting their information', + inputSchema: {} +}, async () => { + try { + // Request user information through form elicitation + const result = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Please provide your registration information:', + requestedSchema: { + type: 'object', + properties: { + username: { + type: 'string', + title: 'Username', + description: 'Your desired username (3-20 characters)', + minLength: 3, + maxLength: 20 + }, + email: { + type: 'string', + title: 'Email', + description: 'Your email address', + format: 'email' + }, + password: { + type: 'string', + title: 'Password', + description: 'Your password (min 8 characters)', + minLength: 8 + }, + newsletter: { + type: 'boolean', + title: 'Newsletter', + description: 'Subscribe to newsletter?', + default: false + } + }, + required: ['username', 'email', 'password'] + } + }); + // Handle the different possible actions + if (result.action === 'accept' && result.content) { + const { username, email, newsletter } = result.content; + return { + content: [ + { + type: 'text', + text: `Registration successful!\n\nUsername: ${username}\nEmail: ${email}\nNewsletter: ${newsletter ? 'Yes' : 'No'}` + } + ] + }; + } + else if (result.action === 'decline') { + return { + content: [ + { + type: 'text', + text: 'Registration cancelled by user.' + } + ] + }; + } + else { + return { + content: [ + { + type: 'text', + text: 'Registration was cancelled.' + } + ] + }; + } + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Registration failed: ${error instanceof Error ? error.message : String(error)}` + } + ], + isError: true + }; + } +}); +/** + * Example 2: Multi-step workflow with multiple form elicitation requests + * Demonstrates how to collect information in multiple steps + */ +mcpServer.registerTool('create_event', { + description: 'Create a calendar event by collecting event details', + inputSchema: {} +}, async () => { + try { + // Step 1: Collect basic event information + const basicInfo = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Step 1: Enter basic event information', + requestedSchema: { + type: 'object', + properties: { + title: { + type: 'string', + title: 'Event Title', + description: 'Name of the event', + minLength: 1 + }, + description: { + type: 'string', + title: 'Description', + description: 'Event description (optional)' + } + }, + required: ['title'] + } + }); + if (basicInfo.action !== 'accept' || !basicInfo.content) { + return { + content: [{ type: 'text', text: 'Event creation cancelled.' }] + }; + } + // Step 2: Collect date and time + const dateTime = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Step 2: Enter date and time', + requestedSchema: { + type: 'object', + properties: { + date: { + type: 'string', + title: 'Date', + description: 'Event date', + format: 'date' + }, + startTime: { + type: 'string', + title: 'Start Time', + description: 'Event start time (HH:MM)' + }, + duration: { + type: 'integer', + title: 'Duration', + description: 'Duration in minutes', + minimum: 15, + maximum: 480 + } + }, + required: ['date', 'startTime', 'duration'] + } + }); + if (dateTime.action !== 'accept' || !dateTime.content) { + return { + content: [{ type: 'text', text: 'Event creation cancelled.' }] + }; + } + // Combine all collected information + const event = { + ...basicInfo.content, + ...dateTime.content + }; + return { + content: [ + { + type: 'text', + text: `Event created successfully!\n\n${JSON.stringify(event, null, 2)}` + } + ] + }; + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Event creation failed: ${error instanceof Error ? error.message : String(error)}` + } + ], + isError: true + }; + } +}); +/** + * Example 3: Collecting address information + * Demonstrates validation with patterns and optional fields + */ +mcpServer.registerTool('update_shipping_address', { + description: 'Update shipping address with validation', + inputSchema: {} +}, async () => { + try { + const result = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Please provide your shipping address:', + requestedSchema: { + type: 'object', + properties: { + name: { + type: 'string', + title: 'Full Name', + description: 'Recipient name', + minLength: 1 + }, + street: { + type: 'string', + title: 'Street Address', + minLength: 1 + }, + city: { + type: 'string', + title: 'City', + minLength: 1 + }, + state: { + type: 'string', + title: 'State/Province', + minLength: 2, + maxLength: 2 + }, + zipCode: { + type: 'string', + title: 'ZIP/Postal Code', + description: '5-digit ZIP code' + }, + phone: { + type: 'string', + title: 'Phone Number (optional)', + description: 'Contact phone number' + } + }, + required: ['name', 'street', 'city', 'state', 'zipCode'] + } + }); + if (result.action === 'accept' && result.content) { + return { + content: [ + { + type: 'text', + text: `Address updated successfully!\n\n${JSON.stringify(result.content, null, 2)}` + } + ] + }; + } + else if (result.action === 'decline') { + return { + content: [{ type: 'text', text: 'Address update cancelled by user.' }] + }; + } + else { + return { + content: [{ type: 'text', text: 'Address update was cancelled.' }] + }; + } + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Address update failed: ${error instanceof Error ? error.message : String(error)}` + } + ], + isError: true + }; + } +}); +async function main() { + const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000; + const app = (0, express_1.default)(); + app.use(express_1.default.json()); + // Allow CORS for all domains, expose the Mcp-Session-Id header + app.use((0, cors_1.default)({ + origin: '*', + exposedHeaders: ['Mcp-Session-Id'] + })); + // Map to store transports by session ID + const transports = {}; + // MCP POST endpoint + const mcpPostHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (sessionId) { + console.log(`Received MCP request for session: ${sessionId}`); + } + try { + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport for this session + transport = transports[sessionId]; + } + else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) { + // New initialization request - create new transport + transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + } + }; + // Connect the transport to the MCP server BEFORE handling the request + await mcpServer.connect(transport); + await transport.handleRequest(req, res, req.body); + return; + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } + }; + app.post('/mcp', mcpPostHandler); + // Handle GET requests for SSE streams + const mcpGetHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Establishing SSE stream for session ${sessionId}`); + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + }; + app.get('/mcp', mcpGetHandler); + // Handle DELETE requests for session termination + const mcpDeleteHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Received session termination request for session ${sessionId}`); + try { + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + } + catch (error) { + console.error('Error handling session termination:', error); + if (!res.headersSent) { + res.status(500).send('Error processing session termination'); + } + } + }; + app.delete('/mcp', mcpDeleteHandler); + // Start listening + app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Form elicitation example server is running on http://localhost:${PORT}/mcp`); + console.log('Available tools:'); + console.log(' - register_user: Collect user registration information'); + console.log(' - create_event: Multi-step event creation'); + console.log(' - update_shipping_address: Collect and validate address'); + console.log('\nConnect your MCP client to this server using the HTTP transport.'); + }); + // Handle server shutdown + process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); + }); +} +main().catch(error => { + console.error('Server error:', error); + process.exit(1); +}); +//# sourceMappingURL=elicitationFormExample.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationFormExample.js.map b/dist/cjs/examples/server/elicitationFormExample.js.map new file mode 100644 index 0000000000..fc5ebcd472 --- /dev/null +++ b/dist/cjs/examples/server/elicitationFormExample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationFormExample.js","sourceRoot":"","sources":["../../../../src/examples/server/elicitationFormExample.ts"],"names":[],"mappings":";AAAA,kEAAkE;AAClE,EAAE;AACF,yFAAyF;AACzF,0EAA0E;AAC1E,2FAA2F;AAC3F,gCAAgC;AAChC,kFAAkF;AAClF,mDAAmD;;;;;AAEnD,6CAAyC;AACzC,gDAAwB;AACxB,sDAA+D;AAC/D,gDAAgD;AAChD,sEAA+E;AAC/E,6CAAqD;AAErD,8FAA8F;AAC9F,2FAA2F;AAC3F,MAAM,SAAS,GAAG,IAAI,kBAAS,CAC3B;IACI,IAAI,EAAE,iCAAiC;IACvC,OAAO,EAAE,OAAO;CACnB,EACD;IACI,YAAY,EAAE,EAAE;CACnB,CACJ,CAAC;AAEF;;;GAGG;AACH,SAAS,CAAC,YAAY,CAClB,eAAe,EACf;IACI,WAAW,EAAE,6DAA6D;IAC1E,WAAW,EAAE,EAAE;CAClB,EACD,KAAK,IAAI,EAAE;IACP,IAAI,CAAC;QACD,oDAAoD;QACpD,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,MAAM,CAAC,WAAW,CAAC;YAC9C,IAAI,EAAE,MAAM;YACZ,OAAO,EAAE,+CAA+C;YACxD,eAAe,EAAE;gBACb,IAAI,EAAE,QAAQ;gBACd,UAAU,EAAE;oBACR,QAAQ,EAAE;wBACN,IAAI,EAAE,QAAQ;wBACd,KAAK,EAAE,UAAU;wBACjB,WAAW,EAAE,yCAAyC;wBACtD,SAAS,EAAE,CAAC;wBACZ,SAAS,EAAE,EAAE;qBAChB;oBACD,KAAK,EAAE;wBACH,IAAI,EAAE,QAAQ;wBACd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AC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationUrlExample.d.ts b/dist/cjs/examples/server/elicitationUrlExample.d.ts new file mode 100644 index 0000000000..611f6eba22 --- /dev/null +++ b/dist/cjs/examples/server/elicitationUrlExample.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=elicitationUrlExample.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationUrlExample.d.ts.map b/dist/cjs/examples/server/elicitationUrlExample.d.ts.map new file mode 100644 index 0000000000..04acd6664d --- /dev/null +++ b/dist/cjs/examples/server/elicitationUrlExample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/elicitationUrlExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationUrlExample.js b/dist/cjs/examples/server/elicitationUrlExample.js new file mode 100644 index 0000000000..e828ccae4f --- /dev/null +++ b/dist/cjs/examples/server/elicitationUrlExample.js @@ -0,0 +1,655 @@ +"use strict"; +// Run with: npx tsx src/examples/server/elicitationUrlExample.ts +// +// This example demonstrates how to use URL elicitation to securely collect +// *sensitive* user input in a remote (HTTP) server. +// URL elicitation allows servers to prompt the end-user to open a URL in their browser +// to collect sensitive information. +// Note: See also elicitationFormExample.ts for an example of using form (not URL) elicitation +// to collect *non-sensitive* user input with a structured schema. +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const express_1 = __importDefault(require("express")); +const node_crypto_1 = require("node:crypto"); +const zod_1 = require("zod"); +const mcp_js_1 = require("../../server/mcp.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const router_js_1 = require("../../server/auth/router.js"); +const bearerAuth_js_1 = require("../../server/auth/middleware/bearerAuth.js"); +const types_js_1 = require("../../types.js"); +const inMemoryEventStore_js_1 = require("../shared/inMemoryEventStore.js"); +const demoInMemoryOAuthProvider_js_1 = require("./demoInMemoryOAuthProvider.js"); +const auth_utils_js_1 = require("../../shared/auth-utils.js"); +const cors_1 = __importDefault(require("cors")); +// Create an MCP server with implementation details +const getServer = () => { + const mcpServer = new mcp_js_1.McpServer({ + name: 'url-elicitation-http-server', + version: '1.0.0' + }, { + capabilities: { logging: {} } + }); + mcpServer.registerTool('payment-confirm', { + description: 'A tool that confirms a payment directly with a user', + inputSchema: { + cartId: zod_1.z.string().describe('The ID of the cart to confirm') + } + }, async ({ cartId }, extra) => { + /* + In a real world scenario, there would be some logic here to check if the user has the provided cartId. + For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to confirm payment) + */ + const sessionId = extra.sessionId; + if (!sessionId) { + throw new Error('Expected a Session ID'); + } + // Create and track the elicitation + const elicitationId = generateTrackedElicitation(sessionId, elicitationId => mcpServer.server.createElicitationCompletionNotifier(elicitationId)); + throw new types_js_1.UrlElicitationRequiredError([ + { + mode: 'url', + message: 'This tool requires a payment confirmation. Open the link to confirm payment!', + url: `http://localhost:${MCP_PORT}/confirm-payment?session=${sessionId}&elicitation=${elicitationId}&cartId=${encodeURIComponent(cartId)}`, + elicitationId + } + ]); + }); + mcpServer.registerTool('third-party-auth', { + description: 'A demo tool that requires third-party OAuth credentials', + inputSchema: { + param1: zod_1.z.string().describe('First parameter') + } + }, async (_, extra) => { + /* + In a real world scenario, there would be some logic here to check if we already have a valid access token for the user. + Auth info (with a subject or `sub` claim) can be typically be found in `extra.authInfo`. + If we do, we can just return the result of the tool call. + If we don't, we can throw an ElicitationRequiredError to request the user to authenticate. + For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to authenticate). + */ + const sessionId = extra.sessionId; + if (!sessionId) { + throw new Error('Expected a Session ID'); + } + // Create and track the elicitation + const elicitationId = generateTrackedElicitation(sessionId, elicitationId => mcpServer.server.createElicitationCompletionNotifier(elicitationId)); + // Simulate OAuth callback and token exchange after 5 seconds + // In a real app, this would be called from your OAuth callback handler + setTimeout(() => { + console.log(`Simulating OAuth token received for elicitation ${elicitationId}`); + completeURLElicitation(elicitationId); + }, 5000); + throw new types_js_1.UrlElicitationRequiredError([ + { + mode: 'url', + message: 'This tool requires access to your example.com account. Open the link to authenticate!', + url: 'https://www.example.com/oauth/authorize', + elicitationId + } + ]); + }); + return mcpServer; +}; +const elicitationsMap = new Map(); +// Clean up old elicitations after 1 hour to prevent memory leaks +const ELICITATION_TTL_MS = 60 * 60 * 1000; // 1 hour +const CLEANUP_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes +function cleanupOldElicitations() { + const now = new Date(); + for (const [id, metadata] of elicitationsMap.entries()) { + if (now.getTime() - metadata.createdAt.getTime() > ELICITATION_TTL_MS) { + elicitationsMap.delete(id); + console.log(`Cleaned up expired elicitation: ${id}`); + } + } +} +setInterval(cleanupOldElicitations, CLEANUP_INTERVAL_MS); +/** + * Elicitation IDs must be unique strings within the MCP session + * UUIDs are used in this example for simplicity + */ +function generateElicitationId() { + return (0, node_crypto_1.randomUUID)(); +} +/** + * Helper function to create and track a new elicitation. + */ +function generateTrackedElicitation(sessionId, createCompletionNotifier) { + const elicitationId = generateElicitationId(); + // Create a Promise and its resolver for tracking completion + let completeResolver; + const completedPromise = new Promise(resolve => { + completeResolver = resolve; + }); + const completionNotifier = createCompletionNotifier ? createCompletionNotifier(elicitationId) : undefined; + // Store the elicitation in our map + elicitationsMap.set(elicitationId, { + status: 'pending', + completedPromise, + completeResolver: completeResolver, + createdAt: new Date(), + sessionId, + completionNotifier + }); + return elicitationId; +} +/** + * Helper function to complete an elicitation. + */ +function completeURLElicitation(elicitationId) { + const elicitation = elicitationsMap.get(elicitationId); + if (!elicitation) { + console.warn(`Attempted to complete unknown elicitation: ${elicitationId}`); + return; + } + if (elicitation.status === 'complete') { + console.warn(`Elicitation already complete: ${elicitationId}`); + return; + } + // Update metadata + elicitation.status = 'complete'; + // Send completion notification to the client + if (elicitation.completionNotifier) { + console.log(`Sending notifications/elicitation/complete notification for elicitation ${elicitationId}`); + elicitation.completionNotifier().catch(error => { + console.error(`Failed to send completion notification for elicitation ${elicitationId}:`, error); + }); + } + // Resolve the promise to unblock any waiting code + elicitation.completeResolver(); +} +const MCP_PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; +const AUTH_PORT = process.env.MCP_AUTH_PORT ? parseInt(process.env.MCP_AUTH_PORT, 10) : 3001; +const app = (0, express_1.default)(); +app.use(express_1.default.json()); +// Allow CORS all domains, expose the Mcp-Session-Id header +app.use((0, cors_1.default)({ + origin: '*', // Allow all origins + exposedHeaders: ['Mcp-Session-Id'], + credentials: true // Allow cookies to be sent cross-origin +})); +// Set up OAuth (required for this example) +let authMiddleware = null; +// Create auth middleware for MCP endpoints +const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`); +const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); +const oauthMetadata = (0, demoInMemoryOAuthProvider_js_1.setupAuthServer)({ authServerUrl, mcpServerUrl, strictResource: true }); +const tokenVerifier = { + verifyAccessToken: async (token) => { + const endpoint = oauthMetadata.introspection_endpoint; + if (!endpoint) { + throw new Error('No token verification endpoint available in metadata'); + } + const response = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: new URLSearchParams({ + token: token + }).toString() + }); + if (!response.ok) { + throw new Error(`Invalid or expired token: ${await response.text()}`); + } + const data = await response.json(); + if (!data.aud) { + throw new Error(`Resource Indicator (RFC8707) missing`); + } + if (!(0, auth_utils_js_1.checkResourceAllowed)({ requestedResource: data.aud, configuredResource: mcpServerUrl })) { + throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); + } + // Convert the response to AuthInfo format + return { + token, + clientId: data.client_id, + scopes: data.scope ? data.scope.split(' ') : [], + expiresAt: data.exp + }; + } +}; +// Add metadata routes to the main MCP server +app.use((0, router_js_1.mcpAuthMetadataRouter)({ + oauthMetadata, + resourceServerUrl: mcpServerUrl, + scopesSupported: ['mcp:tools'], + resourceName: 'MCP Demo Server' +})); +authMiddleware = (0, bearerAuth_js_1.requireBearerAuth)({ + verifier: tokenVerifier, + requiredScopes: [], + resourceMetadataUrl: (0, router_js_1.getOAuthProtectedResourceMetadataUrl)(mcpServerUrl) +}); +/** + * API Key Form Handling + * + * Many servers today require an API key to operate, but there's no scalable way to do this dynamically for remote servers within MCP protocol. + * URL-mode elicitation enables the server to host a simple form and get the secret data securely from the user without involving the LLM or client. + **/ +async function sendApiKeyElicitation(sessionId, sender, createCompletionNotifier) { + if (!sessionId) { + console.error('No session ID provided'); + throw new Error('Expected a Session ID to track elicitation'); + } + console.log('🔑 URL elicitation demo: Requesting API key from client...'); + const elicitationId = generateTrackedElicitation(sessionId, createCompletionNotifier); + try { + const result = await sender({ + mode: 'url', + message: 'Please provide your API key to authenticate with this server', + // Host the form on the same server. In a real app, you might coordinate passing these state variables differently. + url: `http://localhost:${MCP_PORT}/api-key-form?session=${sessionId}&elicitation=${elicitationId}`, + elicitationId + }); + switch (result.action) { + case 'accept': + console.log('🔑 URL elicitation demo: Client accepted the API key elicitation (now pending form submission)'); + // Wait for the API key to be submitted via the form + // The form submission will complete the elicitation + break; + default: + console.log('🔑 URL elicitation demo: Client declined to provide an API key'); + // In a real app, this might close the connection, but for the demo, we'll continue + break; + } + } + catch (error) { + console.error('Error during API key elicitation:', error); + } +} +// API Key Form endpoint - serves a simple HTML form +app.get('/api-key-form', (req, res) => { + const mcpSessionId = req.query.session; + const elicitationId = req.query.elicitation; + if (!mcpSessionId || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie + // In production, this is often handled by some user auth middleware to ensure the user has a valid session + // This session is different from the MCP session. + // This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in. + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + // Serve a simple HTML form + res.send(` + + + + Submit Your API Key + + + +

API Key Required

+
✓ Logged in as: ${userSession.name}
+
+ + + + +
+
This is a demo showing how a server can securely elicit sensitive data from a user using a URL.
+ + + `); +}); +// Handle API key form submission +app.post('/api-key-form', express_1.default.urlencoded(), (req, res) => { + const { session: sessionId, apiKey, elicitation: elicitationId } = req.body; + if (!sessionId || !apiKey || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie here too + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + // A real app might store this API key to be used later for the user. + console.log(`🔑 Received API key \x1b[32m${apiKey}\x1b[0m for session ${sessionId}`); + // If we have an elicitationId, complete the elicitation + completeURLElicitation(elicitationId); + // Send a success response + res.send(` + + + + Success + + + +
+

Success ✓

+

API key received.

+
+

You can close this window and return to your MCP client.

+ + + `); +}); +// Helper to get the user session from the demo_session cookie +function getUserSessionCookie(cookieHeader) { + if (!cookieHeader) + return null; + const cookies = cookieHeader.split(';'); + for (const cookie of cookies) { + const [name, value] = cookie.trim().split('='); + if (name === 'demo_session' && value) { + try { + return JSON.parse(decodeURIComponent(value)); + } + catch (error) { + console.error('Failed to parse demo_session cookie:', error); + return null; + } + } + } + return null; +} +/** + * Payment Confirmation Form Handling + * + * This demonstrates how a server can use URL-mode elicitation to get user confirmation + * for sensitive operations like payment processing. + **/ +// Payment Confirmation Form endpoint - serves a simple HTML form +app.get('/confirm-payment', (req, res) => { + const mcpSessionId = req.query.session; + const elicitationId = req.query.elicitation; + const cartId = req.query.cartId; + if (!mcpSessionId || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie + // In production, this is often handled by some user auth middleware to ensure the user has a valid session + // This session is different from the MCP session. + // This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in. + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + // Serve a simple HTML form + res.send(` + + + + Confirm Payment + + + +

Confirm Payment

+
✓ Logged in as: ${userSession.name}
+ ${cartId ? `
Cart ID: ${cartId}
` : ''} +
+ ⚠️ Please review your order before confirming. +
+
+ + + ${cartId ? `` : ''} + + +
+
This is a demo showing how a server can securely get user confirmation for sensitive operations using URL-mode elicitation.
+ + + `); +}); +// Handle Payment Confirmation form submission +app.post('/confirm-payment', express_1.default.urlencoded(), (req, res) => { + const { session: sessionId, elicitation: elicitationId, cartId, action } = req.body; + if (!sessionId || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie here too + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + if (action === 'confirm') { + // A real app would process the payment here + console.log(`💳 Payment confirmed for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`); + // Complete the elicitation + completeURLElicitation(elicitationId); + // Send a success response + res.send(` + + + + Payment Confirmed + + + +
+

Payment Confirmed ✓

+

Your payment has been successfully processed.

+ ${cartId ? `

Cart ID: ${cartId}

` : ''} +
+

You can close this window and return to your MCP client.

+ + + `); + } + else if (action === 'cancel') { + console.log(`💳 Payment cancelled for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`); + // The client will still receive a notifications/elicitation/complete notification, + // which indicates that the out-of-band interaction is complete (but not necessarily successful) + completeURLElicitation(elicitationId); + res.send(` + + + + Payment Cancelled + + + +
+

Payment Cancelled

+

Your payment has been cancelled.

+
+

You can close this window and return to your MCP client.

+ + + `); + } + else { + res.status(400).send('

Error

Invalid action

'); + } +}); +// Map to store transports by session ID +const transports = {}; +const sessionsNeedingElicitation = {}; +// MCP POST endpoint +const mcpPostHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + console.debug(`Received MCP POST for session: ${sessionId || 'unknown'}`); + try { + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) { + const server = getServer(); + // New initialization request + const eventStore = new inMemoryEventStore_js_1.InMemoryEventStore(); + transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), + eventStore, // Enable resumability + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + sessionsNeedingElicitation[sessionId] = { + elicitationSender: params => server.server.elicitInput(params), + createCompletionNotifier: elicitationId => server.server.createElicitationCompletionNotifier(elicitationId) + }; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + delete sessionsNeedingElicitation[sid]; + } + }; + // Connect the transport to the MCP server BEFORE handling the request + // so responses can flow back through the same transport + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport - no need to reconnect + // The existing transport is already connected to the server + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}; +// Set up routes with auth middleware +app.post('/mcp', authMiddleware, mcpPostHandler); +// Handle GET requests for SSE streams (using built-in support from StreamableHTTP) +const mcpGetHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + // Check for Last-Event-ID header for resumability + const lastEventId = req.headers['last-event-id']; + if (lastEventId) { + console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`); + } + else { + console.log(`Establishing new SSE stream for session ${sessionId}`); + } + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + if (sessionsNeedingElicitation[sessionId]) { + const { elicitationSender, createCompletionNotifier } = sessionsNeedingElicitation[sessionId]; + // Send an elicitation request to the client in the background + sendApiKeyElicitation(sessionId, elicitationSender, createCompletionNotifier) + .then(() => { + // Only delete on successful send for this demo + delete sessionsNeedingElicitation[sessionId]; + console.log(`🔑 URL elicitation demo: Finished sending API key elicitation request for session ${sessionId}`); + }) + .catch(error => { + console.error('Error sending API key elicitation:', error); + // Keep in map to potentially retry on next reconnect + }); + } +}; +// Set up GET route with conditional auth middleware +app.get('/mcp', authMiddleware, mcpGetHandler); +// Handle DELETE requests for session termination (according to MCP spec) +const mcpDeleteHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Received session termination request for session ${sessionId}`); + try { + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + } + catch (error) { + console.error('Error handling session termination:', error); + if (!res.headersSent) { + res.status(500).send('Error processing session termination'); + } + } +}; +// Set up DELETE route with auth middleware +app.delete('/mcp', authMiddleware, mcpDeleteHandler); +app.listen(MCP_PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Streamable HTTP Server listening on port ${MCP_PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + delete sessionsNeedingElicitation[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=elicitationUrlExample.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationUrlExample.js.map b/dist/cjs/examples/server/elicitationUrlExample.js.map new file mode 100644 index 0000000000..462c721e93 --- /dev/null +++ b/dist/cjs/examples/server/elicitationUrlExample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.js","sourceRoot":"","sources":["../../../../src/examples/server/elicitationUrlExample.ts"],"names":[],"mappings":";AAAA,iEAAiE;AACjE,EAAE;AACF,2EAA2E;AAC3E,oDAAoD;AACpD,uFAAuF;AACvF,oCAAoC;AACpC,8FAA8F;AAC9F,kEAAkE;;;;;AAElE,sDAAqD;AACrD,6CAAyC;AACzC,6BAAwB;AACxB,gDAAgD;AAChD,sEAA+E;AAC/E,2DAA0G;AAC1G,8EAA+E;AAC/E,6CAAwI;AACxI,2EAAqE;AACrE,iFAAiE;AAEjE,8DAAkE;AAElE,gDAAwB;AAExB,mDAAmD;AACnD,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,SAAS,GAAG,IAAI,kBAAS,CAC3B;QACI,IAAI,EAAE,6BAA6B;QACnC,OAAO,EAAE,OAAO;KACnB,EACD;QACI,YAAY,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE;KAChC,CACJ,CAAC;IAEF,SAAS,CAAC,YAAY,CAClB,iBAAiB,EACjB;QACI,WAAW,EAAE,qDAAqD;QAClE,WAAW,EAAE;YACT,MAAM,EAAE,OAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,+BAA+B,CAAC;SAC/D;KACJ,EACD,KAAK,EAAE,EAAE,MAAM,EAAE,EAAE,KAAK,EAA2B,EAAE;QACjD;;;MAGF;QACE,MAAM,SAAS,GAAG,KAAK,CAAC,SAAS,CAAC;QAClC,IAAI,CAAC,SAAS,EAAE,CAAC;YACb,MAAM,IAAI,KAAK,CAAC,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OAAO,CAAC,GAAG,CAAC,gDAAgD,QAAQ,EAAE,CAAC,CAAC;AAC5E,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAEvC,6DAA6D;IAC7D,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACjC,IAAI,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,iCAAiC,SAAS,EAAE,CAAC,CAAC;YAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;YAC7B,OAAO,0BAA0B,CAAC,SAAS,CAAC,CAAC;QACjD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts b/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts new file mode 100644 index 0000000000..477fa6bae7 --- /dev/null +++ b/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=jsonResponseStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts.map b/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts.map new file mode 100644 index 0000000000..ee8117ee2e --- /dev/null +++ b/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonResponseStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/jsonResponseStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/jsonResponseStreamableHttp.js b/dist/cjs/examples/server/jsonResponseStreamableHttp.js new file mode 100644 index 0000000000..fa4802f15e --- /dev/null +++ b/dist/cjs/examples/server/jsonResponseStreamableHttp.js @@ -0,0 +1,175 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const express_1 = __importDefault(require("express")); +const node_crypto_1 = require("node:crypto"); +const mcp_js_1 = require("../../server/mcp.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const z = __importStar(require("zod/v4")); +const types_js_1 = require("../../types.js"); +const cors_1 = __importDefault(require("cors")); +// Create an MCP server with implementation details +const getServer = () => { + const server = new mcp_js_1.McpServer({ + name: 'json-response-streamable-http-server', + version: '1.0.0' + }, { + capabilities: { + logging: {} + } + }); + // Register a simple tool that returns a greeting + server.tool('greet', 'A simple greeting tool', { + name: z.string().describe('Name to greet') + }, async ({ name }) => { + return { + content: [ + { + type: 'text', + text: `Hello, ${name}!` + } + ] + }; + }); + // Register a tool that sends multiple greetings with notifications + server.tool('multi-greet', 'A tool that sends different greetings with delays between them', { + name: z.string().describe('Name to greet') + }, async ({ name }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + await server.sendLoggingMessage({ + level: 'debug', + data: `Starting multi-greet for ${name}` + }, extra.sessionId); + await sleep(1000); // Wait 1 second before first greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending first greeting to ${name}` + }, extra.sessionId); + await sleep(1000); // Wait another second before second greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending second greeting to ${name}` + }, extra.sessionId); + return { + content: [ + { + type: 'text', + text: `Good morning, ${name}!` + } + ] + }; + }); + return server; +}; +const app = (0, express_1.default)(); +app.use(express_1.default.json()); +// Configure CORS to expose Mcp-Session-Id header for browser-based clients +app.use((0, cors_1.default)({ + origin: '*', // Allow all origins - adjust as needed for production + exposedHeaders: ['Mcp-Session-Id'] +})); +// Map to store transports by session ID +const transports = {}; +app.post('/mcp', async (req, res) => { + console.log('Received MCP request:', req.body); + try { + // Check for existing session ID + const sessionId = req.headers['mcp-session-id']; + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) { + // New initialization request - use JSON response mode + transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), + enableJsonResponse: true, // Enable JSON response mode + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Connect the transport to the MCP server BEFORE handling the request + const server = getServer(); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport - no need to reconnect + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +// Handle GET requests for SSE streams according to spec +app.get('/mcp', async (req, res) => { + // Since this is a very simple example, we don't support GET requests for this server + // The spec requires returning 405 Method Not Allowed in this case + res.status(405).set('Allow', 'POST').send('Method Not Allowed'); +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Streamable HTTP Server listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + process.exit(0); +}); +//# sourceMappingURL=jsonResponseStreamableHttp.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/jsonResponseStreamableHttp.js.map b/dist/cjs/examples/server/jsonResponseStreamableHttp.js.map new file mode 100644 index 0000000000..cfe7bc4a31 --- /dev/null +++ b/dist/cjs/examples/server/jsonResponseStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonResponseStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/jsonResponseStreamableHttp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sDAAqD;AACrD,6CAAyC;AACzC,gDAAgD;AAChD,sEAA+E;AAC/E,0CAA4B;AAC5B,6CAAqE;AACrE,gDAAwB;AAExB,mDAAmD;AACnD,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,GAAG,IAAI,kBAAS,CACxB;QACI,IAAI,EAAE,sCAAsC;QAC5C,OAAO,EAAE,OAAO;KACnB,EACD;QACI,YAAY,EAAE;YACV,OAAO,EAAE,EAAE;SACd;KACJ,CACJ,CAAC;IAEF,iDAAiD;IACjD,MAAM,CA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E,GAAa,EAAE,EAAE;IAClD,qFAAqF;IACrF,kEAAkE;IAClE,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;AACpE,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,gDAAgD,IAAI,EAAE,CAAC,CAAC;AACxE,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/mcpServerOutputSchema.d.ts b/dist/cjs/examples/server/mcpServerOutputSchema.d.ts new file mode 100644 index 0000000000..a6cb497473 --- /dev/null +++ b/dist/cjs/examples/server/mcpServerOutputSchema.d.ts @@ -0,0 +1,7 @@ +#!/usr/bin/env node +/** + * Example MCP server using the high-level McpServer API with outputSchema + * This demonstrates how to easily create tools with structured output + */ +export {}; +//# sourceMappingURL=mcpServerOutputSchema.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/mcpServerOutputSchema.d.ts.map b/dist/cjs/examples/server/mcpServerOutputSchema.d.ts.map new file mode 100644 index 0000000000..bd3abdcc26 --- /dev/null +++ b/dist/cjs/examples/server/mcpServerOutputSchema.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mcpServerOutputSchema.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/mcpServerOutputSchema.ts"],"names":[],"mappings":";AACA;;;GAGG"} \ No newline at end of file diff --git a/dist/cjs/examples/server/mcpServerOutputSchema.js b/dist/cjs/examples/server/mcpServerOutputSchema.js new file mode 100644 index 0000000000..4ac7e5cdae --- /dev/null +++ b/dist/cjs/examples/server/mcpServerOutputSchema.js @@ -0,0 +1,95 @@ +#!/usr/bin/env node +"use strict"; +/** + * Example MCP server using the high-level McpServer API with outputSchema + * This demonstrates how to easily create tools with structured output + */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const mcp_js_1 = require("../../server/mcp.js"); +const stdio_js_1 = require("../../server/stdio.js"); +const z = __importStar(require("zod/v4")); +const server = new mcp_js_1.McpServer({ + name: 'mcp-output-schema-high-level-example', + version: '1.0.0' +}); +// Define a tool with structured output - Weather data +server.registerTool('get_weather', { + description: 'Get weather information for a city', + inputSchema: { + city: z.string().describe('City name'), + country: z.string().describe('Country code (e.g., US, UK)') + }, + outputSchema: { + temperature: z.object({ + celsius: z.number(), + fahrenheit: z.number() + }), + conditions: z.enum(['sunny', 'cloudy', 'rainy', 'stormy', 'snowy']), + humidity: z.number().min(0).max(100), + wind: z.object({ + speed_kmh: z.number(), + direction: z.string() + }) + } +}, async ({ city, country }) => { + // Parameters are available but not used in this example + void city; + void country; + // Simulate weather API call + const temp_c = Math.round((Math.random() * 35 - 5) * 10) / 10; + const conditions = ['sunny', 'cloudy', 'rainy', 'stormy', 'snowy'][Math.floor(Math.random() * 5)]; + const structuredContent = { + temperature: { + celsius: temp_c, + fahrenheit: Math.round(((temp_c * 9) / 5 + 32) * 10) / 10 + }, + conditions, + humidity: Math.round(Math.random() * 100), + wind: { + speed_kmh: Math.round(Math.random() * 50), + direction: ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'][Math.floor(Math.random() * 8)] + } + }; + return { + content: [ + { + type: 'text', + text: JSON.stringify(structuredContent, null, 2) + } + ], + structuredContent + }; +}); +async function main() { + const transport = new stdio_js_1.StdioServerTransport(); + await server.connect(transport); + console.error('High-level Output Schema Example Server running on stdio'); +} +main().catch(error => { + console.error('Server error:', error); + process.exit(1); +}); +//# sourceMappingURL=mcpServerOutputSchema.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/mcpServerOutputSchema.js.map b/dist/cjs/examples/server/mcpServerOutputSchema.js.map new file mode 100644 index 0000000000..ba0f8b24c4 --- /dev/null +++ b/dist/cjs/examples/server/mcpServerOutputSchema.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mcpServerOutputSchema.js","sourceRoot":"","sources":["../../../../src/examples/server/mcpServerOutputSchema.ts"],"names":[],"mappings":";;AACA;;;GAGG;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,gDAAgD;AAChD,oDAA6D;AAC7D,0CAA4B;AAE5B,MAAM,MAAM,GAAG,IAAI,kBAAS,CAAC;IACzB,IAAI,EAAE,sCAAsC;IAC5C,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,sDAAsD;AACtD,MAAM,CAAC,YAAY,CACf,aAAa,EACb;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100644 index 0000000000..4269b7814f --- /dev/null +++ b/dist/cjs/examples/server/simpleSseServer.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleSseServer.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleSseServer.d.ts.map b/dist/cjs/examples/server/simpleSseServer.d.ts.map new file mode 100644 index 0000000000..08a1b45021 --- /dev/null +++ b/dist/cjs/examples/server/simpleSseServer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleSseServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleSseServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleSseServer.js b/dist/cjs/examples/server/simpleSseServer.js new file mode 100644 index 0000000000..8b1afd86b2 --- /dev/null +++ b/dist/cjs/examples/server/simpleSseServer.js @@ -0,0 +1,169 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const express_1 = __importDefault(require("express")); +const mcp_js_1 = require("../../server/mcp.js"); +const sse_js_1 = require("../../server/sse.js"); +const z = __importStar(require("zod/v4")); +/** + * This example server demonstrates the deprecated HTTP+SSE transport + * (protocol version 2024-11-05). It mainly used for testing backward compatible clients. + * + * The server exposes two endpoints: + * - /mcp: For establishing the SSE stream (GET) + * - /messages: For receiving client messages (POST) + * + */ +// Create an MCP server instance +const getServer = () => { + const server = new mcp_js_1.McpServer({ + name: 'simple-sse-server', + version: '1.0.0' + }, { capabilities: { logging: {} } }); + server.tool('start-notification-stream', 'Starts sending periodic notifications', { + interval: z.number().describe('Interval in milliseconds between notifications').default(1000), + count: z.number().describe('Number of notifications to send').default(10) + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + // Send the initial notification + await server.sendLoggingMessage({ + level: 'info', + data: `Starting notification stream with ${count} messages every ${interval}ms` + }, extra.sessionId); + // Send periodic notifications + while (counter < count) { + counter++; + await sleep(interval); + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + } + return { + content: [ + { + type: 'text', + text: `Completed sending ${count} notifications every ${interval}ms` + } + ] + }; + }); + return server; +}; +const app = (0, express_1.default)(); +app.use(express_1.default.json()); +// Store transports by session ID +const transports = {}; +// SSE endpoint for establishing the stream +app.get('/mcp', async (req, res) => { + console.log('Received GET request to /sse (establishing SSE stream)'); + try { + // Create a new SSE transport for the client + // The endpoint for POST messages is '/messages' + const transport = new sse_js_1.SSEServerTransport('/messages', res); + // Store the transport by session ID + const sessionId = transport.sessionId; + transports[sessionId] = transport; + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + console.log(`SSE transport closed for session ${sessionId}`); + delete transports[sessionId]; + }; + // Connect the transport to the MCP server + const server = getServer(); + await server.connect(transport); + console.log(`Established SSE stream with session ID: ${sessionId}`); + } + catch (error) { + console.error('Error establishing SSE stream:', error); + if (!res.headersSent) { + res.status(500).send('Error establishing SSE stream'); + } + } +}); +// Messages endpoint for receiving client JSON-RPC requests +app.post('/messages', async (req, res) => { + console.log('Received POST request to /messages'); + // Extract session ID from URL query parameter + // In the SSE protocol, this is added by the client based on the endpoint event + const sessionId = req.query.sessionId; + if (!sessionId) { + console.error('No session ID provided in request URL'); + res.status(400).send('Missing sessionId parameter'); + return; + } + const transport = transports[sessionId]; + if (!transport) { + console.error(`No active transport found for session ID: ${sessionId}`); + res.status(404).send('Session not found'); + return; + } + try { + // Handle the POST message with the transport + await transport.handlePostMessage(req, res, req.body); + } + catch (error) { + console.error('Error handling request:', error); + if (!res.headersSent) { + res.status(500).send('Error handling request'); + } + } +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Simple SSE Server (deprecated protocol version 2024-11-05) listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=simpleSseServer.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleSseServer.js.map b/dist/cjs/examples/server/simpleSseServer.js.map new file mode 100644 index 0000000000..6bb0444a2f --- /dev/null +++ b/dist/cjs/examples/server/simpleSseServer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleSseServer.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleSseServer.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sDAAqD;AACrD,gDAAgD;AAChD,gDAAyD;AACzD,0CAA4B;AAG5B;;;;;;;;GAQG;AAEH,gCAAgC;AAChC,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,GAAG,IAAI,kBAAS,CACxB;QAC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AAI,CAAC,wBAAwB,CAAC,CAAC;QACnD,CAAC;IACL,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,gFAAgF,IAAI,EAAE,CAAC,CAAC;AACxG,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAEvC,6DAA6D;IAC7D,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACjC,IAAI,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,iCAAiC,SAAS,EAAE,CAAC,CAAC;YAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts b/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts new file mode 100644 index 0000000000..0aa4ad2439 --- /dev/null +++ b/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleStatelessStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts.map b/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts.map new file mode 100644 index 0000000000..92deb06ecb --- /dev/null +++ b/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStatelessStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleStatelessStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStatelessStreamableHttp.js b/dist/cjs/examples/server/simpleStatelessStreamableHttp.js new file mode 100644 index 0000000000..b82ab00f81 --- /dev/null +++ b/dist/cjs/examples/server/simpleStatelessStreamableHttp.js @@ -0,0 +1,170 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const express_1 = __importDefault(require("express")); +const mcp_js_1 = require("../../server/mcp.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const z = __importStar(require("zod/v4")); +const cors_1 = __importDefault(require("cors")); +const getServer = () => { + // Create an MCP server with implementation details + const server = new mcp_js_1.McpServer({ + name: 'stateless-streamable-http-server', + version: '1.0.0' + }, { capabilities: { logging: {} } }); + // Register a simple prompt + server.prompt('greeting-template', 'A simple greeting prompt template', { + name: z.string().describe('Name to include in greeting') + }, async ({ name }) => { + return { + messages: [ + { + role: 'user', + content: { + type: 'text', + text: `Please greet ${name} in a friendly manner.` + } + } + ] + }; + }); + // Register a tool specifically for testing resumability + server.tool('start-notification-stream', 'Starts sending periodic notifications for testing resumability', { + interval: z.number().describe('Interval in milliseconds between notifications').default(100), + count: z.number().describe('Number of notifications to send (0 for 100)').default(10) + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + while (count === 0 || counter < count) { + counter++; + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Periodic notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + // Wait for the specified interval + await sleep(interval); + } + return { + content: [ + { + type: 'text', + text: `Started sending periodic notifications every ${interval}ms` + } + ] + }; + }); + // Create a simple resource at a fixed URI + server.resource('greeting-resource', 'https://example.com/greetings/default', { mimeType: 'text/plain' }, async () => { + return { + contents: [ + { + uri: 'https://example.com/greetings/default', + text: 'Hello, world!' + } + ] + }; + }); + return server; +}; +const app = (0, express_1.default)(); +app.use(express_1.default.json()); +// Configure CORS to expose Mcp-Session-Id header for browser-based clients +app.use((0, cors_1.default)({ + origin: '*', // Allow all origins - adjust as needed for production + exposedHeaders: ['Mcp-Session-Id'] +})); +app.post('/mcp', async (req, res) => { + const server = getServer(); + try { + const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: undefined + }); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + res.on('close', () => { + console.log('Request closed'); + transport.close(); + server.close(); + }); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +app.get('/mcp', async (req, res) => { + console.log('Received GET MCP request'); + res.writeHead(405).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Method not allowed.' + }, + id: null + })); +}); +app.delete('/mcp', async (req, res) => { + console.log('Received DELETE MCP request'); + res.writeHead(405).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Method not allowed.' + }, + id: null + })); +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Stateless Streamable HTTP Server listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + process.exit(0); +}); +//# sourceMappingURL=simpleStatelessStreamableHttp.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStatelessStreamableHttp.js.map b/dist/cjs/examples/server/simpleStatelessStreamableHttp.js.map new file mode 100644 index 0000000000..abc90f024e --- /dev/null +++ b/dist/cjs/examples/server/simpleStatelessStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStatelessStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleStatelessStreamableHttp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sDAAqD;AACrD,gDAAgD;AAChD,sEAA+E;AAC/E,0CAA4B;AAE5B,gDAAwB;AAExB,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,mDAAmD;IACnD,MAAM,MAAM,GAAG,IAAI,kBAAS,CACxB;QACI,IAAI,EAAE,kCAAkC;QACxC,OAAO,EAAE,OAAO;KACnB,EACD,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,CACpC,CAAC;IAEF,2BAA2B;I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G,CAAC,CAAC,GAAG,CAClB,IAAI,CAAC,SAAS,CAAC;QACX,OAAO,EAAE,KAAK;QACd,KAAK,EAAE;YACH,IAAI,EAAE,CAAC,KAAK;YACZ,OAAO,EAAE,qBAAqB;SACjC;QACD,EAAE,EAAE,IAAI;KACX,CAAC,CACL,CAAC;AACN,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0DAA0D,IAAI,EAAE,CAAC,CAAC;AAClF,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStreamableHttp.d.ts b/dist/cjs/examples/server/simpleStreamableHttp.d.ts new file mode 100644 index 0000000000..a20be42ca4 --- /dev/null +++ b/dist/cjs/examples/server/simpleStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStreamableHttp.d.ts.map b/dist/cjs/examples/server/simpleStreamableHttp.d.ts.map new file mode 100644 index 0000000000..e3cf042241 --- /dev/null +++ b/dist/cjs/examples/server/simpleStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStreamableHttp.js b/dist/cjs/examples/server/simpleStreamableHttp.js new file mode 100644 index 0000000000..86d46ea456 --- /dev/null +++ b/dist/cjs/examples/server/simpleStreamableHttp.js @@ -0,0 +1,611 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const express_1 = __importDefault(require("express")); +const node_crypto_1 = require("node:crypto"); +const z = __importStar(require("zod/v4")); +const mcp_js_1 = require("../../server/mcp.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const router_js_1 = require("../../server/auth/router.js"); +const bearerAuth_js_1 = require("../../server/auth/middleware/bearerAuth.js"); +const types_js_1 = require("../../types.js"); +const inMemoryEventStore_js_1 = require("../shared/inMemoryEventStore.js"); +const demoInMemoryOAuthProvider_js_1 = require("./demoInMemoryOAuthProvider.js"); +const auth_utils_js_1 = require("../../shared/auth-utils.js"); +const cors_1 = __importDefault(require("cors")); +// Check for OAuth flag +const useOAuth = process.argv.includes('--oauth'); +const strictOAuth = process.argv.includes('--oauth-strict'); +// Create an MCP server with implementation details +const getServer = () => { + const server = new mcp_js_1.McpServer({ + name: 'simple-streamable-http-server', + version: '1.0.0', + icons: [{ src: './mcp.svg', sizes: ['512x512'], mimeType: 'image/svg+xml' }], + websiteUrl: 'https://github.com/modelcontextprotocol/typescript-sdk' + }, { capabilities: { logging: {} } }); + // Register a simple tool that returns a greeting + server.registerTool('greet', { + title: 'Greeting Tool', // Display name for UI + description: 'A simple greeting tool', + inputSchema: { + name: z.string().describe('Name to greet') + } + }, async ({ name }) => { + return { + content: [ + { + type: 'text', + text: `Hello, ${name}!` + } + ] + }; + }); + // Register a tool that sends multiple greetings with notifications (with annotations) + server.tool('multi-greet', 'A tool that sends different greetings with delays between them', { + name: z.string().describe('Name to greet') + }, { + title: 'Multiple Greeting Tool', + readOnlyHint: true, + openWorldHint: false + }, async ({ name }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + await server.sendLoggingMessage({ + level: 'debug', + data: `Starting multi-greet for ${name}` + }, extra.sessionId); + await sleep(1000); // Wait 1 second before first greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending first greeting to ${name}` + }, extra.sessionId); + await sleep(1000); // Wait another second before second greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending second greeting to ${name}` + }, extra.sessionId); + return { + content: [ + { + type: 'text', + text: `Good morning, ${name}!` + } + ] + }; + }); + // Register a tool that demonstrates form elicitation (user input collection with a schema) + // This creates a closure that captures the server instance + server.tool('collect-user-info', 'A tool that collects user information through form elicitation', { + infoType: z.enum(['contact', 'preferences', 'feedback']).describe('Type of information to collect') + }, async ({ infoType }) => { + let message; + let requestedSchema; + switch (infoType) { + case 'contact': + message = 'Please provide your contact information'; + requestedSchema = { + type: 'object', + properties: { + name: { + type: 'string', + title: 'Full Name', + description: 'Your full name' + }, + email: { + type: 'string', + title: 'Email Address', + description: 'Your email address', + format: 'email' + }, + phone: { + type: 'string', + title: 'Phone Number', + description: 'Your phone number (optional)' + } + }, + required: ['name', 'email'] + }; + break; + case 'preferences': + message = 'Please set your preferences'; + requestedSchema = { + type: 'object', + properties: { + theme: { + type: 'string', + title: 'Theme', + description: 'Choose your preferred theme', + enum: ['light', 'dark', 'auto'], + enumNames: ['Light', 'Dark', 'Auto'] + }, + notifications: { + type: 'boolean', + title: 'Enable Notifications', + description: 'Would you like to receive notifications?', + default: true + }, + frequency: { + type: 'string', + title: 'Notification Frequency', + description: 'How often would you like notifications?', + enum: ['daily', 'weekly', 'monthly'], + enumNames: ['Daily', 'Weekly', 'Monthly'] + } + }, + required: ['theme'] + }; + break; + case 'feedback': + message = 'Please provide your feedback'; + requestedSchema = { + type: 'object', + properties: { + rating: { + type: 'integer', + title: 'Rating', + description: 'Rate your experience (1-5)', + minimum: 1, + maximum: 5 + }, + comments: { + type: 'string', + title: 'Comments', + description: 'Additional comments (optional)', + maxLength: 500 + }, + recommend: { + type: 'boolean', + title: 'Would you recommend this?', + description: 'Would you recommend this to others?' + } + }, + required: ['rating', 'recommend'] + }; + break; + default: + throw new Error(`Unknown info type: ${infoType}`); + } + try { + // Use the underlying server instance to elicit input from the client + const result = await server.server.elicitInput({ + mode: 'form', + message, + requestedSchema + }); + if (result.action === 'accept') { + return { + content: [ + { + type: 'text', + text: `Thank you! Collected ${infoType} information: ${JSON.stringify(result.content, null, 2)}` + } + ] + }; + } + else if (result.action === 'decline') { + return { + content: [ + { + type: 'text', + text: `No information was collected. User declined ${infoType} information request.` + } + ] + }; + } + else { + return { + content: [ + { + type: 'text', + text: `Information collection was cancelled by the user.` + } + ] + }; + } + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Error collecting ${infoType} information: ${error}` + } + ] + }; + } + }); + // Register a simple prompt with title + server.registerPrompt('greeting-template', { + title: 'Greeting Template', // Display name for UI + description: 'A simple greeting prompt template', + argsSchema: { + name: z.string().describe('Name to include in greeting') + } + }, async ({ name }) => { + return { + messages: [ + { + role: 'user', + content: { + type: 'text', + text: `Please greet ${name} in a friendly manner.` + } + } + ] + }; + }); + // Register a tool specifically for testing resumability + server.tool('start-notification-stream', 'Starts sending periodic notifications for testing resumability', { + interval: z.number().describe('Interval in milliseconds between notifications').default(100), + count: z.number().describe('Number of notifications to send (0 for 100)').default(50) + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + while (count === 0 || counter < count) { + counter++; + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Periodic notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + // Wait for the specified interval + await sleep(interval); + } + return { + content: [ + { + type: 'text', + text: `Started sending periodic notifications every ${interval}ms` + } + ] + }; + }); + // Create a simple resource at a fixed URI + server.registerResource('greeting-resource', 'https://example.com/greetings/default', { + title: 'Default Greeting', // Display name for UI + description: 'A simple greeting resource', + mimeType: 'text/plain' + }, async () => { + return { + contents: [ + { + uri: 'https://example.com/greetings/default', + text: 'Hello, world!' + } + ] + }; + }); + // Create additional resources for ResourceLink demonstration + server.registerResource('example-file-1', 'file:///example/file1.txt', { + title: 'Example File 1', + description: 'First example file for ResourceLink demonstration', + mimeType: 'text/plain' + }, async () => { + return { + contents: [ + { + uri: 'file:///example/file1.txt', + text: 'This is the content of file 1' + } + ] + }; + }); + server.registerResource('example-file-2', 'file:///example/file2.txt', { + title: 'Example File 2', + description: 'Second example file for ResourceLink demonstration', + mimeType: 'text/plain' + }, async () => { + return { + contents: [ + { + uri: 'file:///example/file2.txt', + text: 'This is the content of file 2' + } + ] + }; + }); + // Register a tool that returns ResourceLinks + server.registerTool('list-files', { + title: 'List Files with ResourceLinks', + description: 'Returns a list of files as ResourceLinks without embedding their content', + inputSchema: { + includeDescriptions: z.boolean().optional().describe('Whether to include descriptions in the resource links') + } + }, async ({ includeDescriptions = true }) => { + const resourceLinks = [ + { + type: 'resource_link', + uri: 'https://example.com/greetings/default', + name: 'Default Greeting', + mimeType: 'text/plain', + ...(includeDescriptions && { description: 'A simple greeting resource' }) + }, + { + type: 'resource_link', + uri: 'file:///example/file1.txt', + name: 'Example File 1', + mimeType: 'text/plain', + ...(includeDescriptions && { description: 'First example file for ResourceLink demonstration' }) + }, + { + type: 'resource_link', + uri: 'file:///example/file2.txt', + name: 'Example File 2', + mimeType: 'text/plain', + ...(includeDescriptions && { description: 'Second example file for ResourceLink demonstration' }) + } + ]; + return { + content: [ + { + type: 'text', + text: 'Here are the available files as resource links:' + }, + ...resourceLinks, + { + type: 'text', + text: '\nYou can read any of these resources using their URI.' + } + ] + }; + }); + return server; +}; +const MCP_PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; +const AUTH_PORT = process.env.MCP_AUTH_PORT ? parseInt(process.env.MCP_AUTH_PORT, 10) : 3001; +const app = (0, express_1.default)(); +app.use(express_1.default.json()); +// Allow CORS all domains, expose the Mcp-Session-Id header +app.use((0, cors_1.default)({ + origin: '*', // Allow all origins + exposedHeaders: ['Mcp-Session-Id'] +})); +// Set up OAuth if enabled +let authMiddleware = null; +if (useOAuth) { + // Create auth middleware for MCP endpoints + const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`); + const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); + const oauthMetadata = (0, demoInMemoryOAuthProvider_js_1.setupAuthServer)({ authServerUrl, mcpServerUrl, strictResource: strictOAuth }); + const tokenVerifier = { + verifyAccessToken: async (token) => { + const endpoint = oauthMetadata.introspection_endpoint; + if (!endpoint) { + throw new Error('No token verification endpoint available in metadata'); + } + const response = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: new URLSearchParams({ + token: token + }).toString() + }); + if (!response.ok) { + throw new Error(`Invalid or expired token: ${await response.text()}`); + } + const data = await response.json(); + if (strictOAuth) { + if (!data.aud) { + throw new Error(`Resource Indicator (RFC8707) missing`); + } + if (!(0, auth_utils_js_1.checkResourceAllowed)({ requestedResource: data.aud, configuredResource: mcpServerUrl })) { + throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); + } + } + // Convert the response to AuthInfo format + return { + token, + clientId: data.client_id, + scopes: data.scope ? data.scope.split(' ') : [], + expiresAt: data.exp + }; + } + }; + // Add metadata routes to the main MCP server + app.use((0, router_js_1.mcpAuthMetadataRouter)({ + oauthMetadata, + resourceServerUrl: mcpServerUrl, + scopesSupported: ['mcp:tools'], + resourceName: 'MCP Demo Server' + })); + authMiddleware = (0, bearerAuth_js_1.requireBearerAuth)({ + verifier: tokenVerifier, + requiredScopes: [], + resourceMetadataUrl: (0, router_js_1.getOAuthProtectedResourceMetadataUrl)(mcpServerUrl) + }); +} +// Map to store transports by session ID +const transports = {}; +// MCP POST endpoint with optional auth +const mcpPostHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (sessionId) { + console.log(`Received MCP request for session: ${sessionId}`); + } + else { + console.log('Request body:', req.body); + } + if (useOAuth && req.auth) { + console.log('Authenticated user:', req.auth); + } + try { + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) { + // New initialization request + const eventStore = new inMemoryEventStore_js_1.InMemoryEventStore(); + transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), + eventStore, // Enable resumability + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + } + }; + // Connect the transport to the MCP server BEFORE handling the request + // so responses can flow back through the same transport + const server = getServer(); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport - no need to reconnect + // The existing transport is already connected to the server + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}; +// Set up routes with conditional auth middleware +if (useOAuth && authMiddleware) { + app.post('/mcp', authMiddleware, mcpPostHandler); +} +else { + app.post('/mcp', mcpPostHandler); +} +// Handle GET requests for SSE streams (using built-in support from StreamableHTTP) +const mcpGetHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + if (useOAuth && req.auth) { + console.log('Authenticated SSE connection from user:', req.auth); + } + // Check for Last-Event-ID header for resumability + const lastEventId = req.headers['last-event-id']; + if (lastEventId) { + console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`); + } + else { + console.log(`Establishing new SSE stream for session ${sessionId}`); + } + const transport = transports[sessionId]; + await transport.handleRequest(req, res); +}; +// Set up GET route with conditional auth middleware +if (useOAuth && authMiddleware) { + app.get('/mcp', authMiddleware, mcpGetHandler); +} +else { + app.get('/mcp', mcpGetHandler); +} +// Handle DELETE requests for session termination (according to MCP spec) +const mcpDeleteHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Received session termination request for session ${sessionId}`); + try { + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + } + catch (error) { + console.error('Error handling session termination:', error); + if (!res.headersSent) { + res.status(500).send('Error processing session termination'); + } + } +}; +// Set up DELETE route with conditional auth middleware +if (useOAuth && authMiddleware) { + app.delete('/mcp', authMiddleware, mcpDeleteHandler); +} +else { + app.delete('/mcp', mcpDeleteHandler); +} +app.listen(MCP_PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Streamable HTTP Server listening on port ${MCP_PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=simpleStreamableHttp.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStreamableHttp.js.map b/dist/cjs/examples/server/simpleStreamableHttp.js.map new file mode 100644 index 0000000000..c39bde1267 --- /dev/null +++ b/dist/cjs/examples/server/simpleStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleStreamableHttp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sDAAqD;AACrD,6CAAyC;AACzC,0CAA4B;AAC5B,gDAAgD;AAChD,sEAA+E;AAC/E,2DAA0G;AAC1G,8EAA+E;AAC/E,6CAOwB;AACxB,2EAAqE;AACrE,iFAAiE;AAEjE,8DAAkE;AAElE,gDAAwB;AAExB,uBAAuB;AACvB,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;AAClD,MAAM,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC;AAE5D,mDAAmD;AACnD,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,GAAG,IAAI,kBAAS,CACxB;QACI,IAAI,EAAE,+BAA+B;QACrC,OAAO,EAAE,OAAO;QAChB,KAAK,EAAE,CAAC,EAAE,GAAG,EAAE,WAAW,EAAE,KAA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AAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts b/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts new file mode 100644 index 0000000000..c536d0c80e --- /dev/null +++ b/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=sseAndStreamableHttpCompatibleServer.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map b/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map new file mode 100644 index 0000000000..fb982c84a6 --- /dev/null +++ b/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sseAndStreamableHttpCompatibleServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/sseAndStreamableHttpCompatibleServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js b/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js new file mode 100644 index 0000000000..def1932ede --- /dev/null +++ b/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js @@ -0,0 +1,263 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const express_1 = __importDefault(require("express")); +const node_crypto_1 = require("node:crypto"); +const mcp_js_1 = require("../../server/mcp.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const sse_js_1 = require("../../server/sse.js"); +const z = __importStar(require("zod/v4")); +const types_js_1 = require("../../types.js"); +const inMemoryEventStore_js_1 = require("../shared/inMemoryEventStore.js"); +const cors_1 = __importDefault(require("cors")); +/** + * This example server demonstrates backwards compatibility with both: + * 1. The deprecated HTTP+SSE transport (protocol version 2024-11-05) + * 2. The Streamable HTTP transport (protocol version 2025-03-26) + * + * It maintains a single MCP server instance but exposes two transport options: + * - /mcp: The new Streamable HTTP endpoint (supports GET/POST/DELETE) + * - /sse: The deprecated SSE endpoint for older clients (GET to establish stream) + * - /messages: The deprecated POST endpoint for older clients (POST to send messages) + */ +const getServer = () => { + const server = new mcp_js_1.McpServer({ + name: 'backwards-compatible-server', + version: '1.0.0' + }, { capabilities: { logging: {} } }); + // Register a simple tool that sends notifications over time + server.tool('start-notification-stream', 'Starts sending periodic notifications for testing resumability', { + interval: z.number().describe('Interval in milliseconds between notifications').default(100), + count: z.number().describe('Number of notifications to send (0 for 100)').default(50) + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + while (count === 0 || counter < count) { + counter++; + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Periodic notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + // Wait for the specified interval + await sleep(interval); + } + return { + content: [ + { + type: 'text', + text: `Started sending periodic notifications every ${interval}ms` + } + ] + }; + }); + return server; +}; +// Create Express application +const app = (0, express_1.default)(); +app.use(express_1.default.json()); +// Configure CORS to expose Mcp-Session-Id header for browser-based clients +app.use((0, cors_1.default)({ + origin: '*', // Allow all origins - adjust as needed for production + exposedHeaders: ['Mcp-Session-Id'] +})); +// Store transports by session ID +const transports = {}; +//============================================================================= +// STREAMABLE HTTP TRANSPORT (PROTOCOL VERSION 2025-03-26) +//============================================================================= +// Handle all MCP Streamable HTTP requests (GET, POST, DELETE) on a single endpoint +app.all('/mcp', async (req, res) => { + console.log(`Received ${req.method} request to /mcp`); + try { + // Check for existing session ID + const sessionId = req.headers['mcp-session-id']; + let transport; + if (sessionId && transports[sessionId]) { + // Check if the transport is of the correct type + const existingTransport = transports[sessionId]; + if (existingTransport instanceof streamableHttp_js_1.StreamableHTTPServerTransport) { + // Reuse existing transport + transport = existingTransport; + } + else { + // Transport exists but is not a StreamableHTTPServerTransport (could be SSEServerTransport) + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Session exists but uses a different transport protocol' + }, + id: null + }); + return; + } + } + else if (!sessionId && req.method === 'POST' && (0, types_js_1.isInitializeRequest)(req.body)) { + const eventStore = new inMemoryEventStore_js_1.InMemoryEventStore(); + transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), + eventStore, // Enable resumability + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + console.log(`StreamableHTTP session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + } + }; + // Connect the transport to the MCP server + const server = getServer(); + await server.connect(transport); + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with the transport + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +//============================================================================= +// DEPRECATED HTTP+SSE TRANSPORT (PROTOCOL VERSION 2024-11-05) +//============================================================================= +app.get('/sse', async (req, res) => { + console.log('Received GET request to /sse (deprecated SSE transport)'); + const transport = new sse_js_1.SSEServerTransport('/messages', res); + transports[transport.sessionId] = transport; + res.on('close', () => { + delete transports[transport.sessionId]; + }); + const server = getServer(); + await server.connect(transport); +}); +app.post('/messages', async (req, res) => { + const sessionId = req.query.sessionId; + let transport; + const existingTransport = transports[sessionId]; + if (existingTransport instanceof sse_js_1.SSEServerTransport) { + // Reuse existing transport + transport = existingTransport; + } + else { + // Transport exists but is not a SSEServerTransport (could be StreamableHTTPServerTransport) + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Session exists but uses a different transport protocol' + }, + id: null + }); + return; + } + if (transport) { + await transport.handlePostMessage(req, res, req.body); + } + else { + res.status(400).send('No transport found for sessionId'); + } +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Backwards compatible MCP server listening on port ${PORT}`); + console.log(` +============================================== +SUPPORTED TRANSPORT OPTIONS: + +1. Streamable Http(Protocol version: 2025-03-26) + Endpoint: /mcp + Methods: GET, POST, DELETE + Usage: + - Initialize with POST to /mcp + - Establish SSE stream with GET to /mcp + - Send requests with POST to /mcp + - Terminate session with DELETE to /mcp + +2. Http + SSE (Protocol version: 2024-11-05) + Endpoints: /sse (GET) and /messages (POST) + Usage: + - Establish SSE stream with GET to /sse + - Send requests with POST to /messages?sessionId= +============================================== +`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=sseAndStreamableHttpCompatibleServer.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js.map b/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js.map new file mode 100644 index 0000000000..148cf28b1c --- /dev/null +++ b/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sseAndStreamableHttpCompatibleServer.js","sourceRoot":"","sources":["../../../../src/examples/server/sseAndStreamableHttpCompatibleServer.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sDAAqD;AACrD,6CAAyC;AACzC,gDAAgD;AAChD,sEAA+E;AAC/E,gDAAyD;AACzD,0CAA4B;AAC5B,6CAAqE;AACrE,2EAAqE;AACrE,gDAAwB;AAExB;;;;;;;;;GASG;AAEH,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,GAAG,IAAI,kBAAS,CACxB;QACI,IAAI,EAAE,6BAA6B;QACnC,OAAO,EAAE,OAAO;KACnB,EACD,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,CACpC,CAAC;IAEF,4DAA4D;IAC5D,MAAM,CAAC,IAAI,CACP,2BAA2B,EAC3B,gEAAgE,EAChE;QACI,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,gDAAgD,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC;QAC5F,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,6CAA6C,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC;KACxF,EACD,KAA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CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts b/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts new file mode 100644 index 0000000000..4df17831b7 --- /dev/null +++ b/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=standaloneSseWithGetStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map b/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map new file mode 100644 index 0000000000..df60dc51b0 --- /dev/null +++ b/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"standaloneSseWithGetStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/standaloneSseWithGetStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js b/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js new file mode 100644 index 0000000000..ae1193d31c --- /dev/null +++ b/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js @@ -0,0 +1,116 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const express_1 = __importDefault(require("express")); +const node_crypto_1 = require("node:crypto"); +const mcp_js_1 = require("../../server/mcp.js"); +const streamableHttp_js_1 = require("../../server/streamableHttp.js"); +const types_js_1 = require("../../types.js"); +// Create an MCP server with implementation details +const server = new mcp_js_1.McpServer({ + name: 'resource-list-changed-notification-server', + version: '1.0.0' +}); +// Store transports by session ID to send notifications +const transports = {}; +const addResource = (name, content) => { + const uri = `https://mcp-example.com/dynamic/${encodeURIComponent(name)}`; + server.resource(name, uri, { mimeType: 'text/plain', description: `Dynamic resource: ${name}` }, async () => { + return { + contents: [{ uri, text: content }] + }; + }); +}; +addResource('example-resource', 'Initial content for example-resource'); +const resourceChangeInterval = setInterval(() => { + const name = (0, node_crypto_1.randomUUID)(); + addResource(name, `Content for ${name}`); +}, 5000); // Change resources every 5 seconds for testing +const app = (0, express_1.default)(); +app.use(express_1.default.json()); +app.post('/mcp', async (req, res) => { + console.log('Received MCP request:', req.body); + try { + // Check for existing session ID + const sessionId = req.headers['mcp-session-id']; + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) { + // New initialization request + transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ + sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Connect the transport to the MCP server + await server.connect(transport); + // Handle the request - the onsessioninitialized callback will store the transport + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +// Handle GET requests for SSE streams (now using built-in support from StreamableHTTP) +app.get('/mcp', async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Establishing SSE stream for session ${sessionId}`); + const transport = transports[sessionId]; + await transport.handleRequest(req, res); +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Server listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + clearInterval(resourceChangeInterval); + await server.close(); + process.exit(0); +}); +//# sourceMappingURL=standaloneSseWithGetStreamableHttp.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js.map b/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js.map new file mode 100644 index 0000000000..c48532b79e --- /dev/null +++ b/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"standaloneSseWithGetStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/standaloneSseWithGetStreamableHttp.ts"],"names":[],"mappings":";;;;;AAAA,sDAAqD;AACrD,6CAAyC;AACzC,gDAAgD;AAChD,sEAA+E;AAC/E,6CAAyE;AAEzE,mDAAmD;AACnD,MAAM,MAAM,GAAG,IAAI,kBAAS,CAAC;IACzB,IAAI,EAAE,2CAA2C;IACjD,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,uDAAuD;AACvD,MAAM,UAAU,GAA2D,EAAE,CAAC;AAE9E,MAAM,WAAW,GAAG,CAAC,IAAY,EAAE,OAAe,EAAE,EAAE;IAClD,MAAM,GAAG,GAAG,mCAAmC,kBAAkB,CAAC,IAAI,CAAC,EAAE,CAAC;IAC1E,MAAM,CAAC,QAAQ,CACX,IAAI,EACJ,GAAG,EACH,EAAE,QAAQ,EAAE,YAAY,EAAE,WAAW,EAAE,qBAAqB,IAAI,EAAE,EAAE,EACpE,KAAK,IAAiC,EAAE;QACpC,OAAO;YACH,QAAQ,EAAE,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;SACrC,CAAC;IACN,CAA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AAC,EAAE,CAAC;QACvC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,+BAA+B,CAAC,CAAC;QACtD,OAAO;IACX,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,uCAAuC,SAAS,EAAE,CAAC,CAAC;IAChE,MAAM,SAAS,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC;IACxC,MAAM,SAAS,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,4BAA4B,IAAI,EAAE,CAAC,CAAC;AACpD,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,aAAa,CAAC,sBAAsB,CAAC,CAAC;IACtC,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;IACrB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/toolWithSampleServer.d.ts b/dist/cjs/examples/server/toolWithSampleServer.d.ts new file mode 100644 index 0000000000..acc24b6a53 --- /dev/null +++ b/dist/cjs/examples/server/toolWithSampleServer.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=toolWithSampleServer.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/toolWithSampleServer.d.ts.map b/dist/cjs/examples/server/toolWithSampleServer.d.ts.map new file mode 100644 index 0000000000..bd0cebcf19 --- /dev/null +++ b/dist/cjs/examples/server/toolWithSampleServer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"toolWithSampleServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/toolWithSampleServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/toolWithSampleServer.js b/dist/cjs/examples/server/toolWithSampleServer.js new file mode 100644 index 0000000000..4a35eb7987 --- /dev/null +++ b/dist/cjs/examples/server/toolWithSampleServer.js @@ -0,0 +1,71 @@ +"use strict"; +// Run with: npx tsx src/examples/server/toolWithSampleServer.ts +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const mcp_js_1 = require("../../server/mcp.js"); +const stdio_js_1 = require("../../server/stdio.js"); +const z = __importStar(require("zod/v4")); +const mcpServer = new mcp_js_1.McpServer({ + name: 'tools-with-sample-server', + version: '1.0.0' +}); +// Tool that uses LLM sampling to summarize any text +mcpServer.registerTool('summarize', { + description: 'Summarize any text using an LLM', + inputSchema: { + text: z.string().describe('Text to summarize') + } +}, async ({ text }) => { + // Call the LLM through MCP sampling + const response = await mcpServer.server.createMessage({ + messages: [ + { + role: 'user', + content: { + type: 'text', + text: `Please summarize the following text concisely:\n\n${text}` + } + } + ], + maxTokens: 500 + }); + const contents = Array.isArray(response.content) ? response.content : [response.content]; + return { + content: contents.map(content => ({ + type: 'text', + text: content.type === 'text' ? content.text : 'Unable to generate summary' + })) + }; +}); +async function main() { + const transport = new stdio_js_1.StdioServerTransport(); + await mcpServer.connect(transport); + console.log('MCP server is running...'); +} +main().catch(error => { + console.error('Server error:', error); + process.exit(1); +}); +//# sourceMappingURL=toolWithSampleServer.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/toolWithSampleServer.js.map b/dist/cjs/examples/server/toolWithSampleServer.js.map new file mode 100644 index 0000000000..5f9d219921 --- /dev/null +++ b/dist/cjs/examples/server/toolWithSampleServer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"toolWithSampleServer.js","sourceRoot":"","sources":["../../../../src/examples/server/toolWithSampleServer.ts"],"names":[],"mappings":";AAAA,gEAAgE;;;;;;;;;;;;;;;;;;;;;;;;;AAEhE,gDAAgD;AAChD,oDAA6D;AAC7D,0CAA4B;AAE5B,MAAM,SAAS,GAAG,IAAI,kBAAS,CAAC;IAC5B,IAAI,EAAE,0BAA0B;IAChC,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,oDAAoD;AACpD,SAAS,CAAC,YAAY,CAClB,WAAW,EACX;IACI,WAAW,EAAE,iCAAiC;IAC9C,WAAW,EAAE;QACT,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,mBAAmB,CAAC;KACjD;CACJ,EACD,KAAK,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE;IACf,oCAAoC;IACpC,MAAM,QAAQ,GAAG,MAAM,SAAS,CAAC,MAAM,CAAC,aAAa,CAAC;QAClD,QAAQ,EAAE;YACN;gBACI,IAAI,EAAE,MAAM;gBACZ,OAAO,EAAE;oBACL,IAAI,EAAE,MAAM;oBACZ,IAAI,EAAE,qDAAqD,IAAI,EAAE;iBACpE;aACJ;SACJ;QACD,SAAS,EAAE,GAAG;KACjB,CAAC,CAAC;IAEH,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACzF,OAAO;QACH,OAAO,EAAE,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;YAC9B,IAAI,EAAE,MAAM;YACZ,IAAI,EAAE,OAAO,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,4BAA4B;SAC9E,CAAC,CAAC;KACN,CAAC;AACN,CAAC,CACJ,CAAC;AAEF,KAAK,UAAU,IAAI;IACf,MAAM,SAAS,GAAG,IAAI,+BAAoB,EAAE,CAAC;IAC7C,MAAM,SAAS,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACnC,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;AAC5C,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/shared/inMemoryEventStore.d.ts b/dist/cjs/examples/shared/inMemoryEventStore.d.ts new file mode 100644 index 0000000000..26ff38cf93 --- /dev/null +++ b/dist/cjs/examples/shared/inMemoryEventStore.d.ts @@ -0,0 +1,31 @@ +import { JSONRPCMessage } from '../../types.js'; +import { EventStore } from '../../server/streamableHttp.js'; +/** + * Simple in-memory implementation of the EventStore interface for resumability + * This is primarily intended for examples and testing, not for production use + * where a persistent storage solution would be more appropriate. + */ +export declare class InMemoryEventStore implements EventStore { + private events; + /** + * Generates a unique event ID for a given stream ID + */ + private generateEventId; + /** + * Extracts the stream ID from an event ID + */ + private getStreamIdFromEventId; + /** + * Stores an event with a generated event ID + * Implements EventStore.storeEvent + */ + storeEvent(streamId: string, message: JSONRPCMessage): Promise; + /** + * Replays events that occurred after a specific event ID + * Implements EventStore.replayEventsAfter + */ + replayEventsAfter(lastEventId: string, { send }: { + send: (eventId: string, message: JSONRPCMessage) => Promise; + }): Promise; +} +//# sourceMappingURL=inMemoryEventStore.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/shared/inMemoryEventStore.d.ts.map b/dist/cjs/examples/shared/inMemoryEventStore.d.ts.map new file mode 100644 index 0000000000..a67ee6cd17 --- /dev/null +++ b/dist/cjs/examples/shared/inMemoryEventStore.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"inMemoryEventStore.d.ts","sourceRoot":"","sources":["../../../../src/examples/shared/inMemoryEventStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAE5D;;;;GAIG;AACH,qBAAa,kBAAmB,YAAW,UAAU;IACjD,OAAO,CAAC,MAAM,CAAyE;IAEvF;;OAEG;IACH,OAAO,CAAC,eAAe;IAIvB;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAK9B;;;OAGG;IACG,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;IAM5E;;;OAGG;IACG,iBAAiB,CACnB,WAAW,EAAE,MAAM,EACnB,EAAE,IAAI,EAAE,EAAE;QAAE,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;KAAE,GAChF,OAAO,CAAC,MAAM,CAAC;CAkCrB"} \ No newline at end of file diff --git a/dist/cjs/examples/shared/inMemoryEventStore.js b/dist/cjs/examples/shared/inMemoryEventStore.js new file mode 100644 index 0000000000..d33ffdb5c1 --- /dev/null +++ b/dist/cjs/examples/shared/inMemoryEventStore.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InMemoryEventStore = void 0; +/** + * Simple in-memory implementation of the EventStore interface for resumability + * This is primarily intended for examples and testing, not for production use + * where a persistent storage solution would be more appropriate. + */ +class InMemoryEventStore { + constructor() { + this.events = new Map(); + } + /** + * Generates a unique event ID for a given stream ID + */ + generateEventId(streamId) { + return `${streamId}_${Date.now()}_${Math.random().toString(36).substring(2, 10)}`; + } + /** + * Extracts the stream ID from an event ID + */ + getStreamIdFromEventId(eventId) { + const parts = eventId.split('_'); + return parts.length > 0 ? parts[0] : ''; + } + /** + * Stores an event with a generated event ID + * Implements EventStore.storeEvent + */ + async storeEvent(streamId, message) { + const eventId = this.generateEventId(streamId); + this.events.set(eventId, { streamId, message }); + return eventId; + } + /** + * Replays events that occurred after a specific event ID + * Implements EventStore.replayEventsAfter + */ + async replayEventsAfter(lastEventId, { send }) { + if (!lastEventId || !this.events.has(lastEventId)) { + return ''; + } + // Extract the stream ID from the event ID + const streamId = this.getStreamIdFromEventId(lastEventId); + if (!streamId) { + return ''; + } + let foundLastEvent = false; + // Sort events by eventId for chronological ordering + const sortedEvents = [...this.events.entries()].sort((a, b) => a[0].localeCompare(b[0])); + for (const [eventId, { streamId: eventStreamId, message }] of sortedEvents) { + // Only include events from the same stream + if (eventStreamId !== streamId) { + continue; + } + // Start sending events after we find the lastEventId + if (eventId === lastEventId) { + foundLastEvent = true; + continue; + } + if (foundLastEvent) { + await send(eventId, message); + } + } + return streamId; + } +} +exports.InMemoryEventStore = InMemoryEventStore; +//# sourceMappingURL=inMemoryEventStore.js.map \ No newline at end of file diff --git a/dist/cjs/examples/shared/inMemoryEventStore.js.map b/dist/cjs/examples/shared/inMemoryEventStore.js.map new file mode 100644 index 0000000000..d696450639 --- /dev/null +++ b/dist/cjs/examples/shared/inMemoryEventStore.js.map @@ -0,0 +1 @@ +{"version":3,"file":"inMemoryEventStore.js","sourceRoot":"","sources":["../../../../src/examples/shared/inMemoryEventStore.ts"],"names":[],"mappings":";;;AAGA;;;;GAIG;AACH,MAAa,kBAAkB;IAA/B;QACY,WAAM,GAA+D,IAAI,GAAG,EAAE,CAAC;IAoE3F,CAAC;IAlEG;;OAEG;IACK,eAAe,CAAC,QAAgB;QACpC,OAAO,GAAG,QAAQ,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC;IACtF,CAAC;IAED;;OAEG;IACK,sBAAsB,CAAC,OAAe;QAC1C,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACjC,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC5C,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,UAAU,CAAC,QAAgB,EAAE,OAAuB;QACtD,MAAM,OAAO,GAAG,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,CAAC;QAC/C,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC;QAChD,OAAO,OAAO,CAAC;IACnB,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,iBAAiB,CACnB,WAAmB,EACnB,EAAE,IAAI,EAAyE;QAE/E,IAAI,CAAC,WAAW,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,WAAW,CAAC,EAAE,CAAC;YAChD,OAAO,EAAE,CAAC;QACd,CAAC;QAED,0CAA0C;QAC1C,MAAM,QAAQ,GAAG,IAAI,CAAC,sBAAsB,CAAC,WAAW,CAAC,CAAC;QAC1D,IAAI,CAAC,QAAQ,EAAE,CAAC;YACZ,OAAO,EAAE,CAAC;QACd,CAAC;QAED,IAAI,cAAc,GAAG,KAAK,CAAC;QAE3B,oDAAoD;QACpD,MAAM,YAAY,GAAG,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAEzF,KAAK,MAAM,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC,IAAI,YAAY,EAAE,CAAC;YACzE,2CAA2C;YAC3C,IAAI,aAAa,KAAK,QAAQ,EAAE,CAAC;gBAC7B,SAAS;YACb,CAAC;YAED,qDAAqD;YACrD,IAAI,OAAO,KAAK,WAAW,EAAE,CAAC;gBAC1B,cAAc,GAAG,IAAI,CAAC;gBACtB,SAAS;YACb,CAAC;YAED,IAAI,cAAc,EAAE,CAAC;gBACjB,MAAM,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACjC,CAAC;QACL,CAAC;QACD,OAAO,QAAQ,CAAC;IACpB,CAAC;CACJ;AArED,gDAqEC"} \ No newline at end of file diff --git a/dist/cjs/inMemory.d.ts b/dist/cjs/inMemory.d.ts new file mode 100644 index 0000000000..32a931a863 --- /dev/null +++ b/dist/cjs/inMemory.d.ts @@ -0,0 +1,31 @@ +import { Transport } from './shared/transport.js'; +import { JSONRPCMessage, RequestId } from './types.js'; +import { AuthInfo } from './server/auth/types.js'; +/** + * In-memory transport for creating clients and servers that talk to each other within the same process. + */ +export declare class InMemoryTransport implements Transport { + private _otherTransport?; + private _messageQueue; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage, extra?: { + authInfo?: AuthInfo; + }) => void; + sessionId?: string; + /** + * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a Client and one to a Server. + */ + static createLinkedPair(): [InMemoryTransport, InMemoryTransport]; + start(): Promise; + close(): Promise; + /** + * Sends a message with optional auth info. + * This is useful for testing authentication scenarios. + */ + send(message: JSONRPCMessage, options?: { + relatedRequestId?: RequestId; + authInfo?: AuthInfo; + }): Promise; +} +//# sourceMappingURL=inMemory.d.ts.map \ No newline at end of file diff --git a/dist/cjs/inMemory.d.ts.map b/dist/cjs/inMemory.d.ts.map new file mode 100644 index 0000000000..46bc74be17 --- /dev/null +++ b/dist/cjs/inMemory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"inMemory.d.ts","sourceRoot":"","sources":["../../src/inMemory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAOlD;;GAEG;AACH,qBAAa,iBAAkB,YAAW,SAAS;IAC/C,OAAO,CAAC,eAAe,CAAC,CAAoB;IAC5C,OAAO,CAAC,aAAa,CAAuB;IAE5C,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,KAAK,IAAI,CAAC;IAC/E,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,MAAM,CAAC,gBAAgB,IAAI,CAAC,iBAAiB,EAAE,iBAAiB,CAAC;IAQ3D,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAQtB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAO5B;;;OAGG;IACG,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,SAAS,CAAC;QAAC,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAWtH"} \ No newline at end of file diff --git a/dist/cjs/inMemory.js b/dist/cjs/inMemory.js new file mode 100644 index 0000000000..3070d83910 --- /dev/null +++ b/dist/cjs/inMemory.js @@ -0,0 +1,53 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InMemoryTransport = void 0; +/** + * In-memory transport for creating clients and servers that talk to each other within the same process. + */ +class InMemoryTransport { + constructor() { + this._messageQueue = []; + } + /** + * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a Client and one to a Server. + */ + static createLinkedPair() { + const clientTransport = new InMemoryTransport(); + const serverTransport = new InMemoryTransport(); + clientTransport._otherTransport = serverTransport; + serverTransport._otherTransport = clientTransport; + return [clientTransport, serverTransport]; + } + async start() { + var _a; + // Process any messages that were queued before start was called + while (this._messageQueue.length > 0) { + const queuedMessage = this._messageQueue.shift(); + (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, queuedMessage.message, queuedMessage.extra); + } + } + async close() { + var _a; + const other = this._otherTransport; + this._otherTransport = undefined; + await (other === null || other === void 0 ? void 0 : other.close()); + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + } + /** + * Sends a message with optional auth info. + * This is useful for testing authentication scenarios. + */ + async send(message, options) { + if (!this._otherTransport) { + throw new Error('Not connected'); + } + if (this._otherTransport.onmessage) { + this._otherTransport.onmessage(message, { authInfo: options === null || options === void 0 ? void 0 : options.authInfo }); + } + else { + this._otherTransport._messageQueue.push({ message, extra: { authInfo: options === null || options === void 0 ? void 0 : options.authInfo } }); + } + } +} +exports.InMemoryTransport = InMemoryTransport; +//# sourceMappingURL=inMemory.js.map \ No newline at end of file diff --git a/dist/cjs/inMemory.js.map b/dist/cjs/inMemory.js.map new file mode 100644 index 0000000000..869a51f615 --- /dev/null +++ b/dist/cjs/inMemory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"inMemory.js","sourceRoot":"","sources":["../../src/inMemory.ts"],"names":[],"mappings":";;;AASA;;GAEG;AACH,MAAa,iBAAiB;IAA9B;QAEY,kBAAa,GAAoB,EAAE,CAAC;IAgDhD,CAAC;IAzCG;;OAEG;IACH,MAAM,CAAC,gBAAgB;QACnB,MAAM,eAAe,GAAG,IAAI,iBAAiB,EAAE,CAAC;QAChD,MAAM,eAAe,GAAG,IAAI,iBAAiB,EAAE,CAAC;QAChD,eAAe,CAAC,eAAe,GAAG,eAAe,CAAC;QAClD,eAAe,CAAC,eAAe,GAAG,eAAe,CAAC;QAClD,OAAO,CAAC,eAAe,EAAE,eAAe,CAAC,CAAC;IAC9C,CAAC;IAED,KAAK,CAAC,KAAK;;QACP,gEAAgE;QAChE,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACnC,MAAM,aAAa,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,EAAG,CAAC;YAClD,MAAA,IAAI,CAAC,SAAS,qDAAG,aAAa,CAAC,OAAO,EAAE,aAAa,CAAC,KAAK,CAAC,CAAC;QACjE,CAAC;IACL,CAAC;IAED,KAAK,CAAC,KAAK;;QACP,MAAM,KAAK,GAAG,IAAI,CAAC,eAAe,CAAC;QACnC,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACjC,MAAM,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,KAAK,EAAE,CAAA,CAAC;QACrB,MAAA,IAAI,CAAC,OAAO,oDAAI,CAAC;IACrB,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,IAAI,CAAC,OAAuB,EAAE,OAA+D;QAC/F,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC;YACxB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;QACrC,CAAC;QAED,IAAI,IAAI,CAAC,eAAe,CAAC,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,EAAE,CAAC,CAAC;QAC7E,CAAC;aAAM,CAAC;YACJ,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;QACjG,CAAC;IACL,CAAC;CACJ;AAlDD,8CAkDC"} \ No newline at end of file diff --git a/dist/cjs/package.json b/dist/cjs/package.json new file mode 100644 index 0000000000..b731bd61b9 --- /dev/null +++ b/dist/cjs/package.json @@ -0,0 +1 @@ +{"type": "commonjs"} diff --git a/dist/cjs/server/auth/clients.d.ts b/dist/cjs/server/auth/clients.d.ts new file mode 100644 index 0000000000..be6899a198 --- /dev/null +++ b/dist/cjs/server/auth/clients.d.ts @@ -0,0 +1,19 @@ +import { OAuthClientInformationFull } from '../../shared/auth.js'; +/** + * Stores information about registered OAuth clients for this server. + */ +export interface OAuthRegisteredClientsStore { + /** + * Returns information about a registered client, based on its ID. + */ + getClient(clientId: string): OAuthClientInformationFull | undefined | Promise; + /** + * Registers a new client with the server. The client ID and secret will be automatically generated by the library. A modified version of the client information can be returned to reflect specific values enforced by the server. + * + * NOTE: Implementations should NOT delete expired client secrets in-place. Auth middleware provided by this library will automatically check the `client_secret_expires_at` field and reject requests with expired secrets. Any custom logic for authenticating clients should check the `client_secret_expires_at` field as well. + * + * If unimplemented, dynamic client registration is unsupported. + */ + registerClient?(client: Omit): OAuthClientInformationFull | Promise; +} +//# sourceMappingURL=clients.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/clients.d.ts.map b/dist/cjs/server/auth/clients.d.ts.map new file mode 100644 index 0000000000..ab3851db35 --- /dev/null +++ b/dist/cjs/server/auth/clients.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"clients.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/clients.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAElE;;GAEG;AACH,MAAM,WAAW,2BAA2B;IACxC;;OAEG;IACH,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,0BAA0B,GAAG,SAAS,GAAG,OAAO,CAAC,0BAA0B,GAAG,SAAS,CAAC,CAAC;IAEtH;;;;;;OAMG;IACH,cAAc,CAAC,CACX,MAAM,EAAE,IAAI,CAAC,0BAA0B,EAAE,WAAW,GAAG,qBAAqB,CAAC,GAC9E,0BAA0B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAAC;CACvE"} \ No newline at end of file diff --git a/dist/cjs/server/auth/clients.js b/dist/cjs/server/auth/clients.js new file mode 100644 index 0000000000..866b88b74b --- /dev/null +++ b/dist/cjs/server/auth/clients.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=clients.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/clients.js.map b/dist/cjs/server/auth/clients.js.map new file mode 100644 index 0000000000..0210104422 --- /dev/null +++ b/dist/cjs/server/auth/clients.js.map @@ -0,0 +1 @@ +{"version":3,"file":"clients.js","sourceRoot":"","sources":["../../../../src/server/auth/clients.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/server/auth/errors.d.ts b/dist/cjs/server/auth/errors.d.ts new file mode 100644 index 0000000000..b487760fc2 --- /dev/null +++ b/dist/cjs/server/auth/errors.d.ts @@ -0,0 +1,141 @@ +import { OAuthErrorResponse } from '../../shared/auth.js'; +/** + * Base class for all OAuth errors + */ +export declare class OAuthError extends Error { + readonly errorUri?: string | undefined; + static errorCode: string; + constructor(message: string, errorUri?: string | undefined); + /** + * Converts the error to a standard OAuth error response object + */ + toResponseObject(): OAuthErrorResponse; + get errorCode(): string; +} +/** + * Invalid request error - The request is missing a required parameter, + * includes an invalid parameter value, includes a parameter more than once, + * or is otherwise malformed. + */ +export declare class InvalidRequestError extends OAuthError { + static errorCode: string; +} +/** + * Invalid client error - Client authentication failed (e.g., unknown client, no client + * authentication included, or unsupported authentication method). + */ +export declare class InvalidClientError extends OAuthError { + static errorCode: string; +} +/** + * Invalid grant error - The provided authorization grant or refresh token is + * invalid, expired, revoked, does not match the redirection URI used in the + * authorization request, or was issued to another client. + */ +export declare class InvalidGrantError extends OAuthError { + static errorCode: string; +} +/** + * Unauthorized client error - The authenticated client is not authorized to use + * this authorization grant type. + */ +export declare class UnauthorizedClientError extends OAuthError { + static errorCode: string; +} +/** + * Unsupported grant type error - The authorization grant type is not supported + * by the authorization server. + */ +export declare class UnsupportedGrantTypeError extends OAuthError { + static errorCode: string; +} +/** + * Invalid scope error - The requested scope is invalid, unknown, malformed, or + * exceeds the scope granted by the resource owner. + */ +export declare class InvalidScopeError extends OAuthError { + static errorCode: string; +} +/** + * Access denied error - The resource owner or authorization server denied the request. + */ +export declare class AccessDeniedError extends OAuthError { + static errorCode: string; +} +/** + * Server error - The authorization server encountered an unexpected condition + * that prevented it from fulfilling the request. + */ +export declare class ServerError extends OAuthError { + static errorCode: string; +} +/** + * Temporarily unavailable error - The authorization server is currently unable to + * handle the request due to a temporary overloading or maintenance of the server. + */ +export declare class TemporarilyUnavailableError extends OAuthError { + static errorCode: string; +} +/** + * Unsupported response type error - The authorization server does not support + * obtaining an authorization code using this method. + */ +export declare class UnsupportedResponseTypeError extends OAuthError { + static errorCode: string; +} +/** + * Unsupported token type error - The authorization server does not support + * the requested token type. + */ +export declare class UnsupportedTokenTypeError extends OAuthError { + static errorCode: string; +} +/** + * Invalid token error - The access token provided is expired, revoked, malformed, + * or invalid for other reasons. + */ +export declare class InvalidTokenError extends OAuthError { + static errorCode: string; +} +/** + * Method not allowed error - The HTTP method used is not allowed for this endpoint. + * (Custom, non-standard error) + */ +export declare class MethodNotAllowedError extends OAuthError { + static errorCode: string; +} +/** + * Too many requests error - Rate limit exceeded. + * (Custom, non-standard error based on RFC 6585) + */ +export declare class TooManyRequestsError extends OAuthError { + static errorCode: string; +} +/** + * Invalid client metadata error - The client metadata is invalid. + * (Custom error for dynamic client registration - RFC 7591) + */ +export declare class InvalidClientMetadataError extends OAuthError { + static errorCode: string; +} +/** + * Insufficient scope error - The request requires higher privileges than provided by the access token. + */ +export declare class InsufficientScopeError extends OAuthError { + static errorCode: string; +} +/** + * A utility class for defining one-off error codes + */ +export declare class CustomOAuthError extends OAuthError { + private readonly customErrorCode; + constructor(customErrorCode: string, message: string, errorUri?: string); + get errorCode(): string; +} +/** + * A full list of all OAuthErrors, enabling parsing from error responses + */ +export declare const OAUTH_ERRORS: { + readonly [x: string]: typeof InvalidRequestError; +}; +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/errors.d.ts.map b/dist/cjs/server/auth/errors.d.ts.map new file mode 100644 index 0000000000..5141085c26 --- /dev/null +++ b/dist/cjs/server/auth/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE1D;;GAEG;AACH,qBAAa,UAAW,SAAQ,KAAK;aAKb,QAAQ,CAAC,EAAE,MAAM;IAJrC,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC;gBAGrB,OAAO,EAAE,MAAM,EACC,QAAQ,CAAC,EAAE,MAAM,YAAA;IAMrC;;OAEG;IACH,gBAAgB,IAAI,kBAAkB;IAatC,IAAI,SAAS,IAAI,MAAM,CAEtB;CACJ;AAED;;;;GAIG;AACH,qBAAa,mBAAoB,SAAQ,UAAU;IAC/C,MAAM,CAAC,SAAS,SAAqB;CACxC;AAED;;;GAGG;AACH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AC,SAAS,SAAwB;CAC3C;AAED;;GAEG;AACH,qBAAa,gBAAiB,SAAQ,UAAU;IAExC,OAAO,CAAC,QAAQ,CAAC,eAAe;gBAAf,eAAe,EAAE,MAAM,EACxC,OAAO,EAAE,MAAM,EACf,QAAQ,CAAC,EAAE,MAAM;IAKrB,IAAI,SAAS,IAAI,MAAM,CAEtB;CACJ;AAED;;GAEG;AACH,eAAO,MAAM,YAAY;;CAiBf,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/errors.js b/dist/cjs/server/auth/errors.js new file mode 100644 index 0000000000..6b97cce5d3 --- /dev/null +++ b/dist/cjs/server/auth/errors.js @@ -0,0 +1,193 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OAUTH_ERRORS = exports.CustomOAuthError = exports.InsufficientScopeError = exports.InvalidClientMetadataError = exports.TooManyRequestsError = exports.MethodNotAllowedError = exports.InvalidTokenError = exports.UnsupportedTokenTypeError = exports.UnsupportedResponseTypeError = exports.TemporarilyUnavailableError = exports.ServerError = exports.AccessDeniedError = exports.InvalidScopeError = exports.UnsupportedGrantTypeError = exports.UnauthorizedClientError = exports.InvalidGrantError = exports.InvalidClientError = exports.InvalidRequestError = exports.OAuthError = void 0; +/** + * Base class for all OAuth errors + */ +class OAuthError extends Error { + constructor(message, errorUri) { + super(message); + this.errorUri = errorUri; + this.name = this.constructor.name; + } + /** + * Converts the error to a standard OAuth error response object + */ + toResponseObject() { + const response = { + error: this.errorCode, + error_description: this.message + }; + if (this.errorUri) { + response.error_uri = this.errorUri; + } + return response; + } + get errorCode() { + return this.constructor.errorCode; + } +} +exports.OAuthError = OAuthError; +/** + * Invalid request error - The request is missing a required parameter, + * includes an invalid parameter value, includes a parameter more than once, + * or is otherwise malformed. + */ +class InvalidRequestError extends OAuthError { +} +exports.InvalidRequestError = InvalidRequestError; +InvalidRequestError.errorCode = 'invalid_request'; +/** + * Invalid client error - Client authentication failed (e.g., unknown client, no client + * authentication included, or unsupported authentication method). + */ +class InvalidClientError extends OAuthError { +} +exports.InvalidClientError = InvalidClientError; +InvalidClientError.errorCode = 'invalid_client'; +/** + * Invalid grant error - The provided authorization grant or refresh token is + * invalid, expired, revoked, does not match the redirection URI used in the + * authorization request, or was issued to another client. + */ +class InvalidGrantError extends OAuthError { +} +exports.InvalidGrantError = InvalidGrantError; +InvalidGrantError.errorCode = 'invalid_grant'; +/** + * Unauthorized client error - The authenticated client is not authorized to use + * this authorization grant type. + */ +class UnauthorizedClientError extends OAuthError { +} +exports.UnauthorizedClientError = UnauthorizedClientError; +UnauthorizedClientError.errorCode = 'unauthorized_client'; +/** + * Unsupported grant type error - The authorization grant type is not supported + * by the authorization server. + */ +class UnsupportedGrantTypeError extends OAuthError { +} +exports.UnsupportedGrantTypeError = UnsupportedGrantTypeError; +UnsupportedGrantTypeError.errorCode = 'unsupported_grant_type'; +/** + * Invalid scope error - The requested scope is invalid, unknown, malformed, or + * exceeds the scope granted by the resource owner. + */ +class InvalidScopeError extends OAuthError { +} +exports.InvalidScopeError = InvalidScopeError; +InvalidScopeError.errorCode = 'invalid_scope'; +/** + * Access denied error - The resource owner or authorization server denied the request. + */ +class AccessDeniedError extends OAuthError { +} +exports.AccessDeniedError = AccessDeniedError; +AccessDeniedError.errorCode = 'access_denied'; +/** + * Server error - The authorization server encountered an unexpected condition + * that prevented it from fulfilling the request. + */ +class ServerError extends OAuthError { +} +exports.ServerError = ServerError; +ServerError.errorCode = 'server_error'; +/** + * Temporarily unavailable error - The authorization server is currently unable to + * handle the request due to a temporary overloading or maintenance of the server. + */ +class TemporarilyUnavailableError extends OAuthError { +} +exports.TemporarilyUnavailableError = TemporarilyUnavailableError; +TemporarilyUnavailableError.errorCode = 'temporarily_unavailable'; +/** + * Unsupported response type error - The authorization server does not support + * obtaining an authorization code using this method. + */ +class UnsupportedResponseTypeError extends OAuthError { +} +exports.UnsupportedResponseTypeError = UnsupportedResponseTypeError; +UnsupportedResponseTypeError.errorCode = 'unsupported_response_type'; +/** + * Unsupported token type error - The authorization server does not support + * the requested token type. + */ +class UnsupportedTokenTypeError extends OAuthError { +} +exports.UnsupportedTokenTypeError = UnsupportedTokenTypeError; +UnsupportedTokenTypeError.errorCode = 'unsupported_token_type'; +/** + * Invalid token error - The access token provided is expired, revoked, malformed, + * or invalid for other reasons. + */ +class InvalidTokenError extends OAuthError { +} +exports.InvalidTokenError = InvalidTokenError; +InvalidTokenError.errorCode = 'invalid_token'; +/** + * Method not allowed error - The HTTP method used is not allowed for this endpoint. + * (Custom, non-standard error) + */ +class MethodNotAllowedError extends OAuthError { +} +exports.MethodNotAllowedError = MethodNotAllowedError; +MethodNotAllowedError.errorCode = 'method_not_allowed'; +/** + * Too many requests error - Rate limit exceeded. + * (Custom, non-standard error based on RFC 6585) + */ +class TooManyRequestsError extends OAuthError { +} +exports.TooManyRequestsError = TooManyRequestsError; +TooManyRequestsError.errorCode = 'too_many_requests'; +/** + * Invalid client metadata error - The client metadata is invalid. + * (Custom error for dynamic client registration - RFC 7591) + */ +class InvalidClientMetadataError extends OAuthError { +} +exports.InvalidClientMetadataError = InvalidClientMetadataError; +InvalidClientMetadataError.errorCode = 'invalid_client_metadata'; +/** + * Insufficient scope error - The request requires higher privileges than provided by the access token. + */ +class InsufficientScopeError extends OAuthError { +} +exports.InsufficientScopeError = InsufficientScopeError; +InsufficientScopeError.errorCode = 'insufficient_scope'; +/** + * A utility class for defining one-off error codes + */ +class CustomOAuthError extends OAuthError { + constructor(customErrorCode, message, errorUri) { + super(message, errorUri); + this.customErrorCode = customErrorCode; + } + get errorCode() { + return this.customErrorCode; + } +} +exports.CustomOAuthError = CustomOAuthError; +/** + * A full list of all OAuthErrors, enabling parsing from error responses + */ +exports.OAUTH_ERRORS = { + [InvalidRequestError.errorCode]: InvalidRequestError, + [InvalidClientError.errorCode]: InvalidClientError, + [InvalidGrantError.errorCode]: InvalidGrantError, + [UnauthorizedClientError.errorCode]: UnauthorizedClientError, + [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError, + [InvalidScopeError.errorCode]: InvalidScopeError, + [AccessDeniedError.errorCode]: AccessDeniedError, + [ServerError.errorCode]: ServerError, + [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError, + [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError, + [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError, + [InvalidTokenError.errorCode]: InvalidTokenError, + [MethodNotAllowedError.errorCode]: MethodNotAllowedError, + [TooManyRequestsError.errorCode]: TooManyRequestsError, + [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError, + [InsufficientScopeError.errorCode]: InsufficientScopeError +}; +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/errors.js.map b/dist/cjs/server/auth/errors.js.map new file mode 100644 index 0000000000..974f6ccfd7 --- /dev/null +++ b/dist/cjs/server/auth/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../src/server/auth/errors.ts"],"names":[],"mappings":";;;AAEA;;GAEG;AACH,MAAa,UAAW,SAAQ,KAAK;IAGjC,YACI,OAAe,EACC,QAAiB;QAEjC,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,aAAQ,GAAR,QAAQ,CAAS;QAGjC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;IACtC,CAAC;IAED;;OAEG;IACH,gBAAgB;QACZ,MAAM,QAAQ,GAAuB;YACjC,KAAK,EAAE,IAAI,CAAC,SAAS;YACrB,iBAAiB,EAAE,IAAI,CAAC,OAAO;SAClC,CAAC;QAEF,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAChB,QAAQ,CAAC,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC;QACvC,CAAC;QAED,OAAO,QAAQ,CAAC;IACpB,CAAC;IAED,IAAI,SAAS;QACT,OAAQ,IAAI,CAAC,WAAiC,CAAC,SAAS,CAAC;IAC7D,CAAC;CACJ;A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iBAAiB;IAChD,CAAC,qBAAqB,CAAC,SAAS,CAAC,EAAE,qBAAqB;IACxD,CAAC,oBAAoB,CAAC,SAAS,CAAC,EAAE,oBAAoB;IACtD,CAAC,0BAA0B,CAAC,SAAS,CAAC,EAAE,0BAA0B;IAClE,CAAC,sBAAsB,CAAC,SAAS,CAAC,EAAE,sBAAsB;CACpD,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/authorize.d.ts b/dist/cjs/server/auth/handlers/authorize.d.ts new file mode 100644 index 0000000000..38e9829bd2 --- /dev/null +++ b/dist/cjs/server/auth/handlers/authorize.d.ts @@ -0,0 +1,13 @@ +import { RequestHandler } from 'express'; +import { OAuthServerProvider } from '../provider.js'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type AuthorizationHandlerOptions = { + provider: OAuthServerProvider; + /** + * Rate limiting configuration for the authorization endpoint. + * Set to false to disable rate limiting for this endpoint. + */ + rateLimit?: Partial | false; +}; +export declare function authorizationHandler({ provider, rateLimit: rateLimitConfig }: AuthorizationHandlerOptions): RequestHandler; +//# sourceMappingURL=authorize.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/authorize.d.ts.map b/dist/cjs/server/auth/handlers/authorize.d.ts.map new file mode 100644 index 0000000000..b067988349 --- /dev/null +++ b/dist/cjs/server/auth/handlers/authorize.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"authorize.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/authorize.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAGzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,2BAA2B,GAAG;IACtC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAqBF,wBAAgB,oBAAoB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,2BAA2B,GAAG,cAAc,CAgH1H"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/authorize.js b/dist/cjs/server/auth/handlers/authorize.js new file mode 100644 index 0000000000..9022082196 --- /dev/null +++ b/dist/cjs/server/auth/handlers/authorize.js @@ -0,0 +1,167 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.authorizationHandler = authorizationHandler; +const z = __importStar(require("zod/v4")); +const express_1 = __importDefault(require("express")); +const express_rate_limit_1 = require("express-rate-limit"); +const allowedMethods_js_1 = require("../middleware/allowedMethods.js"); +const errors_js_1 = require("../errors.js"); +// Parameters that must be validated in order to issue redirects. +const ClientAuthorizationParamsSchema = z.object({ + client_id: z.string(), + redirect_uri: z + .string() + .optional() + .refine(value => value === undefined || URL.canParse(value), { message: 'redirect_uri must be a valid URL' }) +}); +// Parameters that must be validated for a successful authorization request. Failure can be reported to the redirect URI. +const RequestAuthorizationParamsSchema = z.object({ + response_type: z.literal('code'), + code_challenge: z.string(), + code_challenge_method: z.literal('S256'), + scope: z.string().optional(), + state: z.string().optional(), + resource: z.string().url().optional() +}); +function authorizationHandler({ provider, rateLimit: rateLimitConfig }) { + // Create a router to apply middleware + const router = express_1.default.Router(); + router.use((0, allowedMethods_js_1.allowedMethods)(['GET', 'POST'])); + router.use(express_1.default.urlencoded({ extended: false })); + // Apply rate limiting unless explicitly disabled + if (rateLimitConfig !== false) { + router.use((0, express_rate_limit_1.rateLimit)({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, // 100 requests per windowMs + standardHeaders: true, + legacyHeaders: false, + message: new errors_js_1.TooManyRequestsError('You have exceeded the rate limit for authorization requests').toResponseObject(), + ...rateLimitConfig + })); + } + router.all('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + // In the authorization flow, errors are split into two categories: + // 1. Pre-redirect errors (direct response with 400) + // 2. Post-redirect errors (redirect with error parameters) + // Phase 1: Validate client_id and redirect_uri. Any errors here must be direct responses. + let client_id, redirect_uri, client; + try { + const result = ClientAuthorizationParamsSchema.safeParse(req.method === 'POST' ? req.body : req.query); + if (!result.success) { + throw new errors_js_1.InvalidRequestError(result.error.message); + } + client_id = result.data.client_id; + redirect_uri = result.data.redirect_uri; + client = await provider.clientsStore.getClient(client_id); + if (!client) { + throw new errors_js_1.InvalidClientError('Invalid client_id'); + } + if (redirect_uri !== undefined) { + if (!client.redirect_uris.includes(redirect_uri)) { + throw new errors_js_1.InvalidRequestError('Unregistered redirect_uri'); + } + } + else if (client.redirect_uris.length === 1) { + redirect_uri = client.redirect_uris[0]; + } + else { + throw new errors_js_1.InvalidRequestError('redirect_uri must be specified when client has multiple registered URIs'); + } + } + catch (error) { + // Pre-redirect errors - return direct response + // + // These don't need to be JSON encoded, as they'll be displayed in a user + // agent, but OTOH they all represent exceptional situations (arguably, + // "programmer error"), so presenting a nice HTML page doesn't help the + // user anyway. + if (error instanceof errors_js_1.OAuthError) { + const status = error instanceof errors_js_1.ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new errors_js_1.ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + return; + } + // Phase 2: Validate other parameters. Any errors here should go into redirect responses. + let state; + try { + // Parse and validate authorization parameters + const parseResult = RequestAuthorizationParamsSchema.safeParse(req.method === 'POST' ? req.body : req.query); + if (!parseResult.success) { + throw new errors_js_1.InvalidRequestError(parseResult.error.message); + } + const { scope, code_challenge, resource } = parseResult.data; + state = parseResult.data.state; + // Validate scopes + let requestedScopes = []; + if (scope !== undefined) { + requestedScopes = scope.split(' '); + } + // All validation passed, proceed with authorization + await provider.authorize(client, { + state, + scopes: requestedScopes, + redirectUri: redirect_uri, + codeChallenge: code_challenge, + resource: resource ? new URL(resource) : undefined + }, res); + } + catch (error) { + // Post-redirect errors - redirect with error parameters + if (error instanceof errors_js_1.OAuthError) { + res.redirect(302, createErrorRedirect(redirect_uri, error, state)); + } + else { + const serverError = new errors_js_1.ServerError('Internal Server Error'); + res.redirect(302, createErrorRedirect(redirect_uri, serverError, state)); + } + } + }); + return router; +} +/** + * Helper function to create redirect URL with error parameters + */ +function createErrorRedirect(redirectUri, error, state) { + const errorUrl = new URL(redirectUri); + errorUrl.searchParams.set('error', error.errorCode); + errorUrl.searchParams.set('error_description', error.message); + if (error.errorUri) { + errorUrl.searchParams.set('error_uri', error.errorUri); + } + if (state) { + errorUrl.searchParams.set('state', state); + } + return errorUrl.href; +} +//# sourceMappingURL=authorize.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/authorize.js.map b/dist/cjs/server/auth/handlers/authorize.js.map new file mode 100644 index 0000000000..28e876271b --- /dev/null +++ b/dist/cjs/server/auth/handlers/authorize.js.map @@ -0,0 +1 @@ +{"version":3,"file":"authorize.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/authorize.ts"],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,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;GAEG;AACH,SAAS,mBAAmB,CAAC,WAAmB,EAAE,KAAiB,EAAE,KAAc;IAC/E,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,WAAW,CAAC,CAAC;IACtC,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IACpD,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,mBAAmB,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;IAC9D,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;QACjB,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,WAAW,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC3D,CAAC;IACD,IAAI,KAAK,EAAE,CAAC;QACR,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC9C,CAAC;IACD,OAAO,QAAQ,CAAC,IAAI,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/metadata.d.ts b/dist/cjs/server/auth/handlers/metadata.d.ts new file mode 100644 index 0000000000..4d03286170 --- /dev/null +++ b/dist/cjs/server/auth/handlers/metadata.d.ts @@ -0,0 +1,4 @@ +import { RequestHandler } from 'express'; +import { OAuthMetadata, OAuthProtectedResourceMetadata } from '../../../shared/auth.js'; +export declare function metadataHandler(metadata: OAuthMetadata | OAuthProtectedResourceMetadata): RequestHandler; +//# sourceMappingURL=metadata.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/metadata.d.ts.map b/dist/cjs/server/auth/handlers/metadata.d.ts.map new file mode 100644 index 0000000000..55e3a50dc1 --- /dev/null +++ b/dist/cjs/server/auth/handlers/metadata.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"metadata.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/metadata.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,8BAA8B,EAAE,MAAM,yBAAyB,CAAC;AAIxF,wBAAgB,eAAe,CAAC,QAAQ,EAAE,aAAa,GAAG,8BAA8B,GAAG,cAAc,CAaxG"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/metadata.js b/dist/cjs/server/auth/handlers/metadata.js new file mode 100644 index 0000000000..4e00bc588e --- /dev/null +++ b/dist/cjs/server/auth/handlers/metadata.js @@ -0,0 +1,21 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.metadataHandler = metadataHandler; +const express_1 = __importDefault(require("express")); +const cors_1 = __importDefault(require("cors")); +const allowedMethods_js_1 = require("../middleware/allowedMethods.js"); +function metadataHandler(metadata) { + // Nested router so we can configure middleware and restrict HTTP method + const router = express_1.default.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use((0, cors_1.default)()); + router.use((0, allowedMethods_js_1.allowedMethods)(['GET', 'OPTIONS'])); + router.get('/', (req, res) => { + res.status(200).json(metadata); + }); + return router; +} +//# sourceMappingURL=metadata.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/metadata.js.map b/dist/cjs/server/auth/handlers/metadata.js.map new file mode 100644 index 0000000000..9679c9fa50 --- /dev/null +++ b/dist/cjs/server/auth/handlers/metadata.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/metadata.ts"],"names":[],"mappings":";;;;;AAKA,0CAaC;AAlBD,sDAAkD;AAElD,gDAAwB;AACxB,uEAAiE;AAEjE,SAAgB,eAAe,CAAC,QAAwD;IACpF,wEAAwE;IACxE,MAAM,MAAM,GAAG,iBAAO,CAAC,MAAM,EAAE,CAAC;IAEhC,kFAAkF;IAClF,MAAM,CAAC,GAAG,CAAC,IAAA,cAAI,GAAE,CAAC,CAAC;IAEnB,MAAM,CAAC,GAAG,CAAC,IAAA,kCAAc,EAAC,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;IAC/C,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;QACzB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACnC,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/register.d.ts b/dist/cjs/server/auth/handlers/register.d.ts new file mode 100644 index 0000000000..e9add28458 --- /dev/null +++ b/dist/cjs/server/auth/handlers/register.d.ts @@ -0,0 +1,29 @@ +import { RequestHandler } from 'express'; +import { OAuthRegisteredClientsStore } from '../clients.js'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type ClientRegistrationHandlerOptions = { + /** + * A store used to save information about dynamically registered OAuth clients. + */ + clientsStore: OAuthRegisteredClientsStore; + /** + * The number of seconds after which to expire issued client secrets, or 0 to prevent expiration of client secrets (not recommended). + * + * If not set, defaults to 30 days. + */ + clientSecretExpirySeconds?: number; + /** + * Rate limiting configuration for the client registration endpoint. + * Set to false to disable rate limiting for this endpoint. + * Registration endpoints are particularly sensitive to abuse and should be rate limited. + */ + rateLimit?: Partial | false; + /** + * Whether to generate a client ID before calling the client registration endpoint. + * + * If not set, defaults to true. + */ + clientIdGeneration?: boolean; +}; +export declare function clientRegistrationHandler({ clientsStore, clientSecretExpirySeconds, rateLimit: rateLimitConfig, clientIdGeneration }: ClientRegistrationHandlerOptions): RequestHandler; +//# sourceMappingURL=register.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/register.d.ts.map b/dist/cjs/server/auth/handlers/register.d.ts.map new file mode 100644 index 0000000000..a38ebdb89e --- /dev/null +++ b/dist/cjs/server/auth/handlers/register.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"register.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/register.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAIlD,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,gCAAgC,GAAG;IAC3C;;OAEG;IACH,YAAY,EAAE,2BAA2B,CAAC;IAE1C;;;;OAIG;IACH,yBAAyB,CAAC,EAAE,MAAM,CAAC;IAEnC;;;;OAIG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;IAE9C;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAChC,CAAC;AAIF,wBAAgB,yBAAyB,CAAC,EACtC,YAAY,EACZ,yBAAgE,EAChE,SAAS,EAAE,eAAe,EAC1B,kBAAyB,EAC5B,EAAE,gCAAgC,GAAG,cAAc,CA0EnD"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/register.js b/dist/cjs/server/auth/handlers/register.js new file mode 100644 index 0000000000..e40c5c904e --- /dev/null +++ b/dist/cjs/server/auth/handlers/register.js @@ -0,0 +1,77 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.clientRegistrationHandler = clientRegistrationHandler; +const express_1 = __importDefault(require("express")); +const auth_js_1 = require("../../../shared/auth.js"); +const node_crypto_1 = __importDefault(require("node:crypto")); +const cors_1 = __importDefault(require("cors")); +const express_rate_limit_1 = require("express-rate-limit"); +const allowedMethods_js_1 = require("../middleware/allowedMethods.js"); +const errors_js_1 = require("../errors.js"); +const DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS = 30 * 24 * 60 * 60; // 30 days +function clientRegistrationHandler({ clientsStore, clientSecretExpirySeconds = DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS, rateLimit: rateLimitConfig, clientIdGeneration = true }) { + if (!clientsStore.registerClient) { + throw new Error('Client registration store does not support registering clients'); + } + // Nested router so we can configure middleware and restrict HTTP method + const router = express_1.default.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use((0, cors_1.default)()); + router.use((0, allowedMethods_js_1.allowedMethods)(['POST'])); + router.use(express_1.default.json()); + // Apply rate limiting unless explicitly disabled - stricter limits for registration + if (rateLimitConfig !== false) { + router.use((0, express_rate_limit_1.rateLimit)({ + windowMs: 60 * 60 * 1000, // 1 hour + max: 20, // 20 requests per hour - stricter as registration is sensitive + standardHeaders: true, + legacyHeaders: false, + message: new errors_js_1.TooManyRequestsError('You have exceeded the rate limit for client registration requests').toResponseObject(), + ...rateLimitConfig + })); + } + router.post('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + try { + const parseResult = auth_js_1.OAuthClientMetadataSchema.safeParse(req.body); + if (!parseResult.success) { + throw new errors_js_1.InvalidClientMetadataError(parseResult.error.message); + } + const clientMetadata = parseResult.data; + const isPublicClient = clientMetadata.token_endpoint_auth_method === 'none'; + // Generate client credentials + const clientSecret = isPublicClient ? undefined : node_crypto_1.default.randomBytes(32).toString('hex'); + const clientIdIssuedAt = Math.floor(Date.now() / 1000); + // Calculate client secret expiry time + const clientsDoExpire = clientSecretExpirySeconds > 0; + const secretExpiryTime = clientsDoExpire ? clientIdIssuedAt + clientSecretExpirySeconds : 0; + const clientSecretExpiresAt = isPublicClient ? undefined : secretExpiryTime; + let clientInfo = { + ...clientMetadata, + client_secret: clientSecret, + client_secret_expires_at: clientSecretExpiresAt + }; + if (clientIdGeneration) { + clientInfo.client_id = node_crypto_1.default.randomUUID(); + clientInfo.client_id_issued_at = clientIdIssuedAt; + } + clientInfo = await clientsStore.registerClient(clientInfo); + res.status(201).json(clientInfo); + } + catch (error) { + if (error instanceof errors_js_1.OAuthError) { + const status = error instanceof errors_js_1.ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new errors_js_1.ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }); + return router; +} +//# sourceMappingURL=register.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/register.js.map b/dist/cjs/server/auth/handlers/register.js.map new file mode 100644 index 0000000000..e116a474fd --- /dev/null +++ b/dist/cjs/server/auth/handlers/register.js.map @@ -0,0 +1 @@ +{"version":3,"file":"register.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/register.ts"],"names":[],"mappings":";;;;;AAuCA,8DA+EC;AAtHD,sDAAkD;AAClD,qDAAgG;AAChG,8DAAiC;AACjC,gDAAwB;AAExB,2DAA4E;AAC5E,uEAAiE;AACjE,4CAAyG;AA8BzG,MAAM,oCAAoC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,UAAU;AAE1E,SAAgB,yBAAyB,CAAC,EACtC,YAAY,EACZ,yBAAyB,GAAG,oCAAoC,EAChE,SAAS,EAAE,eAAe,EAC1B,kBAAkB,GAAG,IAAI,EACM;IAC/B,IAAI,CAAC,YAAY,CAAC,cAAc,EAAE,CAAC;QAC/B,MAAM,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAC;IACtF,CAAC;IAED,wEAAwE;IACxE,MAAM,MAAM,GAAG,iBAAO,CAAC,MAAM,EAAE,CAAC;IAEhC,kFAAkF;IAClF,MAAM,CAAC,GAAG,CAAC,IAAA,cAAI,GAAE,CAAC,CAAC;IAEnB,MAAM,CAAC,GAAG,CAAC,IAAA,kCAAc,EAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACrC,MAAM,CAAC,GAAG,CAAC,iBAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IAE3B,oFAAoF;IACpF,IAAI,eAAe,KAAK,KAAK,EAAE,CAAC;QAC5B,MAAM,CAAC,G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,qBAAqB,GAAG,cAAc,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,gBAAgB,CAAC;YAE5E,IAAI,UAAU,GAA2E;gBACrF,GAAG,cAAc;gBACjB,aAAa,EAAE,YAAY;gBAC3B,wBAAwB,EAAE,qBAAqB;aAClD,CAAC;YAEF,IAAI,kBAAkB,EAAE,CAAC;gBACrB,UAAU,CAAC,SAAS,GAAG,qBAAM,CAAC,UAAU,EAAE,CAAC;gBAC3C,UAAU,CAAC,mBAAmB,GAAG,gBAAgB,CAAC;YACtD,CAAC;YAED,UAAU,GAAG,MAAM,YAAY,CAAC,cAAe,CAAC,UAAU,CAAC,CAAC;YAC5D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACrC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,KAAK,YAAY,sBAAU,EAAE,CAAC;gBAC9B,MAAM,MAAM,GAAG,KAAK,YAAY,uBAAW,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;gBACxD,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,uBAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/revoke.d.ts b/dist/cjs/server/auth/handlers/revoke.d.ts new file mode 100644 index 0000000000..2be32bb3ca --- /dev/null +++ b/dist/cjs/server/auth/handlers/revoke.d.ts @@ -0,0 +1,13 @@ +import { OAuthServerProvider } from '../provider.js'; +import { RequestHandler } from 'express'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type RevocationHandlerOptions = { + provider: OAuthServerProvider; + /** + * Rate limiting configuration for the token revocation endpoint. + * Set to false to disable rate limiting for this endpoint. + */ + rateLimit?: Partial | false; +}; +export declare function revocationHandler({ provider, rateLimit: rateLimitConfig }: RevocationHandlerOptions): RequestHandler; +//# sourceMappingURL=revoke.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/revoke.d.ts.map b/dist/cjs/server/auth/handlers/revoke.d.ts.map new file mode 100644 index 0000000000..fb13cf19fe --- /dev/null +++ b/dist/cjs/server/auth/handlers/revoke.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"revoke.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/revoke.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAIlD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,wBAAwB,GAAG;IACnC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAEF,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,wBAAwB,GAAG,cAAc,CA4DpH"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/revoke.js b/dist/cjs/server/auth/handlers/revoke.js new file mode 100644 index 0000000000..4fb1da738a --- /dev/null +++ b/dist/cjs/server/auth/handlers/revoke.js @@ -0,0 +1,65 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.revocationHandler = revocationHandler; +const express_1 = __importDefault(require("express")); +const cors_1 = __importDefault(require("cors")); +const clientAuth_js_1 = require("../middleware/clientAuth.js"); +const auth_js_1 = require("../../../shared/auth.js"); +const express_rate_limit_1 = require("express-rate-limit"); +const allowedMethods_js_1 = require("../middleware/allowedMethods.js"); +const errors_js_1 = require("../errors.js"); +function revocationHandler({ provider, rateLimit: rateLimitConfig }) { + if (!provider.revokeToken) { + throw new Error('Auth provider does not support revoking tokens'); + } + // Nested router so we can configure middleware and restrict HTTP method + const router = express_1.default.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use((0, cors_1.default)()); + router.use((0, allowedMethods_js_1.allowedMethods)(['POST'])); + router.use(express_1.default.urlencoded({ extended: false })); + // Apply rate limiting unless explicitly disabled + if (rateLimitConfig !== false) { + router.use((0, express_rate_limit_1.rateLimit)({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 50, // 50 requests per windowMs + standardHeaders: true, + legacyHeaders: false, + message: new errors_js_1.TooManyRequestsError('You have exceeded the rate limit for token revocation requests').toResponseObject(), + ...rateLimitConfig + })); + } + // Authenticate and extract client details + router.use((0, clientAuth_js_1.authenticateClient)({ clientsStore: provider.clientsStore })); + router.post('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + try { + const parseResult = auth_js_1.OAuthTokenRevocationRequestSchema.safeParse(req.body); + if (!parseResult.success) { + throw new errors_js_1.InvalidRequestError(parseResult.error.message); + } + const client = req.client; + if (!client) { + // This should never happen + throw new errors_js_1.ServerError('Internal Server Error'); + } + await provider.revokeToken(client, parseResult.data); + res.status(200).json({}); + } + catch (error) { + if (error instanceof errors_js_1.OAuthError) { + const status = error instanceof errors_js_1.ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new errors_js_1.ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }); + return router; +} +//# sourceMappingURL=revoke.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/revoke.js.map b/dist/cjs/server/auth/handlers/revoke.js.map new file mode 100644 index 0000000000..ca01fee7f5 --- /dev/null +++ b/dist/cjs/server/auth/handlers/revoke.js.map @@ -0,0 +1 @@ +{"version":3,"file":"revoke.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/revoke.ts"],"names":[],"mappings":";;;;;AAkBA,8CA4DC;AA7ED,sDAAkD;AAClD,gDAAwB;AACxB,+DAAiE;AACjE,qDAA4E;AAC5E,2DAA4E;AAC5E,uEAAiE;AACjE,4CAAkG;AAWlG,SAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAA4B;IAChG,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;IACtE,CAAC;IAED,wEAAwE;IACxE,MAAM,MAAM,GAAG,iBAAO,CAAC,MAAM,EAAE,CAAC;IAEhC,kFAAkF;IAClF,MAAM,CAAC,GAAG,CAAC,IAAA,cAAI,GAAE,CAAC,CAAC;IAEnB,MAAM,CAAC,GAAG,CAAC,IAAA,kCAAc,EAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACrC,MAAM,CAAC,GAAG,CAAC,iBAAO,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;IAEpD,iDAAiD;IACjD,IAAI,eAAe,KAAK,KAAK,EAAE,CAAC;QAC5B,MAAM,CAAC,GAAG,CACN,IAAA,8BAAS,EAAC;YACN,QAAQ,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI,EAAE,aAAa;YACvC,GAAG,EAAE,EAAE,EAAE,2BAA2B;YACpC,eAAe,EAAE,IAAI;YACrB,aAAa,EAAE,KAAK;YACpB,OAAO,EAAE,IAAI,gCAAoB,CAAC,gEAAgE,CAAC,CAAC,gBAAgB,EAAE;YACtH,GAAG,eAAe;SACrB,CAAC,CACL,CAAC;IACN,CAAC;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AAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/token.d.ts b/dist/cjs/server/auth/handlers/token.d.ts new file mode 100644 index 0000000000..24d1c8783b --- /dev/null +++ b/dist/cjs/server/auth/handlers/token.d.ts @@ -0,0 +1,13 @@ +import { RequestHandler } from 'express'; +import { OAuthServerProvider } from '../provider.js'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type TokenHandlerOptions = { + provider: OAuthServerProvider; + /** + * Rate limiting configuration for the token endpoint. + * Set to false to disable rate limiting for this endpoint. + */ + rateLimit?: Partial | false; +}; +export declare function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHandlerOptions): RequestHandler; +//# sourceMappingURL=token.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/token.d.ts.map b/dist/cjs/server/auth/handlers/token.d.ts.map new file mode 100644 index 0000000000..3d539f3451 --- /dev/null +++ b/dist/cjs/server/auth/handlers/token.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/token.ts"],"names":[],"mappings":"AACA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAIrD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAW5E,MAAM,MAAM,mBAAmB,GAAG;IAC9B,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAmBF,wBAAgB,YAAY,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,mBAAmB,GAAG,cAAc,CAiH1G"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/token.js b/dist/cjs/server/auth/handlers/token.js new file mode 100644 index 0000000000..c88bb294f8 --- /dev/null +++ b/dist/cjs/server/auth/handlers/token.js @@ -0,0 +1,136 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.tokenHandler = tokenHandler; +const z = __importStar(require("zod/v4")); +const express_1 = __importDefault(require("express")); +const cors_1 = __importDefault(require("cors")); +const pkce_challenge_1 = require("pkce-challenge"); +const clientAuth_js_1 = require("../middleware/clientAuth.js"); +const express_rate_limit_1 = require("express-rate-limit"); +const allowedMethods_js_1 = require("../middleware/allowedMethods.js"); +const errors_js_1 = require("../errors.js"); +const TokenRequestSchema = z.object({ + grant_type: z.string() +}); +const AuthorizationCodeGrantSchema = z.object({ + code: z.string(), + code_verifier: z.string(), + redirect_uri: z.string().optional(), + resource: z.string().url().optional() +}); +const RefreshTokenGrantSchema = z.object({ + refresh_token: z.string(), + scope: z.string().optional(), + resource: z.string().url().optional() +}); +function tokenHandler({ provider, rateLimit: rateLimitConfig }) { + // Nested router so we can configure middleware and restrict HTTP method + const router = express_1.default.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use((0, cors_1.default)()); + router.use((0, allowedMethods_js_1.allowedMethods)(['POST'])); + router.use(express_1.default.urlencoded({ extended: false })); + // Apply rate limiting unless explicitly disabled + if (rateLimitConfig !== false) { + router.use((0, express_rate_limit_1.rateLimit)({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 50, // 50 requests per windowMs + standardHeaders: true, + legacyHeaders: false, + message: new errors_js_1.TooManyRequestsError('You have exceeded the rate limit for token requests').toResponseObject(), + ...rateLimitConfig + })); + } + // Authenticate and extract client details + router.use((0, clientAuth_js_1.authenticateClient)({ clientsStore: provider.clientsStore })); + router.post('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + try { + const parseResult = TokenRequestSchema.safeParse(req.body); + if (!parseResult.success) { + throw new errors_js_1.InvalidRequestError(parseResult.error.message); + } + const { grant_type } = parseResult.data; + const client = req.client; + if (!client) { + // This should never happen + throw new errors_js_1.ServerError('Internal Server Error'); + } + switch (grant_type) { + case 'authorization_code': { + const parseResult = AuthorizationCodeGrantSchema.safeParse(req.body); + if (!parseResult.success) { + throw new errors_js_1.InvalidRequestError(parseResult.error.message); + } + const { code, code_verifier, redirect_uri, resource } = parseResult.data; + const skipLocalPkceValidation = provider.skipLocalPkceValidation; + // Perform local PKCE validation unless explicitly skipped + // (e.g. to validate code_verifier in upstream server) + if (!skipLocalPkceValidation) { + const codeChallenge = await provider.challengeForAuthorizationCode(client, code); + if (!(await (0, pkce_challenge_1.verifyChallenge)(code_verifier, codeChallenge))) { + throw new errors_js_1.InvalidGrantError('code_verifier does not match the challenge'); + } + } + // Passes the code_verifier to the provider if PKCE validation didn't occur locally + const tokens = await provider.exchangeAuthorizationCode(client, code, skipLocalPkceValidation ? code_verifier : undefined, redirect_uri, resource ? new URL(resource) : undefined); + res.status(200).json(tokens); + break; + } + case 'refresh_token': { + const parseResult = RefreshTokenGrantSchema.safeParse(req.body); + if (!parseResult.success) { + throw new errors_js_1.InvalidRequestError(parseResult.error.message); + } + const { refresh_token, scope, resource } = parseResult.data; + const scopes = scope === null || scope === void 0 ? void 0 : scope.split(' '); + const tokens = await provider.exchangeRefreshToken(client, refresh_token, scopes, resource ? new URL(resource) : undefined); + res.status(200).json(tokens); + break; + } + // Not supported right now + //case "client_credentials": + default: + throw new errors_js_1.UnsupportedGrantTypeError('The grant type is not supported by this authorization server.'); + } + } + catch (error) { + if (error instanceof errors_js_1.OAuthError) { + const status = error instanceof errors_js_1.ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new errors_js_1.ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }); + return router; +} +//# sourceMappingURL=token.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/token.js.map b/dist/cjs/server/auth/handlers/token.js.map new file mode 100644 index 0000000000..4ca53c5bc4 --- /dev/null +++ b/dist/cjs/server/auth/handlers/token.js.map @@ -0,0 +1 @@ +{"version":3,"file":"token.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/token.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,oCAiHC;AA5JD,0CAA4B;AAC5B,sDAAkD;AAElD,gDAAwB;AACxB,mDAAiD;AACjD,+DAAiE;AACjE,2DAA4E;AAC5E,uEAAiE;AACjE,4CAOsB;AAWtB,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC;IAChC,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE;CACzB,CAAC,CAAC;AAEH,MAAM,4BAA4B,GAAG,CAAC,CAAC,MAAM,CAAC;IAC1C,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE;IAChB,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE;IACzB,YAAY,EAAE,CAAC,CAA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C,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;oBAC7B,MAAM;gBACV,CAAC;gBAED,0BAA0B;gBAC1B,4BAA4B;gBAE5B;oBACI,MAAM,IAAI,qCAAyB,CAAC,+DAA+D,CAAC,CAAC;YAC7G,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,KAAK,YAAY,sBAAU,EAAE,CAAC;gBAC9B,MAAM,MAAM,GAAG,KAAK,YAAY,uBAAW,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;gBACxD,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,uBAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/allowedMethods.d.ts b/dist/cjs/server/auth/middleware/allowedMethods.d.ts new file mode 100644 index 0000000000..ee6037e0de --- /dev/null +++ b/dist/cjs/server/auth/middleware/allowedMethods.d.ts @@ -0,0 +1,9 @@ +import { RequestHandler } from 'express'; +/** + * Middleware to handle unsupported HTTP methods with a 405 Method Not Allowed response. + * + * @param allowedMethods Array of allowed HTTP methods for this endpoint (e.g., ['GET', 'POST']) + * @returns Express middleware that returns a 405 error if method not in allowed list + */ +export declare function allowedMethods(allowedMethods: string[]): RequestHandler; +//# sourceMappingURL=allowedMethods.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/allowedMethods.d.ts.map b/dist/cjs/server/auth/middleware/allowedMethods.d.ts.map new file mode 100644 index 0000000000..d3de93e242 --- /dev/null +++ b/dist/cjs/server/auth/middleware/allowedMethods.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"allowedMethods.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/allowedMethods.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAGzC;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,cAAc,EAAE,MAAM,EAAE,GAAG,cAAc,CAUvE"} \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/allowedMethods.js b/dist/cjs/server/auth/middleware/allowedMethods.js new file mode 100644 index 0000000000..f445537458 --- /dev/null +++ b/dist/cjs/server/auth/middleware/allowedMethods.js @@ -0,0 +1,21 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.allowedMethods = allowedMethods; +const errors_js_1 = require("../errors.js"); +/** + * Middleware to handle unsupported HTTP methods with a 405 Method Not Allowed response. + * + * @param allowedMethods Array of allowed HTTP methods for this endpoint (e.g., ['GET', 'POST']) + * @returns Express middleware that returns a 405 error if method not in allowed list + */ +function allowedMethods(allowedMethods) { + return (req, res, next) => { + if (allowedMethods.includes(req.method)) { + next(); + return; + } + const error = new errors_js_1.MethodNotAllowedError(`The method ${req.method} is not allowed for this endpoint`); + res.status(405).set('Allow', allowedMethods.join(', ')).json(error.toResponseObject()); + }; +} +//# sourceMappingURL=allowedMethods.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/allowedMethods.js.map b/dist/cjs/server/auth/middleware/allowedMethods.js.map new file mode 100644 index 0000000000..be69f33771 --- /dev/null +++ b/dist/cjs/server/auth/middleware/allowedMethods.js.map @@ -0,0 +1 @@ +{"version":3,"file":"allowedMethods.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/allowedMethods.ts"],"names":[],"mappings":";;AASA,wCAUC;AAlBD,4CAAqD;AAErD;;;;;GAKG;AACH,SAAgB,cAAc,CAAC,cAAwB;IACnD,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACtB,IAAI,cAAc,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;YACtC,IAAI,EAAE,CAAC;YACP,OAAO;QACX,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,iCAAqB,CAAC,cAAc,GAAG,CAAC,MAAM,mCAAmC,CAAC,CAAC;QACrG,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;IAC3F,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/bearerAuth.d.ts b/dist/cjs/server/auth/middleware/bearerAuth.d.ts new file mode 100644 index 0000000000..10730758bc --- /dev/null +++ b/dist/cjs/server/auth/middleware/bearerAuth.d.ts @@ -0,0 +1,35 @@ +import { RequestHandler } from 'express'; +import { OAuthTokenVerifier } from '../provider.js'; +import { AuthInfo } from '../types.js'; +export type BearerAuthMiddlewareOptions = { + /** + * A provider used to verify tokens. + */ + verifier: OAuthTokenVerifier; + /** + * Optional scopes that the token must have. + */ + requiredScopes?: string[]; + /** + * Optional resource metadata URL to include in WWW-Authenticate header. + */ + resourceMetadataUrl?: string; +}; +declare module 'express-serve-static-core' { + interface Request { + /** + * Information about the validated access token, if the `requireBearerAuth` middleware was used. + */ + auth?: AuthInfo; + } +} +/** + * Middleware that requires a valid Bearer token in the Authorization header. + * + * This will validate the token with the auth provider and add the resulting auth info to the request object. + * + * If resourceMetadataUrl is provided, it will be included in the WWW-Authenticate header + * for 401 responses as per the OAuth 2.0 Protected Resource Metadata spec. + */ +export declare function requireBearerAuth({ verifier, requiredScopes, resourceMetadataUrl }: BearerAuthMiddlewareOptions): RequestHandler; +//# sourceMappingURL=bearerAuth.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/bearerAuth.d.ts.map b/dist/cjs/server/auth/middleware/bearerAuth.d.ts.map new file mode 100644 index 0000000000..c9d939f3b7 --- /dev/null +++ b/dist/cjs/server/auth/middleware/bearerAuth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bearerAuth.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/bearerAuth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,MAAM,MAAM,2BAA2B,GAAG;IACtC;;OAEG;IACH,QAAQ,EAAE,kBAAkB,CAAC;IAE7B;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAE1B;;OAEG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAChC,CAAC;AAEF,OAAO,QAAQ,2BAA2B,CAAC;IACvC,UAAU,OAAO;QACb;;WAEG;QACH,IAAI,CAAC,EAAE,QAAQ,CAAC;KACnB;CACJ;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,cAAmB,EAAE,mBAAmB,EAAE,EAAE,2BAA2B,GAAG,cAAc,CA8DrI"} \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/bearerAuth.js b/dist/cjs/server/auth/middleware/bearerAuth.js new file mode 100644 index 0000000000..dcfc509356 --- /dev/null +++ b/dist/cjs/server/auth/middleware/bearerAuth.js @@ -0,0 +1,75 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.requireBearerAuth = requireBearerAuth; +const errors_js_1 = require("../errors.js"); +/** + * Middleware that requires a valid Bearer token in the Authorization header. + * + * This will validate the token with the auth provider and add the resulting auth info to the request object. + * + * If resourceMetadataUrl is provided, it will be included in the WWW-Authenticate header + * for 401 responses as per the OAuth 2.0 Protected Resource Metadata spec. + */ +function requireBearerAuth({ verifier, requiredScopes = [], resourceMetadataUrl }) { + return async (req, res, next) => { + try { + const authHeader = req.headers.authorization; + if (!authHeader) { + throw new errors_js_1.InvalidTokenError('Missing Authorization header'); + } + const [type, token] = authHeader.split(' '); + if (type.toLowerCase() !== 'bearer' || !token) { + throw new errors_js_1.InvalidTokenError("Invalid Authorization header format, expected 'Bearer TOKEN'"); + } + const authInfo = await verifier.verifyAccessToken(token); + // Check if token has the required scopes (if any) + if (requiredScopes.length > 0) { + const hasAllScopes = requiredScopes.every(scope => authInfo.scopes.includes(scope)); + if (!hasAllScopes) { + throw new errors_js_1.InsufficientScopeError('Insufficient scope'); + } + } + // Check if the token is set to expire or if it is expired + if (typeof authInfo.expiresAt !== 'number' || isNaN(authInfo.expiresAt)) { + throw new errors_js_1.InvalidTokenError('Token has no expiration time'); + } + else if (authInfo.expiresAt < Date.now() / 1000) { + throw new errors_js_1.InvalidTokenError('Token has expired'); + } + req.auth = authInfo; + next(); + } + catch (error) { + // Build WWW-Authenticate header parts + const buildWwwAuthHeader = (errorCode, message) => { + let header = `Bearer error="${errorCode}", error_description="${message}"`; + if (requiredScopes.length > 0) { + header += `, scope="${requiredScopes.join(' ')}"`; + } + if (resourceMetadataUrl) { + header += `, resource_metadata="${resourceMetadataUrl}"`; + } + return header; + }; + if (error instanceof errors_js_1.InvalidTokenError) { + res.set('WWW-Authenticate', buildWwwAuthHeader(error.errorCode, error.message)); + res.status(401).json(error.toResponseObject()); + } + else if (error instanceof errors_js_1.InsufficientScopeError) { + res.set('WWW-Authenticate', buildWwwAuthHeader(error.errorCode, error.message)); + res.status(403).json(error.toResponseObject()); + } + else if (error instanceof errors_js_1.ServerError) { + res.status(500).json(error.toResponseObject()); + } + else if (error instanceof errors_js_1.OAuthError) { + res.status(400).json(error.toResponseObject()); + } + else { + const serverError = new errors_js_1.ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }; +} +//# sourceMappingURL=bearerAuth.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/bearerAuth.js.map b/dist/cjs/server/auth/middleware/bearerAuth.js.map new file mode 100644 index 0000000000..d111d36bf8 --- /dev/null +++ b/dist/cjs/server/auth/middleware/bearerAuth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bearerAuth.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/bearerAuth.ts"],"names":[],"mappings":";;AAuCA,8CA8DC;AApGD,4CAAkG;AA8BlG;;;;;;;GAOG;AACH,SAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,cAAc,GAAG,EAAE,EAAE,mBAAmB,EAA+B;IACjH,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC5B,IAAI,CAAC;YACD,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,aAAa,CAAC;YAC7C,IAAI,CAAC,UAAU,EAAE,CAAC;gBACd,MAAM,IAAI,6BAAiB,CAAC,8BAA8B,CAAC,CAAC;YAChE,CAAC;YAED,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAC5C,IAAI,IAAI,CAAC,WAAW,EAAE,KAAK,QAAQ,IAAI,CAAC,KAAK,EAAE,CAAC;gBAC5C,MAAM,IAAI,6BAAiB,CAAC,8DAA8D,CAAC,CAAC;YAChG,CAAC;YAED,MAAM,QAAQ,GAAG,MAAM,QAAQ,CAAC,iBAAiB,CAAC,KAAK,CAAC,CAAC;YAEzD,kDAAkD;YAClD,IAAI,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAC5B,MAAM,YAAY,GAAG,cAAc,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;gBAEpF,IAAI,CAAC,YAAY,E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CAAC;iBAAM,IAAI,KAAK,YAAY,kCAAsB,EAAE,CAAC;gBACjD,GAAG,CAAC,GAAG,CAAC,kBAAkB,EAAE,kBAAkB,CAAC,KAAK,CAAC,SAAS,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;gBAChF,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACnD,CAAC;iBAAM,IAAI,KAAK,YAAY,uBAAW,EAAE,CAAC;gBACtC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACnD,CAAC;iBAAM,IAAI,KAAK,YAAY,sBAAU,EAAE,CAAC;gBACrC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACnD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,uBAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/clientAuth.d.ts b/dist/cjs/server/auth/middleware/clientAuth.d.ts new file mode 100644 index 0000000000..837f95fd29 --- /dev/null +++ b/dist/cjs/server/auth/middleware/clientAuth.d.ts @@ -0,0 +1,19 @@ +import { RequestHandler } from 'express'; +import { OAuthRegisteredClientsStore } from '../clients.js'; +import { OAuthClientInformationFull } from '../../../shared/auth.js'; +export type ClientAuthenticationMiddlewareOptions = { + /** + * A store used to read information about registered OAuth clients. + */ + clientsStore: OAuthRegisteredClientsStore; +}; +declare module 'express-serve-static-core' { + interface Request { + /** + * The authenticated client for this request, if the `authenticateClient` middleware was used. + */ + client?: OAuthClientInformationFull; + } +} +export declare function authenticateClient({ clientsStore }: ClientAuthenticationMiddlewareOptions): RequestHandler; +//# sourceMappingURL=clientAuth.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/clientAuth.d.ts.map b/dist/cjs/server/auth/middleware/clientAuth.d.ts.map new file mode 100644 index 0000000000..5dfa3924f2 --- /dev/null +++ b/dist/cjs/server/auth/middleware/clientAuth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"clientAuth.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/clientAuth.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AAGrE,MAAM,MAAM,qCAAqC,GAAG;IAChD;;OAEG;IACH,YAAY,EAAE,2BAA2B,CAAC;CAC7C,CAAC;AAOF,OAAO,QAAQ,2BAA2B,CAAC;IACvC,UAAU,OAAO;QACb;;WAEG;QACH,MAAM,CAAC,EAAE,0BAA0B,CAAC;KACvC;CACJ;AAED,wBAAgB,kBAAkB,CAAC,EAAE,YAAY,EAAE,EAAE,qCAAqC,GAAG,cAAc,CA4C1G"} \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/clientAuth.js b/dist/cjs/server/auth/middleware/clientAuth.js new file mode 100644 index 0000000000..2c3732ff8f --- /dev/null +++ b/dist/cjs/server/auth/middleware/clientAuth.js @@ -0,0 +1,75 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.authenticateClient = authenticateClient; +const z = __importStar(require("zod/v4")); +const errors_js_1 = require("../errors.js"); +const ClientAuthenticatedRequestSchema = z.object({ + client_id: z.string(), + client_secret: z.string().optional() +}); +function authenticateClient({ clientsStore }) { + return async (req, res, next) => { + try { + const result = ClientAuthenticatedRequestSchema.safeParse(req.body); + if (!result.success) { + throw new errors_js_1.InvalidRequestError(String(result.error)); + } + const { client_id, client_secret } = result.data; + const client = await clientsStore.getClient(client_id); + if (!client) { + throw new errors_js_1.InvalidClientError('Invalid client_id'); + } + // If client has a secret, validate it + if (client.client_secret) { + // Check if client_secret is required but not provided + if (!client_secret) { + throw new errors_js_1.InvalidClientError('Client secret is required'); + } + // Check if client_secret matches + if (client.client_secret !== client_secret) { + throw new errors_js_1.InvalidClientError('Invalid client_secret'); + } + // Check if client_secret has expired + if (client.client_secret_expires_at && client.client_secret_expires_at < Math.floor(Date.now() / 1000)) { + throw new errors_js_1.InvalidClientError('Client secret has expired'); + } + } + req.client = client; + next(); + } + catch (error) { + if (error instanceof errors_js_1.OAuthError) { + const status = error instanceof errors_js_1.ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new errors_js_1.ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }; +} +//# sourceMappingURL=clientAuth.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/clientAuth.js.map b/dist/cjs/server/auth/middleware/clientAuth.js.map new file mode 100644 index 0000000000..862ba692e8 --- /dev/null +++ b/dist/cjs/server/auth/middleware/clientAuth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"clientAuth.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/clientAuth.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,gDA4CC;AAvED,0CAA4B;AAI5B,4CAAgG;AAShG,MAAM,gCAAgC,GAAG,CAAC,CAAC,MAAM,CAAC;IAC9C,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACvC,CAAC,CAAC;AAWH,SAAgB,kBAAkB,CAAC,EAAE,YAAY,EAAyC;IACtF,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC5B,IAAI,CAAC;YACD,MAAM,MAAM,GAAG,gCAAgC,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YACpE,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;gBAClB,MAAM,IAAI,+BAAmB,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;YACxD,CAAC;YAED,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC;YACjD,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;YACvD,IAAI,CAAC,MAAM,EAAE,CAAC;gBACV,MAAM,IAAI,8BAAkB,CAAC,mBAAmB,CAAC,CAAC;YACtD,CAAC;YAED,sCAAsC;YACtC,IAAI,MAAM,CAAC,aAAa,EAAE,CAAC;gBACvB,sDAAsD;gBACtD,IAAI,CAAC,aAAa,EAAE,CAAC;oBACjB,MAAM,IAAI,8BAAkB,CAAC,2BAA2B,CAAC,CAAC;gBAC9D,CAAC;gBAED,iCAAiC;gBACjC,IAAI,MAAM,CAAC,aAAa,KAAK,aAAa,EAAE,CAAC;oBACzC,MAAM,IAAI,8BAAkB,CAAC,uBAAuB,CAAC,CAAC;gBAC1D,CAAC;gBAED,qCAAqC;gBACrC,IAAI,MAAM,CAAC,wBAAwB,IAAI,MAAM,CAAC,wBAAwB,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;oBACrG,MAAM,IAAI,8BAAkB,CAAC,2BAA2B,CAAC,CAAC;gBAC9D,CAAC;YACL,CAAC;YAED,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC;YACpB,IAAI,EAAE,CAAC;QACX,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,KAAK,YAAY,sBAAU,EAAE,CAAC;gBAC9B,MAAM,MAAM,GAAG,KAAK,YAAY,uBAAW,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;gBACxD,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,uBAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/provider.d.ts b/dist/cjs/server/auth/provider.d.ts new file mode 100644 index 0000000000..3e4eca392c --- /dev/null +++ b/dist/cjs/server/auth/provider.d.ts @@ -0,0 +1,68 @@ +import { Response } from 'express'; +import { OAuthRegisteredClientsStore } from './clients.js'; +import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../shared/auth.js'; +import { AuthInfo } from './types.js'; +export type AuthorizationParams = { + state?: string; + scopes?: string[]; + codeChallenge: string; + redirectUri: string; + resource?: URL; +}; +/** + * Implements an end-to-end OAuth server. + */ +export interface OAuthServerProvider { + /** + * A store used to read information about registered OAuth clients. + */ + get clientsStore(): OAuthRegisteredClientsStore; + /** + * Begins the authorization flow, which can either be implemented by this server itself or via redirection to a separate authorization server. + * + * This server must eventually issue a redirect with an authorization response or an error response to the given redirect URI. Per OAuth 2.1: + * - In the successful case, the redirect MUST include the `code` and `state` (if present) query parameters. + * - In the error case, the redirect MUST include the `error` query parameter, and MAY include an optional `error_description` query parameter. + */ + authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; + /** + * Returns the `codeChallenge` that was used when the indicated authorization began. + */ + challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise; + /** + * Exchanges an authorization code for an access token. + */ + exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, redirectUri?: string, resource?: URL): Promise; + /** + * Exchanges a refresh token for an access token. + */ + exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; + /** + * Verifies an access token and returns information about it. + */ + verifyAccessToken(token: string): Promise; + /** + * Revokes an access or refresh token. If unimplemented, token revocation is not supported (not recommended). + * + * If the given token is invalid or already revoked, this method should do nothing. + */ + revokeToken?(client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest): Promise; + /** + * Whether to skip local PKCE validation. + * + * If true, the server will not perform PKCE validation locally and will pass the code_verifier to the upstream server. + * + * NOTE: This should only be true if the upstream server is performing the actual PKCE validation. + */ + skipLocalPkceValidation?: boolean; +} +/** + * Slim implementation useful for token verification + */ +export interface OAuthTokenVerifier { + /** + * Verifies an access token and returns information about it. + */ + verifyAccessToken(token: string): Promise; +} +//# sourceMappingURL=provider.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/provider.d.ts.map b/dist/cjs/server/auth/provider.d.ts.map new file mode 100644 index 0000000000..d1a4bfff0b --- /dev/null +++ b/dist/cj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EAAE,QAAQ,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IAExI;;OAEG;IACH,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAEpD;;;;OAIG;IACH,WAAW,CAAC,CAAC,MAAM,EAAE,0BAA0B,EAAE,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEtG;;;;;;OAMG;IACH,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACrC;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IAC/B;;OAEG;IACH,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CACvD"} \ No newline at end of file diff --git a/dist/cjs/server/auth/provider.js b/dist/cjs/server/auth/provider.js new file mode 100644 index 0000000000..0903bb2eff --- /dev/null +++ b/dist/cjs/server/auth/provider.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=provider.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/provider.js.map b/dist/cjs/server/auth/provider.js.map new file mode 100644 index 0000000000..b968414aa9 --- /dev/null +++ b/dist/cjs/server/auth/provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../../src/server/auth/provider.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/server/auth/providers/proxyProvider.d.ts b/dist/cjs/server/auth/providers/proxyProvider.d.ts new file mode 100644 index 0000000000..ee6f350817 --- /dev/null +++ b/dist/cjs/server/auth/providers/proxyProvider.d.ts @@ -0,0 +1,49 @@ +import { Response } from 'express'; +import { OAuthRegisteredClientsStore } from '../clients.js'; +import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../../shared/auth.js'; +import { AuthInfo } from '../types.js'; +import { AuthorizationParams, OAuthServerProvider } from '../provider.js'; +import { FetchLike } from '../../../shared/transport.js'; +export type ProxyEndpoints = { + authorizationUrl: string; + tokenUrl: string; + revocationUrl?: string; + registrationUrl?: string; +}; +export type ProxyOptions = { + /** + * Individual endpoint URLs for proxying specific OAuth operations + */ + endpoints: ProxyEndpoints; + /** + * Function to verify access tokens and return auth info + */ + verifyAccessToken: (token: string) => Promise; + /** + * Function to fetch client information from the upstream server + */ + getClient: (clientId: string) => Promise; + /** + * Custom fetch implementation used for all network requests. + */ + fetch?: FetchLike; +}; +/** + * Implements an OAuth server that proxies requests to another OAuth server. + */ +export declare class ProxyOAuthServerProvider implements OAuthServerProvider { + protected readonly _endpoints: ProxyEndpoints; + protected readonly _verifyAccessToken: (token: string) => Promise; + protected readonly _getClient: (clientId: string) => Promise; + protected readonly _fetch?: FetchLike; + skipLocalPkceValidation: boolean; + revokeToken?: (client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest) => Promise; + constructor(options: ProxyOptions); + get clientsStore(): OAuthRegisteredClientsStore; + authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; + challengeForAuthorizationCode(_client: OAuthClientInformationFull, _authorizationCode: string): Promise; + exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, redirectUri?: string, resource?: URL): Promise; + exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; + verifyAccessToken(token: string): Promise; +} +//# sourceMappingURL=proxyProvider.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/providers/proxyProvider.d.ts.map b/dist/cjs/server/auth/providers/proxyProvider.d.ts.map new file mode 100644 index 0000000000..ba2efd1aab --- /dev/null +++ b/dist/cjs/server/auth/providers/proxyProvider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"proxyProvider.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/providers/proxyProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACn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/B,WAAW,CAAC,EAAE,CAAC,MAAM,EAAE,0BAA0B,EAAE,OAAO,EAAE,2BAA2B,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;gBAE9F,OAAO,EAAE,YAAY;IAsCjC,IAAI,YAAY,IAAI,2BAA2B,CAuB9C;IAEK,SAAS,CAAC,MAAM,EAAE,0BAA0B,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAoBxG,6BAA6B,CAAC,OAAO,EAAE,0BAA0B,EAAE,kBAAkB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAM/G,yBAAyB,CAC3B,MAAM,EAAE,0BAA0B,EAClC,iBAAiB,EAAE,MAAM,EACzB,YAAY,CAAC,EAAE,MAAM,EACrB,WAAW,CAAC,EAAE,MAAM,EACpB,QAAQ,CAAC,EAAE,GAAG,GACf,OAAO,CAAC,WAAW,CAAC;IAuCjB,oBAAoB,CACtB,MAAM,EAAE,0BAA0B,EAClC,YAAY,EAAE,MAAM,EACpB,MAAM,CAAC,EAAE,MAAM,EAAE,EACjB,QAAQ,CAAC,EAAE,GAAG,GACf,OAAO,CAAC,WAAW,CAAC;IAmCjB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;CAG5D"} \ No newline at end of file diff --git a/dist/cjs/server/auth/providers/proxyProvider.js b/dist/cjs/server/auth/providers/proxyProvider.js new file mode 100644 index 0000000000..51bd2a9c21 --- /dev/null +++ b/dist/cjs/server/auth/providers/proxyProvider.js @@ -0,0 +1,161 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ProxyOAuthServerProvider = void 0; +const auth_js_1 = require("../../../shared/auth.js"); +const errors_js_1 = require("../errors.js"); +/** + * Implements an OAuth server that proxies requests to another OAuth server. + */ +class ProxyOAuthServerProvider { + constructor(options) { + var _a; + this.skipLocalPkceValidation = true; + this._endpoints = options.endpoints; + this._verifyAccessToken = options.verifyAccessToken; + this._getClient = options.getClient; + this._fetch = options.fetch; + if ((_a = options.endpoints) === null || _a === void 0 ? void 0 : _a.revocationUrl) { + this.revokeToken = async (client, request) => { + var _a; + const revocationUrl = this._endpoints.revocationUrl; + if (!revocationUrl) { + throw new Error('No revocation endpoint configured'); + } + const params = new URLSearchParams(); + params.set('token', request.token); + params.set('client_id', client.client_id); + if (client.client_secret) { + params.set('client_secret', client.client_secret); + } + if (request.token_type_hint) { + params.set('token_type_hint', request.token_type_hint); + } + const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(revocationUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: params.toString() + }); + if (!response.ok) { + throw new errors_js_1.ServerError(`Token revocation failed: ${response.status}`); + } + }; + } + } + get clientsStore() { + const registrationUrl = this._endpoints.registrationUrl; + return { + getClient: this._getClient, + ...(registrationUrl && { + registerClient: async (client) => { + var _a; + const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(registrationUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(client) + }); + if (!response.ok) { + throw new errors_js_1.ServerError(`Client registration failed: ${response.status}`); + } + const data = await response.json(); + return auth_js_1.OAuthClientInformationFullSchema.parse(data); + } + }) + }; + } + async authorize(client, params, res) { + var _a; + // Start with required OAuth parameters + const targetUrl = new URL(this._endpoints.authorizationUrl); + const searchParams = new URLSearchParams({ + client_id: client.client_id, + response_type: 'code', + redirect_uri: params.redirectUri, + code_challenge: params.codeChallenge, + code_challenge_method: 'S256' + }); + // Add optional standard OAuth parameters + if (params.state) + searchParams.set('state', params.state); + if ((_a = params.scopes) === null || _a === void 0 ? void 0 : _a.length) + searchParams.set('scope', params.scopes.join(' ')); + if (params.resource) + searchParams.set('resource', params.resource.href); + targetUrl.search = searchParams.toString(); + res.redirect(targetUrl.toString()); + } + async challengeForAuthorizationCode(_client, _authorizationCode) { + // In a proxy setup, we don't store the code challenge ourselves + // Instead, we proxy the token request and let the upstream server validate it + return ''; + } + async exchangeAuthorizationCode(client, authorizationCode, codeVerifier, redirectUri, resource) { + var _a; + const params = new URLSearchParams({ + grant_type: 'authorization_code', + client_id: client.client_id, + code: authorizationCode + }); + if (client.client_secret) { + params.append('client_secret', client.client_secret); + } + if (codeVerifier) { + params.append('code_verifier', codeVerifier); + } + if (redirectUri) { + params.append('redirect_uri', redirectUri); + } + if (resource) { + params.append('resource', resource.href); + } + const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(this._endpoints.tokenUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: params.toString() + }); + if (!response.ok) { + throw new errors_js_1.ServerError(`Token exchange failed: ${response.status}`); + } + const data = await response.json(); + return auth_js_1.OAuthTokensSchema.parse(data); + } + async exchangeRefreshToken(client, refreshToken, scopes, resource) { + var _a; + const params = new URLSearchParams({ + grant_type: 'refresh_token', + client_id: client.client_id, + refresh_token: refreshToken + }); + if (client.client_secret) { + params.set('client_secret', client.client_secret); + } + if (scopes === null || scopes === void 0 ? void 0 : scopes.length) { + params.set('scope', scopes.join(' ')); + } + if (resource) { + params.set('resource', resource.href); + } + const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(this._endpoints.tokenUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: params.toString() + }); + if (!response.ok) { + throw new errors_js_1.ServerError(`Token refresh failed: ${response.status}`); + } + const data = await response.json(); + return auth_js_1.OAuthTokensSchema.parse(data); + } + async verifyAccessToken(token) { + return this._verifyAccessToken(token); + } +} +exports.ProxyOAuthServerProvider = ProxyOAuthServerProvider; +//# sourceMappingURL=proxyProvider.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/providers/proxyProvider.js.map b/dist/cjs/server/auth/providers/proxyProvider.js.map new file mode 100644 index 0000000000..dd33760a83 --- /dev/null +++ b/dist/cjs/server/auth/providers/proxyProvider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M,CAAC,GAAG,CAAC,eAAe,EAAE,MAAM,CAAC,aAAa,CAAC,CAAC;QACtD,CAAC;QAED,IAAI,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,MAAM,EAAE,CAAC;YACjB,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QAC1C,CAAC;QAED,IAAI,QAAQ,EAAE,CAAC;YACX,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;QAC1C,CAAC;QAED,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAA,IAAI,CAAC,MAAM,mCAAI,KAAK,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE;YACpE,MAAM,EAAE,MAAM;YACd,OAAO,EAAE;gBACL,cAAc,EAAE,mCAAmC;aACtD;YACD,IAAI,EAAE,MAAM,CAAC,QAAQ,EAAE;SAC1B,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACf,MAAM,IAAI,uBAAW,CAAC,yBAAyB,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;QACtE,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,OAAO,2BAAiB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACzC,CAAC;IAED,KAAK,CAAC,iBAAiB,CAAC,KAAa;QACjC,OAAO,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;CACJ;AA3LD,4DA2LC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/router.d.ts b/dist/cjs/server/auth/router.d.ts new file mode 100644 index 0000000000..43dabde7d2 --- /dev/null +++ b/dist/cjs/server/auth/router.d.ts @@ -0,0 +1,101 @@ +import express, { RequestHandler } from 'express'; +import { ClientRegistrationHandlerOptions } from './handlers/register.js'; +import { TokenHandlerOptions } from './handlers/token.js'; +import { AuthorizationHandlerOptions } from './handlers/authorize.js'; +import { RevocationHandlerOptions } from './handlers/revoke.js'; +import { OAuthServerProvider } from './provider.js'; +import { OAuthMetadata } from '../../shared/auth.js'; +export type AuthRouterOptions = { + /** + * A provider implementing the actual authorization logic for this router. + */ + provider: OAuthServerProvider; + /** + * The authorization server's issuer identifier, which is a URL that uses the "https" scheme and has no query or fragment components. + */ + issuerUrl: URL; + /** + * The base URL of the authorization server to use for the metadata endpoints. + * + * If not provided, the issuer URL will be used as the base URL. + */ + baseUrl?: URL; + /** + * An optional URL of a page containing human-readable information that developers might want or need to know when using the authorization server. + */ + serviceDocumentationUrl?: URL; + /** + * An optional list of scopes supported by this authorization server + */ + scopesSupported?: string[]; + /** + * The resource name to be displayed in protected resource metadata + */ + resourceName?: string; + /** + * The URL of the protected resource (RS) whose metadata we advertise. + * If not provided, falls back to `baseUrl` and then to `issuerUrl` (AS=RS). + */ + resourceServerUrl?: URL; + authorizationOptions?: Omit; + clientRegistrationOptions?: Omit; + revocationOptions?: Omit; + tokenOptions?: Omit; +}; +export declare const createOAuthMetadata: (options: { + provider: OAuthServerProvider; + issuerUrl: URL; + baseUrl?: URL; + serviceDocumentationUrl?: URL; + scopesSupported?: string[]; +}) => OAuthMetadata; +/** + * Installs standard MCP authorization server endpoints, including dynamic client registration and token revocation (if supported). + * Also advertises standard authorization server metadata, for easier discovery of supported configurations by clients. + * Note: if your MCP server is only a resource server and not an authorization server, use mcpAuthMetadataRouter instead. + * + * By default, rate limiting is applied to all endpoints to prevent abuse. + * + * This router MUST be installed at the application root, like so: + * + * const app = express(); + * app.use(mcpAuthRouter(...)); + */ +export declare function mcpAuthRouter(options: AuthRouterOptions): RequestHandler; +export type AuthMetadataOptions = { + /** + * OAuth Metadata as would be returned from the authorization server + * this MCP server relies on + */ + oauthMetadata: OAuthMetadata; + /** + * The url of the MCP server, for use in protected resource metadata + */ + resourceServerUrl: URL; + /** + * The url for documentation for the MCP server + */ + serviceDocumentationUrl?: URL; + /** + * An optional list of scopes supported by this MCP server + */ + scopesSupported?: string[]; + /** + * An optional resource name to display in resource metadata + */ + resourceName?: string; +}; +export declare function mcpAuthMetadataRouter(options: AuthMetadataOptions): express.Router; +/** + * Helper function to construct the OAuth 2.0 Protected Resource Metadata URL + * from a given server URL. This replaces the path with the standard metadata endpoint. + * + * @param serverUrl - The base URL of the protected resource server + * @returns The URL for the OAuth protected resource metadata endpoint + * + * @example + * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) + * // Returns: 'https://api.example.com/.well-known/oauth-protected-resource/mcp' + */ +export declare function getOAuthProtectedResourceMetadataUrl(serverUrl: URL): string; +//# sourceMappingURL=router.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/router.d.ts.map b/dist/cjs/server/auth/router.d.ts.map new file mode 100644 index 0000000000..54e90be267 --- /dev/null +++ b/dist/cjs/server/auth/router.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/router.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,EAAE,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAA6B,gCAAgC,EAAE,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAgB,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAAwB,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AAC5F,OAAO,EAAqB,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAEnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,aAAa,EAAkC,MAAM,sBAAsB,CAAC;AAErF,MAAM,MAAM,iBAAiB,GAAG;IAC5B;;OAEG;IACH,QAAQ,EAAE,mBAAmB,CAAC;IAE9B;;OAEG;IACH,SAAS,EAAE,GAAG,CAAC;IAEf;;;;OAIG;IACH,OAAO,CAAC,EAAE,GAAG,CAAC;IAEd;;OAEG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AoC,CAAC,SAAS,EAAE,GAAG,GAAG,MAAM,CAI3E"} \ No newline at end of file diff --git a/dist/cjs/server/auth/router.js b/dist/cjs/server/auth/router.js new file mode 100644 index 0000000000..66b037f65d --- /dev/null +++ b/dist/cjs/server/auth/router.js @@ -0,0 +1,125 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createOAuthMetadata = void 0; +exports.mcpAuthRouter = mcpAuthRouter; +exports.mcpAuthMetadataRouter = mcpAuthMetadataRouter; +exports.getOAuthProtectedResourceMetadataUrl = getOAuthProtectedResourceMetadataUrl; +const express_1 = __importDefault(require("express")); +const register_js_1 = require("./handlers/register.js"); +const token_js_1 = require("./handlers/token.js"); +const authorize_js_1 = require("./handlers/authorize.js"); +const revoke_js_1 = require("./handlers/revoke.js"); +const metadata_js_1 = require("./handlers/metadata.js"); +const checkIssuerUrl = (issuer) => { + // Technically RFC 8414 does not permit a localhost HTTPS exemption, but this will be necessary for ease of testing + if (issuer.protocol !== 'https:' && issuer.hostname !== 'localhost' && issuer.hostname !== '127.0.0.1') { + throw new Error('Issuer URL must be HTTPS'); + } + if (issuer.hash) { + throw new Error(`Issuer URL must not have a fragment: ${issuer}`); + } + if (issuer.search) { + throw new Error(`Issuer URL must not have a query string: ${issuer}`); + } +}; +const createOAuthMetadata = (options) => { + var _a; + const issuer = options.issuerUrl; + const baseUrl = options.baseUrl; + checkIssuerUrl(issuer); + const authorization_endpoint = '/authorize'; + const token_endpoint = '/token'; + const registration_endpoint = options.provider.clientsStore.registerClient ? '/register' : undefined; + const revocation_endpoint = options.provider.revokeToken ? '/revoke' : undefined; + const metadata = { + issuer: issuer.href, + service_documentation: (_a = options.serviceDocumentationUrl) === null || _a === void 0 ? void 0 : _a.href, + authorization_endpoint: new URL(authorization_endpoint, baseUrl || issuer).href, + response_types_supported: ['code'], + code_challenge_methods_supported: ['S256'], + token_endpoint: new URL(token_endpoint, baseUrl || issuer).href, + token_endpoint_auth_methods_supported: ['client_secret_post', 'none'], + grant_types_supported: ['authorization_code', 'refresh_token'], + scopes_supported: options.scopesSupported, + revocation_endpoint: revocation_endpoint ? new URL(revocation_endpoint, baseUrl || issuer).href : undefined, + revocation_endpoint_auth_methods_supported: revocation_endpoint ? ['client_secret_post'] : undefined, + registration_endpoint: registration_endpoint ? new URL(registration_endpoint, baseUrl || issuer).href : undefined + }; + return metadata; +}; +exports.createOAuthMetadata = createOAuthMetadata; +/** + * Installs standard MCP authorization server endpoints, including dynamic client registration and token revocation (if supported). + * Also advertises standard authorization server metadata, for easier discovery of supported configurations by clients. + * Note: if your MCP server is only a resource server and not an authorization server, use mcpAuthMetadataRouter instead. + * + * By default, rate limiting is applied to all endpoints to prevent abuse. + * + * This router MUST be installed at the application root, like so: + * + * const app = express(); + * app.use(mcpAuthRouter(...)); + */ +function mcpAuthRouter(options) { + var _a, _b; + const oauthMetadata = (0, exports.createOAuthMetadata)(options); + const router = express_1.default.Router(); + router.use(new URL(oauthMetadata.authorization_endpoint).pathname, (0, authorize_js_1.authorizationHandler)({ provider: options.provider, ...options.authorizationOptions })); + router.use(new URL(oauthMetadata.token_endpoint).pathname, (0, token_js_1.tokenHandler)({ provider: options.provider, ...options.tokenOptions })); + router.use(mcpAuthMetadataRouter({ + oauthMetadata, + // Prefer explicit RS; otherwise fall back to AS baseUrl, then to issuer (back-compat) + resourceServerUrl: (_b = (_a = options.resourceServerUrl) !== null && _a !== void 0 ? _a : options.baseUrl) !== null && _b !== void 0 ? _b : new URL(oauthMetadata.issuer), + serviceDocumentationUrl: options.serviceDocumentationUrl, + scopesSupported: options.scopesSupported, + resourceName: options.resourceName + })); + if (oauthMetadata.registration_endpoint) { + router.use(new URL(oauthMetadata.registration_endpoint).pathname, (0, register_js_1.clientRegistrationHandler)({ + clientsStore: options.provider.clientsStore, + ...options.clientRegistrationOptions + })); + } + if (oauthMetadata.revocation_endpoint) { + router.use(new URL(oauthMetadata.revocation_endpoint).pathname, (0, revoke_js_1.revocationHandler)({ provider: options.provider, ...options.revocationOptions })); + } + return router; +} +function mcpAuthMetadataRouter(options) { + var _a; + checkIssuerUrl(new URL(options.oauthMetadata.issuer)); + const router = express_1.default.Router(); + const protectedResourceMetadata = { + resource: options.resourceServerUrl.href, + authorization_servers: [options.oauthMetadata.issuer], + scopes_supported: options.scopesSupported, + resource_name: options.resourceName, + resource_documentation: (_a = options.serviceDocumentationUrl) === null || _a === void 0 ? void 0 : _a.href + }; + // Serve PRM at the path-specific URL per RFC 9728 + const rsPath = new URL(options.resourceServerUrl.href).pathname; + router.use(`/.well-known/oauth-protected-resource${rsPath === '/' ? '' : rsPath}`, (0, metadata_js_1.metadataHandler)(protectedResourceMetadata)); + // Always add this for OAuth Authorization Server metadata per RFC 8414 + router.use('/.well-known/oauth-authorization-server', (0, metadata_js_1.metadataHandler)(options.oauthMetadata)); + return router; +} +/** + * Helper function to construct the OAuth 2.0 Protected Resource Metadata URL + * from a given server URL. This replaces the path with the standard metadata endpoint. + * + * @param serverUrl - The base URL of the protected resource server + * @returns The URL for the OAuth protected resource metadata endpoint + * + * @example + * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) + * // Returns: 'https://api.example.com/.well-known/oauth-protected-resource/mcp' + */ +function getOAuthProtectedResourceMetadataUrl(serverUrl) { + const u = new URL(serverUrl.href); + const rsPath = u.pathname && u.pathname !== '/' ? u.pathname : ''; + return new URL(`/.well-known/oauth-protected-resource${rsPath}`, u).href; +} +//# sourceMappingURL=router.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/router.js.map b/dist/cjs/server/auth/router.js.map new file mode 100644 index 0000000000..3c813c7ae5 --- /dev/null +++ b/dist/cjs/server/auth/router.js.map @@ -0,0 +1 @@ +{"version":3,"file":"router.js","sourceRoot":"","sources":["../../../../src/server/auth/router.ts"],"names":[],"mappings":";;;;;;AAwHA,sCAyCC;AA8BD,sDAuBC;AAaD,oFAI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 index 0000000000..05ec8485a5 --- /dev/null +++ b/dist/cjs/server/auth/types.d.ts @@ -0,0 +1,32 @@ +/** + * Information about a validated access token, provided to request handlers. + */ +export interface AuthInfo { + /** + * The access token. + */ + token: string; + /** + * The client ID associated with this token. + */ + clientId: string; + /** + * Scopes associated with this token. + */ + scopes: string[]; + /** + * When the token expires (in seconds since epoch). + */ + expiresAt?: number; + /** + * The RFC 8707 resource server identifier for which this token is valid. + * If set, this MUST match the MCP server's resource identifier (minus hash fragment). + */ + resource?: URL; + /** + * Additional data associated with the token. + * This field should be used for any additional data that needs to be attached to the auth info. + */ + extra?: Record; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/types.d.ts.map b/dist/cjs/server/auth/types.d.ts.map new file mode 100644 index 0000000000..021e947401 --- /dev/null +++ b/dist/cjs/server/auth/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,QAAQ;IACrB;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,MAAM,EAAE,MAAM,EAAE,CAAC;IAEjB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,QAAQ,CAAC,EAAE,GAAG,CAAC;IAEf;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/types.js b/dist/cjs/server/auth/types.js new file mode 100644 index 0000000000..11e638d1ee --- /dev/null +++ b/dist/cjs/server/auth/types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/types.js.map b/dist/cjs/server/auth/types.js.map new file mode 100644 index 0000000000..0d8063dee4 --- /dev/null +++ b/dist/cjs/server/auth/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/server/auth/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/server/completable.d.ts b/dist/cjs/server/completable.d.ts new file mode 100644 index 0000000000..1b3159ac8f --- /dev/null +++ b/dist/cjs/server/completable.d.ts @@ -0,0 +1,38 @@ +import { AnySchema, SchemaInput } from './zod-compat.js'; +export declare const COMPLETABLE_SYMBOL: unique symbol; +export type CompleteCallback = (value: SchemaInput, context?: { + arguments?: Record; +}) => SchemaInput[] | Promise[]>; +export type CompletableMeta = { + complete: CompleteCallback; +}; +export type CompletableSchema = T & { + [COMPLETABLE_SYMBOL]: CompletableMeta; +}; +/** + * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. + * Works with both Zod v3 and v4 schemas. + */ +export declare function completable(schema: T, complete: CompleteCallback): CompletableSchema; +/** + * Checks if a schema is completable (has completion metadata). + */ +export declare function isCompletable(schema: unknown): schema is CompletableSchema; +/** + * Gets the completer callback from a completable schema, if it exists. + */ +export declare function getCompleter(schema: T): CompleteCallback | undefined; +/** + * Unwraps a completable schema to get the underlying schema. + * For backward compatibility with code that called `.unwrap()`. + */ +export declare function unwrapCompletable(schema: CompletableSchema): T; +export declare enum McpZodTypeKind { + Completable = "McpCompletable" +} +export interface CompletableDef { + type: T; + complete: CompleteCallback; + typeName: McpZodTypeKind.Completable; +} +//# sourceMappingURL=completable.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/completable.d.ts.map b/dist/cjs/server/completable.d.ts.map new file mode 100644 index 0000000000..83ea2f1e27 --- /dev/null +++ b/dist/cjs/server/completable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"completable.d.ts","sourceRoot":"","sources":["../../../src/server/completable.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,WAA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;AAED,MAAM,WAAW,cAAc,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS;IAC3D,IAAI,EAAE,CAAC,CAAC;IACR,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC;IAC9B,QAAQ,EAAE,cAAc,CAAC,WAAW,CAAC;CACxC"} \ No newline at end of file diff --git a/dist/cjs/server/completable.js b/dist/cjs/server/completable.js new file mode 100644 index 0000000000..cfddaeba48 --- /dev/null +++ b/dist/cjs/server/completable.js @@ -0,0 +1,48 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.McpZodTypeKind = exports.COMPLETABLE_SYMBOL = void 0; +exports.completable = completable; +exports.isCompletable = isCompletable; +exports.getCompleter = getCompleter; +exports.unwrapCompletable = unwrapCompletable; +exports.COMPLETABLE_SYMBOL = Symbol.for('mcp.completable'); +/** + * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. + * Works with both Zod v3 and v4 schemas. + */ +function completable(schema, complete) { + Object.defineProperty(schema, exports.COMPLETABLE_SYMBOL, { + value: { complete }, + enumerable: false, + writable: false, + configurable: false + }); + return schema; +} +/** + * Checks if a schema is completable (has completion metadata). + */ +function isCompletable(schema) { + return !!schema && typeof schema === 'object' && exports.COMPLETABLE_SYMBOL in schema; +} +/** + * Gets the completer callback from a completable schema, if it exists. + */ +function getCompleter(schema) { + const meta = schema[exports.COMPLETABLE_SYMBOL]; + return meta === null || meta === void 0 ? void 0 : meta.complete; +} +/** + * Unwraps a completable schema to get the underlying schema. + * For backward compatibility with code that called `.unwrap()`. + */ +function unwrapCompletable(schema) { + return schema; +} +// Legacy exports for backward compatibility +// These types are deprecated but kept for existing code +var McpZodTypeKind; +(function (McpZodTypeKind) { + McpZodTypeKind["Completable"] = "McpCompletable"; +})(McpZodTypeKind || (exports.McpZodTypeKind = McpZodTypeKind = {})); +//# sourceMappingURL=completable.js.map \ No newline at end of file diff --git a/dist/cjs/server/completable.js.map b/dist/cjs/server/completable.js.map new file mode 100644 index 0000000000..728e58bdce --- /dev/null +++ b/dist/cjs/server/completable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"completable.js","sourceRoot":"","sources":["../../../src/server/completable.ts"],"names":[],"mappings":";;;AAuBA,kCAQC;AAKD,sCAEC;AAKD,oCAGC;AAMD,8CAEC;AApDY,QAAA,kBAAkB,GAAkB,MAAM,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;AAiB/E;;;GAGG;AACH,SAAgB,WAAW,CAAsB,MAAS,EAAE,QAA6B;IACrF,MAAM,CAAC,cAAc,CAAC,MAAgB,EAAE,0BAAkB,EAAE;QACxD,KAAK,EAAE,EAAE,QAAQ,EAAwB;QACzC,UAAU,EAAE,KAAK;QACjB,QAAQ,EAAE,KAAK;QACf,YAAY,EAAE,KAAK;KACtB,CAAC,CAAC;IACH,OAAO,MAA8B,CAAC;AAC1C,CAAC;AAED;;GAEG;AACH,SAAgB,aAAa,CAAC,MAAe;IACzC,OAAO,CAAC,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,0BAAkB,IAAK,MAAiB,CAAC;AAC9F,CAAC;AAED;;GAEG;AACH,SAAgB,YAAY,CAAsB,MAAS;IACvD,MAAM,IAAI,GAAI,MAAmE,CAAC,0BAAkB,CAAC,CAAC;IACtG,OAAO,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,QAA2C,CAAC;AAC7D,CAAC;AAED;;;GAGG;AACH,SAAgB,iBAAiB,CAAsB,MAA4B;IAC/E,OAAO,MAAM,CAAC;AAClB,CAAC;AAED,4CAA4C;AAC5C,wDAAwD;AACxD,IAAY,cAEX;AAFD,WAAY,cAAc;IACtB,gDAA8B,CAAA;AAClC,CAAC,EAFW,cAAc,8BAAd,cAAc,QAEzB"} \ No newline at end of file diff --git a/dist/cjs/server/index.d.ts b/dist/cjs/server/index.d.ts new file mode 100644 index 0000000000..8aabf3c536 --- /dev/null +++ b/dist/cjs/server/index.d.ts @@ -0,0 +1,333 @@ +import { Protocol, type NotificationOptions, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; +import { type ClientCapabilities, type CreateMessageRequest, type ElicitRequestFormParams, type ElicitRequestURLParams, type ElicitResult, type Implementation, type ListRootsRequest, type LoggingMessageNotification, type Notification, type Request, type ResourceUpdatedNotification, type Result, type ServerCapabilities, type ServerNotification, type ServerRequest, type ServerResult } from '../types.js'; +import type { jsonSchemaValidator } from '../validation/types.js'; +type LegacyElicitRequestFormParams = Omit; +export type ServerOptions = ProtocolOptions & { + /** + * Capabilities to advertise as being supported by this server. + */ + capabilities?: ServerCapabilities; + /** + * Optional instructions describing how to use the server and its features. + */ + instructions?: string; + /** + * JSON Schema validator for elicitation response validation. + * + * The validator is used to validate user input returned from elicitation + * requests against the requested schema. + * + * @default AjvJsonSchemaValidator + * + * @example + * ```typescript + * // ajv (default) + * const server = new Server( + * { name: 'my-server', version: '1.0.0' }, + * { + * capabilities: {} + * jsonSchemaValidator: new AjvJsonSchemaValidator() + * } + * ); + * + * // @cfworker/json-schema + * const server = new Server( + * { name: 'my-server', version: '1.0.0' }, + * { + * capabilities: {}, + * jsonSchemaValidator: new CfWorkerJsonSchemaValidator() + * } + * ); + * ``` + */ + jsonSchemaValidator?: jsonSchemaValidator; +}; +/** + * An MCP server on top of a pluggable transport. + * + * This server will automatically respond to the initialization flow as initiated from the client. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed server + * const server = new Server({ + * name: "CustomServer", + * version: "1.0.0" + * }) + * ``` + * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. + */ +export declare class Server extends Protocol { + private _serverInfo; + private _clientCapabilities?; + private _clientVersion?; + private _capabilities; + private _instructions?; + private _jsonSchemaValidator; + /** + * Callback for when initialization has fully completed (i.e., the client has sent an `initialized` notification). + */ + oninitialized?: () => void; + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo: Implementation, options?: ServerOptions); + private _loggingLevels; + private readonly LOG_LEVEL_SEVERITY; + private isMessageIgnored; + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities: ServerCapabilities): void; + protected assertCapabilityForMethod(method: RequestT['method']): void; + protected assertNotificationCapability(method: (ServerNotification | NotificationT)['method']): void; + protected assertRequestHandlerCapability(method: string): void; + private _oninitialize; + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + */ + getClientCapabilities(): ClientCapabilities | undefined; + /** + * After initialization has completed, this will be populated with information about the client's name and version. + */ + getClientVersion(): Implementation | undefined; + private getCapabilities; + ping(): Promise<{ + _meta?: Record | undefined; + }>; + createMessage(params: CreateMessageRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + model: string; + role: "user" | "assistant"; + content: { + type: "text"; + text: string; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + [x: string]: unknown; + type: "tool_use"; + name: string; + id: string; + input: { + [x: string]: unknown; + }; + _meta?: { + [x: string]: unknown; + } | undefined; + } | { + [x: string]: unknown; + type: "tool_result"; + toolUseId: string; + content: ({ + type: "text"; + text: string; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "resource"; + resource: { + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + }; + _meta?: Record | undefined; + } | { + uri: string; + name: string; + type: "resource_link"; + description?: string | undefined; + mimeType?: string | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + })[]; + structuredContent?: { + [x: string]: unknown; + } | undefined; + isError?: boolean | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + } | ({ + type: "text"; + text: string; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + [x: string]: unknown; + type: "tool_use"; + name: string; + id: string; + input: { + [x: string]: unknown; + }; + _meta?: { + [x: string]: unknown; + } | undefined; + } | { + [x: string]: unknown; + type: "tool_result"; + toolUseId: string; + content: ({ + type: "text"; + text: string; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "resource"; + resource: { + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + }; + _meta?: Record | undefined; + } | { + uri: string; + name: string; + type: "resource_link"; + description?: string | undefined; + mimeType?: string | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + })[]; + structuredContent?: { + [x: string]: unknown; + } | undefined; + isError?: boolean | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + })[]; + _meta?: Record | undefined; + stopReason?: string | undefined; + }>; + /** + * Creates an elicitation request for the given parameters. + * @param params The parameters for the form elicitation request (explicit mode: 'form'). + * @param options Optional request options. + * @returns The result of the elicitation request. + */ + elicitInput(params: ElicitRequestFormParams, options?: RequestOptions): Promise; + /** + * Creates an elicitation request for the given parameters. + * @param params The parameters for the URL elicitation request (with url and elicitationId). + * @param options Optional request options. + * @returns The result of the elicitation request. + */ + elicitInput(params: ElicitRequestURLParams, options?: RequestOptions): Promise; + /** + * Creates an elicitation request for the given parameters. + * @deprecated Use the overloads with explicit `mode: 'form' | 'url'` instead. + * @param params The parameters for the form elicitation request (legacy signature without mode). + * @param options Optional request options. + * @returns The result of the elicitation request. + */ + elicitInput(params: LegacyElicitRequestFormParams, options?: RequestOptions): Promise; + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId: string, options?: NotificationOptions): () => Promise; + listRoots(params?: ListRootsRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + roots: { + uri: string; + name?: string | undefined; + _meta?: Record | undefined; + }[]; + _meta?: Record | undefined; + }>; + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string): Promise; + sendResourceUpdated(params: ResourceUpdatedNotification['params']): Promise; + sendResourceListChanged(): Promise; + sendToolListChanged(): Promise; + sendPromptListChanged(): Promise; +} +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/index.d.ts.map b/dist/cjs/server/index.d.ts.map new file mode 100644 index 0000000000..4b8cc1c0a0 --- /dev/null +++ b/dist/cjs/server/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAAE,KAAK,mBAAmB,EAAE,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACzI,OAAO,EACH,KAAK,kBAAkB,EACvB,KAAK,oBAAoB,EAEzB,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CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC;IAuDzG;;;;;;;OAOG;IACH,mCAAmC,CAAC,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC;IAiBxG,SAAS,CAAC,MAAM,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;IAI7E;;;;;;OAMG;IACG,kBAAkB,CAAC,MAAM,EAAE,0BAA0B,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC,EAAE,MAAM;IAQnF,mBAAmB,CAAC,MAAM,EAAE,2BAA2B,CAAC,QAAQ,CAAC;IAOjE,uBAAuB;IAMvB,mBAAmB;IAInB,qBAAqB;CAG9B"} \ No newline at end of file diff --git a/dist/cjs/server/index.js b/dist/cjs/server/index.js new file mode 100644 index 0000000000..4658ed28e8 --- /dev/null +++ b/dist/cjs/server/index.js @@ -0,0 +1,304 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Server = void 0; +const protocol_js_1 = require("../shared/protocol.js"); +const types_js_1 = require("../types.js"); +const ajv_provider_js_1 = require("../validation/ajv-provider.js"); +/** + * An MCP server on top of a pluggable transport. + * + * This server will automatically respond to the initialization flow as initiated from the client. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed server + * const server = new Server({ + * name: "CustomServer", + * version: "1.0.0" + * }) + * ``` + * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. + */ +class Server extends protocol_js_1.Protocol { + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo, options) { + var _a, _b; + super(options); + this._serverInfo = _serverInfo; + // Map log levels by session id + this._loggingLevels = new Map(); + // Map LogLevelSchema to severity index + this.LOG_LEVEL_SEVERITY = new Map(types_js_1.LoggingLevelSchema.options.map((level, index) => [level, index])); + // Is a message with the given level ignored in the log level set for the given session id? + this.isMessageIgnored = (level, sessionId) => { + const currentLevel = this._loggingLevels.get(sessionId); + return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; + }; + this._capabilities = (_a = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a !== void 0 ? _a : {}; + this._instructions = options === null || options === void 0 ? void 0 : options.instructions; + this._jsonSchemaValidator = (_b = options === null || options === void 0 ? void 0 : options.jsonSchemaValidator) !== null && _b !== void 0 ? _b : new ajv_provider_js_1.AjvJsonSchemaValidator(); + this.setRequestHandler(types_js_1.InitializeRequestSchema, request => this._oninitialize(request)); + this.setNotificationHandler(types_js_1.InitializedNotificationSchema, () => { var _a; return (_a = this.oninitialized) === null || _a === void 0 ? void 0 : _a.call(this); }); + if (this._capabilities.logging) { + this.setRequestHandler(types_js_1.SetLevelRequestSchema, async (request, extra) => { + var _a; + const transportSessionId = extra.sessionId || ((_a = extra.requestInfo) === null || _a === void 0 ? void 0 : _a.headers['mcp-session-id']) || undefined; + const { level } = request.params; + const parseResult = types_js_1.LoggingLevelSchema.safeParse(level); + if (parseResult.success) { + this._loggingLevels.set(transportSessionId, parseResult.data); + } + return {}; + }); + } + } + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) { + throw new Error('Cannot register capabilities after connecting to transport'); + } + this._capabilities = (0, protocol_js_1.mergeCapabilities)(this._capabilities, capabilities); + } + assertCapabilityForMethod(method) { + var _a, _b, _c; + switch (method) { + case 'sampling/createMessage': + if (!((_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.sampling)) { + throw new Error(`Client does not support sampling (required for ${method})`); + } + break; + case 'elicitation/create': + if (!((_b = this._clientCapabilities) === null || _b === void 0 ? void 0 : _b.elicitation)) { + throw new Error(`Client does not support elicitation (required for ${method})`); + } + break; + case 'roots/list': + if (!((_c = this._clientCapabilities) === null || _c === void 0 ? void 0 : _c.roots)) { + throw new Error(`Client does not support listing roots (required for ${method})`); + } + break; + case 'ping': + // No specific capability required for ping + break; + } + } + assertNotificationCapability(method) { + var _a, _b; + switch (method) { + case 'notifications/message': + if (!this._capabilities.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case 'notifications/resources/updated': + case 'notifications/resources/list_changed': + if (!this._capabilities.resources) { + throw new Error(`Server does not support notifying about resources (required for ${method})`); + } + break; + case 'notifications/tools/list_changed': + if (!this._capabilities.tools) { + throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); + } + break; + case 'notifications/prompts/list_changed': + if (!this._capabilities.prompts) { + throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); + } + break; + case 'notifications/elicitation/complete': + if (!((_b = (_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.elicitation) === null || _b === void 0 ? void 0 : _b.url)) { + throw new Error(`Client does not support URL elicitation (required for ${method})`); + } + break; + case 'notifications/cancelled': + // Cancellation notifications are always allowed + break; + case 'notifications/progress': + // Progress notifications are always allowed + break; + } + } + assertRequestHandlerCapability(method) { + switch (method) { + case 'completion/complete': + if (!this._capabilities.completions) { + throw new Error(`Server does not support completions (required for ${method})`); + } + break; + case 'logging/setLevel': + if (!this._capabilities.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case 'prompts/get': + case 'prompts/list': + if (!this._capabilities.prompts) { + throw new Error(`Server does not support prompts (required for ${method})`); + } + break; + case 'resources/list': + case 'resources/templates/list': + case 'resources/read': + if (!this._capabilities.resources) { + throw new Error(`Server does not support resources (required for ${method})`); + } + break; + case 'tools/call': + case 'tools/list': + if (!this._capabilities.tools) { + throw new Error(`Server does not support tools (required for ${method})`); + } + break; + case 'ping': + case 'initialize': + // No specific capability required for these methods + break; + } + } + async _oninitialize(request) { + const requestedVersion = request.params.protocolVersion; + this._clientCapabilities = request.params.capabilities; + this._clientVersion = request.params.clientInfo; + const protocolVersion = types_js_1.SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : types_js_1.LATEST_PROTOCOL_VERSION; + return { + protocolVersion, + capabilities: this.getCapabilities(), + serverInfo: this._serverInfo, + ...(this._instructions && { instructions: this._instructions }) + }; + } + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + */ + getClientCapabilities() { + return this._clientCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the client's name and version. + */ + getClientVersion() { + return this._clientVersion; + } + getCapabilities() { + return this._capabilities; + } + async ping() { + return this.request({ method: 'ping' }, types_js_1.EmptyResultSchema); + } + async createMessage(params, options) { + return this.request({ method: 'sampling/createMessage', params }, types_js_1.CreateMessageResultSchema, options); + } + // Implementation (not visible to callers) + async elicitInput(params, options) { + var _a, _b, _c, _d; + const mode = ('mode' in params ? params.mode : 'form'); + switch (mode) { + case 'url': { + if (!((_b = (_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.elicitation) === null || _b === void 0 ? void 0 : _b.url)) { + throw new Error('Client does not support url elicitation.'); + } + const urlParams = params; + return this.request({ method: 'elicitation/create', params: urlParams }, types_js_1.ElicitResultSchema, options); + } + case 'form': { + if (!((_d = (_c = this._clientCapabilities) === null || _c === void 0 ? void 0 : _c.elicitation) === null || _d === void 0 ? void 0 : _d.form)) { + throw new Error('Client does not support form elicitation.'); + } + const formParams = 'mode' in params + ? params + : { ...params, mode: 'form' }; + const result = await this.request({ method: 'elicitation/create', params: formParams }, types_js_1.ElicitResultSchema, options); + if (result.action === 'accept' && result.content && formParams.requestedSchema) { + try { + const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); + const validationResult = validator(result.content); + if (!validationResult.valid) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); + } + } + catch (error) { + if (error instanceof types_js_1.McpError) { + throw error; + } + throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); + } + } + return result; + } + } + } + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId, options) { + var _a, _b; + if (!((_b = (_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.elicitation) === null || _b === void 0 ? void 0 : _b.url)) { + throw new Error('Client does not support URL elicitation (required for notifications/elicitation/complete)'); + } + return () => this.notification({ + method: 'notifications/elicitation/complete', + params: { + elicitationId + } + }, options); + } + async listRoots(params, options) { + return this.request({ method: 'roots/list', params }, types_js_1.ListRootsResultSchema, options); + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + async sendLoggingMessage(params, sessionId) { + if (this._capabilities.logging) { + if (!this.isMessageIgnored(params.level, sessionId)) { + return this.notification({ method: 'notifications/message', params }); + } + } + } + async sendResourceUpdated(params) { + return this.notification({ + method: 'notifications/resources/updated', + params + }); + } + async sendResourceListChanged() { + return this.notification({ + method: 'notifications/resources/list_changed' + }); + } + async sendToolListChanged() { + return this.notification({ method: 'notifications/tools/list_changed' }); + } + async sendPromptListChanged() { + return this.notification({ method: 'notifications/prompts/list_changed' }); + } +} +exports.Server = Server; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/cjs/server/index.js.map b/dist/cjs/server/index.js.map new file mode 100644 index 0000000000..edfc221a28 --- /dev/null +++ b/dist/cjs/server/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot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AAC;IAED,KAAK,CAAC,SAAS,CAAC,MAAmC,EAAE,OAAwB;QACzE,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,EAAE,gCAAqB,EAAE,OAAO,CAAC,CAAC;IAC1F,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,kBAAkB,CAAC,MAA4C,EAAE,SAAkB;QACrF,IAAI,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,CAAC;YAC7B,IAAI,CAAC,IAAI,CAAC,gBAAgB,CAAC,MAAM,CAAC,KAAK,EAAE,SAAS,CAAC,EAAE,CAAC;gBAClD,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,uBAAuB,EAAE,MAAM,EAAE,CAAC,CAAC;YAC1E,CAAC;QACL,CAAC;IACL,CAAC;IAED,KAAK,CAAC,mBAAmB,CAAC,MAA6C;QACnE,OAAO,IAAI,CAAC,YAAY,CAAC;YACrB,MAAM,EAAE,iCAAiC;YACzC,MAAM;SACT,CAAC,CAAC;IACP,CAAC;IAED,KAAK,CAAC,uBAAuB;QACzB,OAAO,IAAI,CAAC,YAAY,CAAC;YACrB,MAAM,EAAE,sCAAsC;SACjD,CAAC,CAAC;IACP,CAAC;IAED,KAAK,CAAC,mBAAmB;QACrB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,kCAAkC,EAAE,CAAC,CAAC;IAC7E,CAAC;IAED,KAAK,CAAC,qBAAqB;QACvB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,oCAAoC,EAAE,CAAC,CAAC;IAC/E,CAAC;CACJ;AA3WD,wBA2WC"} \ No newline at end of file diff --git a/dist/cjs/server/mcp.d.ts b/dist/cjs/server/mcp.d.ts new file mode 100644 index 0000000000..c0294b5698 --- /dev/null +++ b/dist/cjs/server/mcp.d.ts @@ -0,0 +1,332 @@ +import { Server, ServerOptions } from './index.js'; +import { AnySchema, AnyObjectSchema, ZodRawShapeCompat, SchemaOutput, ShapeOutput } from './zod-compat.js'; +import { Implementation, CallToolResult, Resource, ListResourcesResult, GetPromptResult, ReadResourceResult, ServerRequest, ServerNotification, ToolAnnotations, SecurityScheme, LoggingMessageNotification } from '../types.js'; +import { UriTemplate, Variables } from '../shared/uriTemplate.js'; +import { RequestHandlerExtra } from '../shared/protocol.js'; +import { Transport } from '../shared/transport.js'; +/** + * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. + * For advanced usage (like sending notifications or setting custom request handlers), use the underlying + * Server instance available via the `server` property. + */ +export declare class McpServer { + /** + * The underlying Server instance, useful for advanced operations like sending notifications. + */ + readonly server: Server; + private _registeredResources; + private _registeredResourceTemplates; + private _registeredTools; + private _registeredPrompts; + constructor(serverInfo: Implementation, options?: ServerOptions); + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + connect(transport: Transport): Promise; + /** + * Closes the connection. + */ + close(): Promise; + private _toolHandlersInitialized; + private setToolRequestHandlers; + /** + * Creates a tool error result. + * + * @param errorMessage - The error message. + * @returns The tool error result. + */ + private createToolError; + private _completionHandlerInitialized; + private setCompletionRequestHandler; + private handlePromptCompletion; + private handleResourceCompletion; + private _resourceHandlersInitialized; + private setResourceRequestHandlers; + private _promptHandlersInitialized; + private setPromptRequestHandlers; + /** + * Registers a resource `name` at a fixed URI, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, uri: string, readCallback: ReadResourceCallback): RegisteredResource; + /** + * Registers a resource `name` at a fixed URI with metadata, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, uri: string, metadata: ResourceMetadata, readCallback: ReadResourceCallback): RegisteredResource; + /** + * Registers a resource `name` with a template pattern, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, template: ResourceTemplate, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; + /** + * Registers a resource `name` with a template pattern and metadata, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, template: ResourceTemplate, metadata: ResourceMetadata, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; + /** + * Registers a resource with a config object and callback. + * For static resources, use a URI string. For dynamic resources, use a ResourceTemplate. + */ + registerResource(name: string, uriOrTemplate: string, config: ResourceMetadata, readCallback: ReadResourceCallback): RegisteredResource; + registerResource(name: string, uriOrTemplate: ResourceTemplate, config: ResourceMetadata, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; + private _createRegisteredResource; + private _createRegisteredResourceTemplate; + private _createRegisteredPrompt; + private _createRegisteredTool; + /** + * Registers a zero-argument tool `name`, which will run the given function when the client calls it. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, cb: ToolCallback): RegisteredTool; + /** + * Registers a zero-argument tool `name` (with a description) which will run the given function when the client calls it. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, description: string, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool taking either a parameter schema for validation or annotations for additional metadata. + * This unified overload handles both `tool(name, paramsSchema, cb)` and `tool(name, annotations, cb)` cases. + * + * Note: We use a union type for the second parameter because TypeScript cannot reliably disambiguate + * between ToolAnnotations and ZodRawShape during overload resolution, as both are plain object types. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, paramsSchemaOrAnnotations: Args | ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool `name` (with a description) taking either parameter schema or annotations. + * This unified overload handles both `tool(name, description, paramsSchema, cb)` and + * `tool(name, description, annotations, cb)` cases. + * + * Note: We use a union type for the third parameter because TypeScript cannot reliably disambiguate + * between ToolAnnotations and ZodRawShape during overload resolution, as both are plain object types. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, description: string, paramsSchemaOrAnnotations: Args | ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool with both parameter schema and annotations. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, paramsSchema: Args, annotations: ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool with description, parameter schema, and annotations. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, description: string, paramsSchema: Args, annotations: ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool with a config object and callback. + */ + registerTool(name: string, config: { + title?: string; + description?: string; + inputSchema?: InputArgs; + outputSchema?: OutputArgs; + annotations?: ToolAnnotations; + securitySchemes?: SecurityScheme[]; + _meta?: Record; + }, cb: ToolCallback): RegisteredTool; + /** + * Registers a zero-argument prompt `name`, which will run the given function when the client calls it. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a zero-argument prompt `name` (with a description) which will run the given function when the client calls it. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, description: string, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a prompt `name` accepting the given arguments, which must be an object containing named properties associated with Zod schemas. When the client calls it, the function will be run with the parsed and validated arguments. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, argsSchema: Args, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a prompt `name` (with a description) accepting the given arguments, which must be an object containing named properties associated with Zod schemas. When the client calls it, the function will be run with the parsed and validated arguments. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, description: string, argsSchema: Args, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a prompt with a config object and callback. + */ + registerPrompt(name: string, config: { + title?: string; + description?: string; + argsSchema?: Args; + }, cb: PromptCallback): RegisteredPrompt; + /** + * Checks if the server is connected to a transport. + * @returns True if the server is connected + */ + isConnected(): boolean; + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string): Promise; + /** + * Sends a resource list changed event to the client, if connected. + */ + sendResourceListChanged(): void; + /** + * Sends a tool list changed event to the client, if connected. + */ + sendToolListChanged(): void; + /** + * Sends a prompt list changed event to the client, if connected. + */ + sendPromptListChanged(): void; +} +/** + * A callback to complete one variable within a resource template's URI template. + */ +export type CompleteResourceTemplateCallback = (value: string, context?: { + arguments?: Record; +}) => string[] | Promise; +/** + * A resource template combines a URI pattern with optional functionality to enumerate + * all resources matching that pattern. + */ +export declare class ResourceTemplate { + private _callbacks; + private _uriTemplate; + constructor(uriTemplate: string | UriTemplate, _callbacks: { + /** + * A callback to list all resources matching this template. This is required to specified, even if `undefined`, to avoid accidentally forgetting resource listing. + */ + list: ListResourcesCallback | undefined; + /** + * An optional callback to autocomplete variables within the URI template. Useful for clients and users to discover possible values. + */ + complete?: { + [variable: string]: CompleteResourceTemplateCallback; + }; + }); + /** + * Gets the URI template pattern. + */ + get uriTemplate(): UriTemplate; + /** + * Gets the list callback, if one was provided. + */ + get listCallback(): ListResourcesCallback | undefined; + /** + * Gets the callback for completing a specific URI template variable, if one was provided. + */ + completeCallback(variable: string): CompleteResourceTemplateCallback | undefined; +} +/** + * Callback for a tool handler registered with Server.tool(). + * + * Parameters will include tool arguments, if applicable, as well as other request handler context. + * + * The callback should return: + * - `structuredContent` if the tool has an outputSchema defined + * - `content` if the tool does not have an outputSchema + * - Both fields are optional but typically one should be provided + */ +export type ToolCallback = Args extends ZodRawShapeCompat ? (args: ShapeOutput, extra: RequestHandlerExtra) => CallToolResult | Promise : Args extends AnySchema ? (args: SchemaOutput, extra: RequestHandlerExtra) => CallToolResult | Promise : (extra: RequestHandlerExtra) => CallToolResult | Promise; +export type RegisteredTool = { + title?: string; + description?: string; + inputSchema?: AnySchema; + outputSchema?: AnySchema; + annotations?: ToolAnnotations; + securitySchemes?: SecurityScheme[]; + _meta?: Record; + callback: ToolCallback; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string | null; + title?: string; + description?: string; + paramsSchema?: InputArgs; + outputSchema?: OutputArgs; + annotations?: ToolAnnotations; + securitySchemes?: SecurityScheme[]; + _meta?: Record; + callback?: ToolCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +/** + * Additional, optional information for annotating a resource. + */ +export type ResourceMetadata = Omit; +/** + * Callback to list all resources matching a given template. + */ +export type ListResourcesCallback = (extra: RequestHandlerExtra) => ListResourcesResult | Promise; +/** + * Callback to read a resource at a given URI. + */ +export type ReadResourceCallback = (uri: URL, extra: RequestHandlerExtra) => ReadResourceResult | Promise; +export type RegisteredResource = { + name: string; + title?: string; + metadata?: ResourceMetadata; + readCallback: ReadResourceCallback; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string; + title?: string; + uri?: string | null; + metadata?: ResourceMetadata; + callback?: ReadResourceCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +/** + * Callback to read a resource at a given URI, following a filled-in URI template. + */ +export type ReadResourceTemplateCallback = (uri: URL, variables: Variables, extra: RequestHandlerExtra) => ReadResourceResult | Promise; +export type RegisteredResourceTemplate = { + resourceTemplate: ResourceTemplate; + title?: string; + metadata?: ResourceMetadata; + readCallback: ReadResourceTemplateCallback; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string | null; + title?: string; + template?: ResourceTemplate; + metadata?: ResourceMetadata; + callback?: ReadResourceTemplateCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +type PromptArgsRawShape = ZodRawShapeCompat; +export type PromptCallback = Args extends PromptArgsRawShape ? (args: ShapeOutput, extra: RequestHandlerExtra) => GetPromptResult | Promise : (extra: RequestHandlerExtra) => GetPromptResult | Promise; +export type RegisteredPrompt = { + title?: string; + description?: string; + argsSchema?: AnyObjectSchema; + callback: PromptCallback; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string | null; + title?: string; + description?: string; + argsSchema?: Args; + callback?: PromptCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +export {}; +//# sourceMappingURL=mcp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/mcp.d.ts.map b/dist/cjs/server/mcp.d.ts.map new file mode 100644 index 0000000000..9ed3a0fd27 --- /dev/null +++ b/dist/cjs/server/mcp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../../../src/server/mcp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACH,SAAS,EACT,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,WAAW,EASd,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EACH,cAAc,EAGd,cAAc,EAOd,QAAQ,EACR,mBAAmB,EAYnB,eAAe,EACf,kBAAkB,EAClB,aAAa,EACb,kBAAkB,EAClB,eAAe,EACf,cAAc,EACd,0BAA0B,EAK7B,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAGnD;;;;GAIG;AACH,qBAAa,SAAS;IAClB;;OAEG;IACH,SAAgB,MAAM,EAAE,MAAM,CAAC;IAE/B,OAAO,CAAC,oBAAoB,CAA6C;IACzE,OAAO,CAAC,4BAA4B,CAE7B;IACP,OAAO,CAAC,gBAAgB,CAA0C;IAClE,OAAO,CAAC,kBAAkB,CAA4C;gBAE1D,UAAU,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE,aAAa;IAI/D;;;;OAIG;IACG,OAAO,CAAC,SAAS,EAAE,SAAS,GAAG,OAAO,CAAC,IAAI,CAAC;IAIlD;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B,OAAO,CAAC,wBAAwB,CAAS;IAEzC,OAAO,CAAC,sBAAsB;IA8H9B;;;;;OAKG;IACH,OAAO,CAAC,eAAe;IAYvB,OAAO,CAAC,6BAA6B,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,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,UAAU,CAAC,EAAE,IAAI,CAAC;QAClB,QAAQ,CAAC,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC;QAChC,OAAO,CAAC,EAAE,OAAO,CAAC;KACrB,GAAG,IAAI,CAAC;IACT,MAAM,IAAI,IAAI,CAAC;CAClB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/mcp.js b/dist/cjs/server/mcp.js new file mode 100644 index 0000000000..06cc0b883c --- /dev/null +++ b/dist/cjs/server/mcp.js @@ -0,0 +1,758 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ResourceTemplate = exports.McpServer = void 0; +const index_js_1 = require("./index.js"); +const zod_compat_js_1 = require("./zod-compat.js"); +const zod_json_schema_compat_js_1 = require("./zod-json-schema-compat.js"); +const types_js_1 = require("../types.js"); +const completable_js_1 = require("./completable.js"); +const uriTemplate_js_1 = require("../shared/uriTemplate.js"); +const toolNameValidation_js_1 = require("../shared/toolNameValidation.js"); +/** + * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. + * For advanced usage (like sending notifications or setting custom request handlers), use the underlying + * Server instance available via the `server` property. + */ +class McpServer { + constructor(serverInfo, options) { + this._registeredResources = {}; + this._registeredResourceTemplates = {}; + this._registeredTools = {}; + this._registeredPrompts = {}; + this._toolHandlersInitialized = false; + this._completionHandlerInitialized = false; + this._resourceHandlersInitialized = false; + this._promptHandlersInitialized = false; + this.server = new index_js_1.Server(serverInfo, options); + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + async connect(transport) { + return await this.server.connect(transport); + } + /** + * Closes the connection. + */ + async close() { + await this.server.close(); + } + setToolRequestHandlers() { + if (this._toolHandlersInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListToolsRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.CallToolRequestSchema)); + this.server.registerCapabilities({ + tools: { + listChanged: true + } + }); + this.server.setRequestHandler(types_js_1.ListToolsRequestSchema, () => { + // eslint-disable-next-line no-console + console.log('Tool list handler called'); + return { + tools: Object.entries(this._registeredTools) + .filter(([, tool]) => tool.enabled) + .map(([name, tool]) => { + const toolDefinition = { + name, + title: tool.title, + description: tool.description, + inputSchema: (() => { + const obj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.inputSchema); + return obj + ? (0, zod_json_schema_compat_js_1.toJsonSchemaCompat)(obj, { + strictUnions: true, + pipeStrategy: 'input' + }) + : EMPTY_OBJECT_JSON_SCHEMA; + })(), + annotations: tool.annotations, + securitySchemes: tool.securitySchemes, + _meta: tool._meta + }; + if (tool.outputSchema) { + const obj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.outputSchema); + if (obj) { + toolDefinition.outputSchema = (0, zod_json_schema_compat_js_1.toJsonSchemaCompat)(obj, { + strictUnions: true, + pipeStrategy: 'output' + }); + } + } + return toolDefinition; + }) + }; + }); + this.server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request, extra) => { + const tool = this._registeredTools[request.params.name]; + let result; + try { + if (!tool) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Tool ${request.params.name} not found`); + } + if (!tool.enabled) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); + } + if (tool.inputSchema) { + const cb = tool.callback; + // Try to normalize to object schema first (for raw shapes and object schemas) + // If that fails, use the schema directly (for union/intersection/etc) + const inputObj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.inputSchema); + const schemaToParse = inputObj !== null && inputObj !== void 0 ? inputObj : tool.inputSchema; + const parseResult = await (0, zod_compat_js_1.safeParseAsync)(schemaToParse, request.params.arguments); + if (!parseResult.success) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${request.params.name}: ${(0, zod_compat_js_1.getParseErrorMessage)(parseResult.error)}`); + } + const args = parseResult.data; + result = await Promise.resolve(cb(args, extra)); + } + else { + const cb = tool.callback; + result = await Promise.resolve(cb(extra)); + } + if (tool.outputSchema && !result.isError) { + if (!result.structuredContent) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Output validation error: Tool ${request.params.name} has an output schema but no structured content was provided`); + } + // if the tool has an output schema, validate structured content + const outputObj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.outputSchema); + const parseResult = await (0, zod_compat_js_1.safeParseAsync)(outputObj, result.structuredContent); + if (!parseResult.success) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${request.params.name}: ${(0, zod_compat_js_1.getParseErrorMessage)(parseResult.error)}`); + } + } + } + catch (error) { + if (error instanceof types_js_1.McpError) { + if (error.code === types_js_1.ErrorCode.UrlElicitationRequired) { + throw error; // Return the error to the caller without wrapping in CallToolResult + } + } + return this.createToolError(error instanceof Error ? error.message : String(error)); + } + return result; + }); + this._toolHandlersInitialized = true; + } + /** + * Creates a tool error result. + * + * @param errorMessage - The error message. + * @returns The tool error result. + */ + createToolError(errorMessage) { + return { + content: [ + { + type: 'text', + text: errorMessage + } + ], + isError: true + }; + } + setCompletionRequestHandler() { + if (this._completionHandlerInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.CompleteRequestSchema)); + this.server.registerCapabilities({ + completions: {} + }); + this.server.setRequestHandler(types_js_1.CompleteRequestSchema, async (request) => { + switch (request.params.ref.type) { + case 'ref/prompt': + (0, types_js_1.assertCompleteRequestPrompt)(request); + return this.handlePromptCompletion(request, request.params.ref); + case 'ref/resource': + (0, types_js_1.assertCompleteRequestResourceTemplate)(request); + return this.handleResourceCompletion(request, request.params.ref); + default: + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); + } + }); + this._completionHandlerInitialized = true; + } + async handlePromptCompletion(request, ref) { + const prompt = this._registeredPrompts[ref.name]; + if (!prompt) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${ref.name} not found`); + } + if (!prompt.enabled) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); + } + if (!prompt.argsSchema) { + return EMPTY_COMPLETION_RESULT; + } + const promptShape = (0, zod_compat_js_1.getObjectShape)(prompt.argsSchema); + const field = promptShape === null || promptShape === void 0 ? void 0 : promptShape[request.params.argument.name]; + if (!(0, completable_js_1.isCompletable)(field)) { + return EMPTY_COMPLETION_RESULT; + } + const completer = (0, completable_js_1.getCompleter)(field); + if (!completer) { + return EMPTY_COMPLETION_RESULT; + } + const suggestions = await completer(request.params.argument.value, request.params.context); + return createCompletionResult(suggestions); + } + async handleResourceCompletion(request, ref) { + const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri); + if (!template) { + if (this._registeredResources[ref.uri]) { + // Attempting to autocomplete a fixed resource URI is not an error in the spec (but probably should be). + return EMPTY_COMPLETION_RESULT; + } + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); + } + const completer = template.resourceTemplate.completeCallback(request.params.argument.name); + if (!completer) { + return EMPTY_COMPLETION_RESULT; + } + const suggestions = await completer(request.params.argument.value, request.params.context); + return createCompletionResult(suggestions); + } + setResourceRequestHandlers() { + if (this._resourceHandlersInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListResourcesRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListResourceTemplatesRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ReadResourceRequestSchema)); + this.server.registerCapabilities({ + resources: { + listChanged: true + } + }); + this.server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async (request, extra) => { + const resources = Object.entries(this._registeredResources) + .filter(([_, resource]) => resource.enabled) + .map(([uri, resource]) => ({ + uri, + name: resource.name, + ...resource.metadata + })); + const templateResources = []; + for (const template of Object.values(this._registeredResourceTemplates)) { + if (!template.resourceTemplate.listCallback) { + continue; + } + const result = await template.resourceTemplate.listCallback(extra); + for (const resource of result.resources) { + templateResources.push({ + ...template.metadata, + // the defined resource metadata should override the template metadata if present + ...resource + }); + } + } + return { resources: [...resources, ...templateResources] }; + }); + this.server.setRequestHandler(types_js_1.ListResourceTemplatesRequestSchema, async () => { + const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ + name, + uriTemplate: template.resourceTemplate.uriTemplate.toString(), + ...template.metadata + })); + return { resourceTemplates }; + }); + this.server.setRequestHandler(types_js_1.ReadResourceRequestSchema, async (request, extra) => { + const uri = new URL(request.params.uri); + // First check for exact resource match + const resource = this._registeredResources[uri.toString()]; + if (resource) { + if (!resource.enabled) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Resource ${uri} disabled`); + } + return resource.readCallback(uri, extra); + } + // Then check templates + for (const template of Object.values(this._registeredResourceTemplates)) { + const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); + if (variables) { + return template.readCallback(uri, variables, extra); + } + } + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Resource ${uri} not found`); + }); + this.setCompletionRequestHandler(); + this._resourceHandlersInitialized = true; + } + setPromptRequestHandlers() { + if (this._promptHandlersInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListPromptsRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.GetPromptRequestSchema)); + this.server.registerCapabilities({ + prompts: { + listChanged: true + } + }); + this.server.setRequestHandler(types_js_1.ListPromptsRequestSchema, () => ({ + prompts: Object.entries(this._registeredPrompts) + .filter(([, prompt]) => prompt.enabled) + .map(([name, prompt]) => { + return { + name, + title: prompt.title, + description: prompt.description, + arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined + }; + }) + })); + this.server.setRequestHandler(types_js_1.GetPromptRequestSchema, async (request, extra) => { + const prompt = this._registeredPrompts[request.params.name]; + if (!prompt) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); + } + if (!prompt.enabled) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); + } + if (prompt.argsSchema) { + const argsObj = (0, zod_compat_js_1.normalizeObjectSchema)(prompt.argsSchema); + const parseResult = await (0, zod_compat_js_1.safeParseAsync)(argsObj, request.params.arguments); + if (!parseResult.success) { + throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${(0, zod_compat_js_1.getParseErrorMessage)(parseResult.error)}`); + } + const args = parseResult.data; + const cb = prompt.callback; + return await Promise.resolve(cb(args, extra)); + } + else { + const cb = prompt.callback; + return await Promise.resolve(cb(extra)); + } + }); + this.setCompletionRequestHandler(); + this._promptHandlersInitialized = true; + } + resource(name, uriOrTemplate, ...rest) { + let metadata; + if (typeof rest[0] === 'object') { + metadata = rest.shift(); + } + const readCallback = rest[0]; + if (typeof uriOrTemplate === 'string') { + if (this._registeredResources[uriOrTemplate]) { + throw new Error(`Resource ${uriOrTemplate} is already registered`); + } + const registeredResource = this._createRegisteredResource(name, undefined, uriOrTemplate, metadata, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } + else { + if (this._registeredResourceTemplates[name]) { + throw new Error(`Resource template ${name} is already registered`); + } + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, undefined, uriOrTemplate, metadata, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + registerResource(name, uriOrTemplate, config, readCallback) { + if (typeof uriOrTemplate === 'string') { + if (this._registeredResources[uriOrTemplate]) { + throw new Error(`Resource ${uriOrTemplate} is already registered`); + } + const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } + else { + if (this._registeredResourceTemplates[name]) { + throw new Error(`Resource template ${name} is already registered`); + } + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + _createRegisteredResource(name, title, uri, metadata, readCallback) { + const registeredResource = { + name, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResource.update({ enabled: false }), + enable: () => registeredResource.update({ enabled: true }), + remove: () => registeredResource.update({ uri: null }), + update: updates => { + if (typeof updates.uri !== 'undefined' && updates.uri !== uri) { + delete this._registeredResources[uri]; + if (updates.uri) + this._registeredResources[updates.uri] = registeredResource; + } + if (typeof updates.name !== 'undefined') + registeredResource.name = updates.name; + if (typeof updates.title !== 'undefined') + registeredResource.title = updates.title; + if (typeof updates.metadata !== 'undefined') + registeredResource.metadata = updates.metadata; + if (typeof updates.callback !== 'undefined') + registeredResource.readCallback = updates.callback; + if (typeof updates.enabled !== 'undefined') + registeredResource.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResources[uri] = registeredResource; + return registeredResource; + } + _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { + const registeredResourceTemplate = { + resourceTemplate: template, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResourceTemplate.update({ enabled: false }), + enable: () => registeredResourceTemplate.update({ enabled: true }), + remove: () => registeredResourceTemplate.update({ name: null }), + update: updates => { + if (typeof updates.name !== 'undefined' && updates.name !== name) { + delete this._registeredResourceTemplates[name]; + if (updates.name) + this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; + } + if (typeof updates.title !== 'undefined') + registeredResourceTemplate.title = updates.title; + if (typeof updates.template !== 'undefined') + registeredResourceTemplate.resourceTemplate = updates.template; + if (typeof updates.metadata !== 'undefined') + registeredResourceTemplate.metadata = updates.metadata; + if (typeof updates.callback !== 'undefined') + registeredResourceTemplate.readCallback = updates.callback; + if (typeof updates.enabled !== 'undefined') + registeredResourceTemplate.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResourceTemplates[name] = registeredResourceTemplate; + return registeredResourceTemplate; + } + _createRegisteredPrompt(name, title, description, argsSchema, callback) { + const registeredPrompt = { + title, + description, + argsSchema: argsSchema === undefined ? undefined : (0, zod_compat_js_1.objectFromShape)(argsSchema), + callback, + enabled: true, + disable: () => registeredPrompt.update({ enabled: false }), + enable: () => registeredPrompt.update({ enabled: true }), + remove: () => registeredPrompt.update({ name: null }), + update: updates => { + if (typeof updates.name !== 'undefined' && updates.name !== name) { + delete this._registeredPrompts[name]; + if (updates.name) + this._registeredPrompts[updates.name] = registeredPrompt; + } + if (typeof updates.title !== 'undefined') + registeredPrompt.title = updates.title; + if (typeof updates.description !== 'undefined') + registeredPrompt.description = updates.description; + if (typeof updates.argsSchema !== 'undefined') + registeredPrompt.argsSchema = (0, zod_compat_js_1.objectFromShape)(updates.argsSchema); + if (typeof updates.callback !== 'undefined') + registeredPrompt.callback = updates.callback; + if (typeof updates.enabled !== 'undefined') + registeredPrompt.enabled = updates.enabled; + this.sendPromptListChanged(); + } + }; + this._registeredPrompts[name] = registeredPrompt; + return registeredPrompt; + } + _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, securitySchemes, _meta, callback) { + // Validate tool name according to SEP specification + (0, toolNameValidation_js_1.validateAndWarnToolName)(name); + const registeredTool = { + title, + description, + inputSchema: getZodSchemaObject(inputSchema), + outputSchema: getZodSchemaObject(outputSchema), + annotations, + securitySchemes, + _meta, + callback, + enabled: true, + disable: () => registeredTool.update({ enabled: false }), + enable: () => registeredTool.update({ enabled: true }), + remove: () => registeredTool.update({ name: null }), + update: updates => { + if (typeof updates.name !== 'undefined' && updates.name !== name) { + if (typeof updates.name === 'string') { + (0, toolNameValidation_js_1.validateAndWarnToolName)(updates.name); + } + delete this._registeredTools[name]; + if (updates.name) + this._registeredTools[updates.name] = registeredTool; + } + if (typeof updates.title !== 'undefined') + registeredTool.title = updates.title; + if (typeof updates.description !== 'undefined') + registeredTool.description = updates.description; + if (typeof updates.paramsSchema !== 'undefined') + registeredTool.inputSchema = (0, zod_compat_js_1.objectFromShape)(updates.paramsSchema); + if (typeof updates.callback !== 'undefined') + registeredTool.callback = updates.callback; + if (typeof updates.annotations !== 'undefined') + registeredTool.annotations = updates.annotations; + if (typeof updates.securitySchemes !== 'undefined') + registeredTool.securitySchemes = updates.securitySchemes; + if (typeof updates._meta !== 'undefined') + registeredTool._meta = updates._meta; + if (typeof updates.enabled !== 'undefined') + registeredTool.enabled = updates.enabled; + this.sendToolListChanged(); + } + }; + this._registeredTools[name] = registeredTool; + this.setToolRequestHandlers(); + this.sendToolListChanged(); + return registeredTool; + } + /** + * tool() implementation. Parses arguments passed to overrides defined above. + */ + tool(name, ...rest) { + if (this._registeredTools[name]) { + throw new Error(`Tool ${name} is already registered`); + } + let description; + let inputSchema; + let outputSchema; + let annotations; + // Tool properties are passed as separate arguments, with omissions allowed. + // Support for this style is frozen as of protocol version 2025-03-26. Future additions + // to tool definition should *NOT* be added. + if (typeof rest[0] === 'string') { + description = rest.shift(); + } + // Handle the different overload combinations + if (rest.length > 1) { + // We have at least one more arg before the callback + const firstArg = rest[0]; + if (isZodRawShape(firstArg)) { + // We have a params schema as the first arg + inputSchema = rest.shift(); + // Check if the next arg is potentially annotations + if (rest.length > 1 && typeof rest[0] === 'object' && rest[0] !== null && !isZodRawShape(rest[0])) { + // Case: tool(name, paramsSchema, annotations, cb) + // Or: tool(name, description, paramsSchema, annotations, cb) + annotations = rest.shift(); + } + } + else if (typeof firstArg === 'object' && firstArg !== null) { + // Not a ZodRawShape, so must be annotations in this position + // Case: tool(name, annotations, cb) + // Or: tool(name, description, annotations, cb) + annotations = rest.shift(); + } + } + const callback = rest[0]; + return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, undefined, undefined, callback); + } + /** + * Registers a tool with a config object and callback. + */ + registerTool(name, config, cb) { + if (this._registeredTools[name]) { + throw new Error(`Tool ${name} is already registered`); + } + console.log('registerTool'); + const { title, description, inputSchema, outputSchema, annotations, securitySchemes, _meta } = config; + return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, securitySchemes, _meta, cb); + } + prompt(name, ...rest) { + if (this._registeredPrompts[name]) { + throw new Error(`Prompt ${name} is already registered`); + } + let description; + if (typeof rest[0] === 'string') { + description = rest.shift(); + } + let argsSchema; + if (rest.length > 1) { + argsSchema = rest.shift(); + } + const cb = rest[0]; + const registeredPrompt = this._createRegisteredPrompt(name, undefined, description, argsSchema, cb); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } + /** + * Registers a prompt with a config object and callback. + */ + registerPrompt(name, config, cb) { + if (this._registeredPrompts[name]) { + throw new Error(`Prompt ${name} is already registered`); + } + const { title, description, argsSchema } = config; + const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } + /** + * Checks if the server is connected to a transport. + * @returns True if the server is connected + */ + isConnected() { + return this.server.transport !== undefined; + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + async sendLoggingMessage(params, sessionId) { + return this.server.sendLoggingMessage(params, sessionId); + } + /** + * Sends a resource list changed event to the client, if connected. + */ + sendResourceListChanged() { + if (this.isConnected()) { + this.server.sendResourceListChanged(); + } + } + /** + * Sends a tool list changed event to the client, if connected. + */ + sendToolListChanged() { + if (this.isConnected()) { + this.server.sendToolListChanged(); + } + } + /** + * Sends a prompt list changed event to the client, if connected. + */ + sendPromptListChanged() { + if (this.isConnected()) { + this.server.sendPromptListChanged(); + } + } +} +exports.McpServer = McpServer; +/** + * A resource template combines a URI pattern with optional functionality to enumerate + * all resources matching that pattern. + */ +class ResourceTemplate { + constructor(uriTemplate, _callbacks) { + this._callbacks = _callbacks; + this._uriTemplate = typeof uriTemplate === 'string' ? new uriTemplate_js_1.UriTemplate(uriTemplate) : uriTemplate; + } + /** + * Gets the URI template pattern. + */ + get uriTemplate() { + return this._uriTemplate; + } + /** + * Gets the list callback, if one was provided. + */ + get listCallback() { + return this._callbacks.list; + } + /** + * Gets the callback for completing a specific URI template variable, if one was provided. + */ + completeCallback(variable) { + var _a; + return (_a = this._callbacks.complete) === null || _a === void 0 ? void 0 : _a[variable]; + } +} +exports.ResourceTemplate = ResourceTemplate; +const EMPTY_OBJECT_JSON_SCHEMA = { + type: 'object', + properties: {} +}; +// Helper to check if an object is a Zod schema (ZodRawShapeCompat) +function isZodRawShape(obj) { + if (typeof obj !== 'object' || obj === null) + return false; + const isEmptyObject = Object.keys(obj).length === 0; + // Check if object is empty or at least one property is a ZodType instance + // Note: use heuristic check to avoid instanceof failure across different Zod versions + return isEmptyObject || Object.values(obj).some(isZodTypeLike); +} +function isZodTypeLike(value) { + return (value !== null && + typeof value === 'object' && + 'parse' in value && + typeof value.parse === 'function' && + 'safeParse' in value && + typeof value.safeParse === 'function'); +} +/** + * Converts a provided Zod schema to a Zod object if it is a ZodRawShape, + * otherwise returns the schema as is. + */ +function getZodSchemaObject(schema) { + if (!schema) { + return undefined; + } + if (isZodRawShape(schema)) { + return (0, zod_compat_js_1.objectFromShape)(schema); + } + return schema; +} +function promptArgumentsFromSchema(schema) { + const shape = (0, zod_compat_js_1.getObjectShape)(schema); + if (!shape) + return []; + return Object.entries(shape).map(([name, field]) => { + // Get description - works for both v3 and v4 + const description = (0, zod_compat_js_1.getSchemaDescription)(field); + // Check if optional - works for both v3 and v4 + const isOptional = (0, zod_compat_js_1.isSchemaOptional)(field); + return { + name, + description, + required: !isOptional + }; + }); +} +function getMethodValue(schema) { + const shape = (0, zod_compat_js_1.getObjectShape)(schema); + const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + // Extract literal value - works for both v3 and v4 + const value = (0, zod_compat_js_1.getLiteralValue)(methodSchema); + if (typeof value === 'string') { + return value; + } + throw new Error('Schema method literal must be a string'); +} +function createCompletionResult(suggestions) { + return { + completion: { + values: suggestions.slice(0, 100), + total: suggestions.length, + hasMore: suggestions.length > 100 + } + }; +} +const EMPTY_COMPLETION_RESULT = { + completion: { + values: [], + hasMore: false + } +}; +//# sourceMappingURL=mcp.js.map \ No newline at end of file diff --git a/dist/cjs/server/mcp.js.map b/dist/cjs/server/mcp.js.map new file mode 100644 index 0000000000..631cee2ecc --- /dev/null +++ b/dist/cjs/server/mcp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mcp.js","sourceRoot":"","sources":["../../../src/server/mcp.ts"],"names":[],"mappings":";;;AAAA,yCAAmD;AACnD,mDAcyB;AACzB,2EAAiE;AACjE,0CAmCqB;AACrB,qDAA+D;AAC/D,6DAAkE;AAGlE,2EAA0E;AAE1E;;;;GAIG;AACH,MAAa,SAAS;IAalB,YAAY,UAA0B,EAAE,OAAuB;QAPvD,yBAAoB,GAA0C,EAAE,CAAC;QACjE,iCAA4B,GAEhC,EAAE,CAAC;QACC,qBAAgB,GAAuC,EAAE,CAAC;QAC1D,uBAAkB,GAAyC,EAAE,CAAC;QAsB9D,6BAAwB,GAAG,KAAK,CAAC;QAkJjC,kCAA6B,GAAG,KAAK,CAAC;QAmFtC,iCAA4B,GAAG,KAAK,CAAC;QAmFrC,+BAA0B,GAAG,KAAK,CAAC;QA3UvC,IAAI,CAAC,MAAM,GAAG,IAAI,iBAAM,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAClD,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,OAAO,CAAC,SAAoB;QAC9B,OAAO,MAAM,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChD,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,KAAK;QACP,MAAM,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;I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;IAED,mDAAmD;IACnD,MAAM,KAAK,GAAG,IAAA,+BAAe,EAAC,YAAY,CAAC,CAAC;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC5B,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC9D,CAAC;AAED,SAAS,sBAAsB,CAAC,WAAqB;IACjD,OAAO;QACH,UAAU,EAAE;YACR,MAAM,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC;YACjC,KAAK,EAAE,WAAW,CAAC,MAAM;YACzB,OAAO,EAAE,WAAW,CAAC,MAAM,GAAG,GAAG;SACpC;KACJ,CAAC;AACN,CAAC;AAED,MAAM,uBAAuB,GAAmB;IAC5C,UAAU,EAAE;QACR,MAAM,EAAE,EAAE;QACV,OAAO,EAAE,KAAK;KACjB;CACJ,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/sse.d.ts b/dist/cjs/server/sse.d.ts new file mode 100644 index 0000000000..aba8d51209 --- /dev/null +++ b/dist/cjs/server/sse.d.ts @@ -0,0 +1,76 @@ +import { IncomingMessage, ServerResponse } from 'node:http'; +import { Transport } from '../shared/transport.js'; +import { JSONRPCMessage, MessageExtraInfo } from '../types.js'; +import { AuthInfo } from './auth/types.js'; +/** + * Configuration options for SSEServerTransport. + */ +export interface SSEServerTransportOptions { + /** + * List of allowed host header values for DNS rebinding protection. + * If not specified, host validation is disabled. + */ + allowedHosts?: string[]; + /** + * List of allowed origin header values for DNS rebinding protection. + * If not specified, origin validation is disabled. + */ + allowedOrigins?: string[]; + /** + * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). + * Default is false for backwards compatibility. + */ + enableDnsRebindingProtection?: boolean; +} +/** + * Server transport for SSE: this will send messages over an SSE connection and receive messages from HTTP POST requests. + * + * This transport is only available in Node.js environments. + * @deprecated SSEServerTransport is deprecated. Use StreamableHTTPServerTransport instead. + */ +export declare class SSEServerTransport implements Transport { + private _endpoint; + private res; + private _sseResponse?; + private _sessionId; + private _options; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; + /** + * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. + */ + constructor(_endpoint: string, res: ServerResponse, options?: SSEServerTransportOptions); + /** + * Validates request headers for DNS rebinding protection. + * @returns Error message if validation fails, undefined if validation passes. + */ + private validateRequestHeaders; + /** + * Handles the initial SSE connection request. + * + * This should be called when a GET request is made to establish the SSE stream. + */ + start(): Promise; + /** + * Handles incoming POST messages. + * + * This should be called when a POST request is made to send a message to the server. + */ + handlePostMessage(req: IncomingMessage & { + auth?: AuthInfo; + }, res: ServerResponse, parsedBody?: unknown): Promise; + /** + * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. + */ + handleMessage(message: unknown, extra?: MessageExtraInfo): Promise; + close(): Promise; + send(message: JSONRPCMessage): Promise; + /** + * Returns the session ID for this transport. + * + * This can be used to route incoming POST requests. + */ + get sessionId(): string; +} +//# sourceMappingURL=sse.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/sse.d.ts.map b/dist/cjs/server/sse.d.ts.map new file mode 100644 index 0000000000..c3c267cd8f --- /dev/null +++ b/dist/cjs/server/sse.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../../src/server/sse.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAwB,gBAAgB,EAAe,MAAM,aAAa,CAAC;AAGlG,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAK3C;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACtC;;;OAGG;IACH,YAAY,CAA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a/dist/cjs/server/sse.js b/dist/cjs/server/sse.js new file mode 100644 index 0000000000..d59d47c037 --- /dev/null +++ b/dist/cjs/server/sse.js @@ -0,0 +1,168 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SSEServerTransport = void 0; +const node_crypto_1 = require("node:crypto"); +const types_js_1 = require("../types.js"); +const raw_body_1 = __importDefault(require("raw-body")); +const content_type_1 = __importDefault(require("content-type")); +const url_1 = require("url"); +const MAXIMUM_MESSAGE_SIZE = '4mb'; +/** + * Server transport for SSE: this will send messages over an SSE connection and receive messages from HTTP POST requests. + * + * This transport is only available in Node.js environments. + * @deprecated SSEServerTransport is deprecated. Use StreamableHTTPServerTransport instead. + */ +class SSEServerTransport { + /** + * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. + */ + constructor(_endpoint, res, options) { + this._endpoint = _endpoint; + this.res = res; + this._sessionId = (0, node_crypto_1.randomUUID)(); + this._options = options || { enableDnsRebindingProtection: false }; + } + /** + * Validates request headers for DNS rebinding protection. + * @returns Error message if validation fails, undefined if validation passes. + */ + validateRequestHeaders(req) { + // Skip validation if protection is not enabled + if (!this._options.enableDnsRebindingProtection) { + return undefined; + } + // Validate Host header if allowedHosts is configured + if (this._options.allowedHosts && this._options.allowedHosts.length > 0) { + const hostHeader = req.headers.host; + if (!hostHeader || !this._options.allowedHosts.includes(hostHeader)) { + return `Invalid Host header: ${hostHeader}`; + } + } + // Validate Origin header if allowedOrigins is configured + if (this._options.allowedOrigins && this._options.allowedOrigins.length > 0) { + const originHeader = req.headers.origin; + if (!originHeader || !this._options.allowedOrigins.includes(originHeader)) { + return `Invalid Origin header: ${originHeader}`; + } + } + return undefined; + } + /** + * Handles the initial SSE connection request. + * + * This should be called when a GET request is made to establish the SSE stream. + */ + async start() { + if (this._sseResponse) { + throw new Error('SSEServerTransport already started! If using Server class, note that connect() calls start() automatically.'); + } + this.res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive' + }); + // Send the endpoint event + // Use a dummy base URL because this._endpoint is relative. + // This allows using URL/URLSearchParams for robust parameter handling. + const dummyBase = 'http://localhost'; // Any valid base works + const endpointUrl = new url_1.URL(this._endpoint, dummyBase); + endpointUrl.searchParams.set('sessionId', this._sessionId); + // Reconstruct the relative URL string (pathname + search + hash) + const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash; + this.res.write(`event: endpoint\ndata: ${relativeUrlWithSession}\n\n`); + this._sseResponse = this.res; + this.res.on('close', () => { + var _a; + this._sseResponse = undefined; + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + }); + } + /** + * Handles incoming POST messages. + * + * This should be called when a POST request is made to send a message to the server. + */ + async handlePostMessage(req, res, parsedBody) { + var _a, _b, _c, _d; + if (!this._sseResponse) { + const message = 'SSE connection not established'; + res.writeHead(500).end(message); + throw new Error(message); + } + // Validate request headers for DNS rebinding protection + const validationError = this.validateRequestHeaders(req); + if (validationError) { + res.writeHead(403).end(validationError); + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(validationError)); + return; + } + const authInfo = req.auth; + const requestInfo = { headers: req.headers }; + let body; + try { + const ct = content_type_1.default.parse((_b = req.headers['content-type']) !== null && _b !== void 0 ? _b : ''); + if (ct.type !== 'application/json') { + throw new Error(`Unsupported content-type: ${ct.type}`); + } + body = + parsedBody !== null && parsedBody !== void 0 ? parsedBody : (await (0, raw_body_1.default)(req, { + limit: MAXIMUM_MESSAGE_SIZE, + encoding: (_c = ct.parameters.charset) !== null && _c !== void 0 ? _c : 'utf-8' + })); + } + catch (error) { + res.writeHead(400).end(String(error)); + (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error); + return; + } + try { + await this.handleMessage(typeof body === 'string' ? JSON.parse(body) : body, { requestInfo, authInfo }); + } + catch (_e) { + res.writeHead(400).end(`Invalid message: ${body}`); + return; + } + res.writeHead(202).end('Accepted'); + } + /** + * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. + */ + async handleMessage(message, extra) { + var _a, _b; + let parsedMessage; + try { + parsedMessage = types_js_1.JSONRPCMessageSchema.parse(message); + } + catch (error) { + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + throw error; + } + (_b = this.onmessage) === null || _b === void 0 ? void 0 : _b.call(this, parsedMessage, extra); + } + async close() { + var _a, _b; + (_a = this._sseResponse) === null || _a === void 0 ? void 0 : _a.end(); + this._sseResponse = undefined; + (_b = this.onclose) === null || _b === void 0 ? void 0 : _b.call(this); + } + async send(message) { + if (!this._sseResponse) { + throw new Error('Not connected'); + } + this._sseResponse.write(`event: message\ndata: ${JSON.stringify(message)}\n\n`); + } + /** + * Returns the session ID for this transport. + * + * This can be used to route incoming POST requests. + */ + get sessionId() { + return this._sessionId; + } +} +exports.SSEServerTransport = SSEServerTransport; +//# sourceMappingURL=sse.js.map \ No newline at end of file diff --git a/dist/cjs/server/sse.js.map b/dist/cjs/server/sse.js.map new file mode 100644 index 0000000000..7eaf7edfb3 --- /dev/null +++ b/dist/cjs/server/sse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sse.js","sourceRoot":"","sources":["../../../src/server/sse.ts"],"names":[],"mappings":";;;;;;AAAA,6CAAyC;AAGzC,0CAAkG;AAClG,wDAAkC;AAClC,gEAAuC;AAEvC,6BAA0B;AAE1B,MAAM,oBAAoB,GAAG,KAAK,CAAC;AAyBnC;;;;;GAKG;AACH,MAAa,kBAAkB;IAQ3B;;OAEG;IACH,YACY,SAAiB,EACjB,GAAmB,EAC3B,OAAmC;QAF3B,cAAS,GAAT,SAAS,CAAQ;QACjB,QAAG,GAAH,GAAG,CAAgB;QAG3B,IAAI,CAAC,UAAU,GAAG,IAAA,wBAAU,GAAE,CAAC;QAC/B,IAAI,CAAC,QAAQ,GAA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CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,oBAAoB,IAAI,EAAE,CAAC,CAAC;YACnD,OAAO;QACX,CAAC;QAED,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACvC,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,aAAa,CAAC,OAAgB,EAAE,KAAwB;;QAC1D,IAAI,aAA6B,CAAC;QAClC,IAAI,CAAC;YACD,aAAa,GAAG,+BAAoB,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACxD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,MAAA,IAAI,CAAC,OAAO,qDAAG,KAAc,CAAC,CAAC;YAC/B,MAAM,KAAK,CAAC;QAChB,CAAC;QAED,MAAA,IAAI,CAAC,SAAS,qDAAG,aAAa,EAAE,KAAK,CAAC,CAAC;IAC3C,CAAC;IAED,KAAK,CAAC,KAAK;;QACP,MAAA,IAAI,CAAC,YAAY,0CAAE,GAAG,EAAE,CAAC;QACzB,IAAI,CAAC,YAAY,GAAG,SAAS,CAAC;QAC9B,MAAA,IAAI,CAAC,OAAO,oDAAI,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,OAAuB;QAC9B,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;QACrC,CAAC;QAED,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,yBAAyB,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpF,CAAC;IAED;;;;OAIG;IACH,IAAI,SAAS;QACT,OAAO,IAAI,CAAC,UAAU,CAAC;IAC3B,CAAC;CACJ;AA7KD,gDA6KC"} \ No newline at end of file diff --git a/dist/cjs/server/stdio.d.ts b/dist/cjs/server/stdio.d.ts new file mode 100644 index 0000000000..df3029d0da --- /dev/null +++ b/dist/cjs/server/stdio.d.ts @@ -0,0 +1,28 @@ +import { Readable, Writable } from 'node:stream'; +import { JSONRPCMessage } from '../types.js'; +import { Transport } from '../shared/transport.js'; +/** + * Server transport for stdio: this communicates with a MCP client by reading from the current process' stdin and writing to stdout. + * + * This transport is only available in Node.js environments. + */ +export declare class StdioServerTransport implements Transport { + private _stdin; + private _stdout; + private _readBuffer; + private _started; + constructor(_stdin?: Readable, _stdout?: Writable); + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + _ondata: (chunk: Buffer) => void; + _onerror: (error: Error) => void; + /** + * Starts listening for messages on stdin. + */ + start(): Promise; + private processReadBuffer; + close(): Promise; + send(message: JSONRPCMessage): Promise; +} +//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/stdio.d.ts.map b/dist/cjs/server/stdio.d.ts.map new file mode 100644 index 0000000000..fdd2dfe48e --- /dev/null +++ b/dist/cjs/server/stdio.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/server/stdio.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;;;GAIG;AACH,qBAAa,oBAAqB,YAAW,SAAS;IAK9C,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,OAAO;IALnB,OAAO,CAAC,WAAW,CAAgC;IACnD,OAAO,CAAC,QAAQ,CAAS;gBAGb,MAAM,GAAE,QAAwB,EAChC,OAAO,GAAE,QAAyB;IAG9C,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;IAG9C,OAAO,UAAW,MAAM,UAGtB;IACF,QAAQ,UAAW,KAAK,UAEtB;IAEF;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAY5B,OAAO,CAAC,iBAAiB;IAenB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAkB5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAU/C"} \ No newline at end of file diff --git a/dist/cjs/server/stdio.js b/dist/cjs/server/stdio.js new file mode 100644 index 0000000000..e60d19caf9 --- /dev/null +++ b/dist/cjs/server/stdio.js @@ -0,0 +1,85 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StdioServerTransport = void 0; +const node_process_1 = __importDefault(require("node:process")); +const stdio_js_1 = require("../shared/stdio.js"); +/** + * Server transport for stdio: this communicates with a MCP client by reading from the current process' stdin and writing to stdout. + * + * This transport is only available in Node.js environments. + */ +class StdioServerTransport { + constructor(_stdin = node_process_1.default.stdin, _stdout = node_process_1.default.stdout) { + this._stdin = _stdin; + this._stdout = _stdout; + this._readBuffer = new stdio_js_1.ReadBuffer(); + this._started = false; + // Arrow functions to bind `this` properly, while maintaining function identity. + this._ondata = (chunk) => { + this._readBuffer.append(chunk); + this.processReadBuffer(); + }; + this._onerror = (error) => { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }; + } + /** + * Starts listening for messages on stdin. + */ + async start() { + if (this._started) { + throw new Error('StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.'); + } + this._started = true; + this._stdin.on('data', this._ondata); + this._stdin.on('error', this._onerror); + } + processReadBuffer() { + var _a, _b; + while (true) { + try { + const message = this._readBuffer.readMessage(); + if (message === null) { + break; + } + (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message); + } + catch (error) { + (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); + } + } + } + async close() { + var _a; + // Remove our event listeners first + this._stdin.off('data', this._ondata); + this._stdin.off('error', this._onerror); + // Check if we were the only data listener + const remainingDataListeners = this._stdin.listenerCount('data'); + if (remainingDataListeners === 0) { + // Only pause stdin if we were the only listener + // This prevents interfering with other parts of the application that might be using stdin + this._stdin.pause(); + } + // Clear the buffer and notify closure + this._readBuffer.clear(); + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + } + send(message) { + return new Promise(resolve => { + const json = (0, stdio_js_1.serializeMessage)(message); + if (this._stdout.write(json)) { + resolve(); + } + else { + this._stdout.once('drain', resolve); + } + }); + } +} +exports.StdioServerTransport = StdioServerTransport; +//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/dist/cjs/server/stdio.js.map b/dist/cjs/server/stdio.js.map new file mode 100644 index 0000000000..9397ec5d28 --- /dev/null +++ b/dist/cjs/server/stdio.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/server/stdio.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAmC;AAEnC,iDAAkE;AAIlE;;;;GAIG;AACH,MAAa,oBAAoB;IAI7B,YACY,SAAmB,sBAAO,CAAC,KAAK,EAChC,UAAoB,sBAAO,CAAC,MAAM;QADlC,WAAM,GAAN,MAAM,CAA0B;QAChC,YAAO,GAAP,OAAO,CAA2B;QALtC,gBAAW,GAAe,IAAI,qBAAU,EAAE,CAAC;QAC3C,aAAQ,GAAG,KAAK,CAAC;QAWzB,gFAAgF;QAChF,YAAO,GAAG,CAAC,KAAa,EAAE,EAAE;YACxB,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC/B,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAC7B,CAAC,CAAC;QACF,aAAQ,GAAG,CAAC,KAAY,EAAE,EAAE;;YACxB,MAAA,IAAI,CAAC,OAAO,qDAAG,KAAK,CAAC,CAAC;QA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QACtC,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;QACzB,MAAA,IAAI,CAAC,OAAO,oDAAI,CAAC;IACrB,CAAC;IAED,IAAI,CAAC,OAAuB;QACxB,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE;YACzB,MAAM,IAAI,GAAG,IAAA,2BAAgB,EAAC,OAAO,CAAC,CAAC;YACvC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC3B,OAAO,EAAE,CAAC;YACd,CAAC;iBAAM,CAAC;gBACJ,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAhFD,oDAgFC"} \ No newline at end of file diff --git a/dist/cjs/server/streamableHttp.d.ts b/dist/cjs/server/streamableHttp.d.ts new file mode 100644 index 0000000000..cdad6d6593 --- /dev/null +++ b/dist/cjs/server/streamableHttp.d.ts @@ -0,0 +1,185 @@ +import { IncomingMessage, ServerResponse } from 'node:http'; +import { Transport } from '../shared/transport.js'; +import { MessageExtraInfo, JSONRPCMessage, RequestId } from '../types.js'; +import { AuthInfo } from './auth/types.js'; +export type StreamId = string; +export type EventId = string; +/** + * Interface for resumability support via event storage + */ +export interface EventStore { + /** + * Stores an event for later retrieval + * @param streamId ID of the stream the event belongs to + * @param message The JSON-RPC message to store + * @returns The generated event ID for the stored event + */ + storeEvent(streamId: StreamId, message: JSONRPCMessage): Promise; + replayEventsAfter(lastEventId: EventId, { send }: { + send: (eventId: EventId, message: JSONRPCMessage) => Promise; + }): Promise; +} +/** + * Configuration options for StreamableHTTPServerTransport + */ +export interface StreamableHTTPServerTransportOptions { + /** + * Function that generates a session ID for the transport. + * The session ID SHOULD be globally unique and cryptographically secure (e.g., a securely generated UUID, a JWT, or a cryptographic hash) + * + * Return undefined to disable session management. + */ + sessionIdGenerator: (() => string) | undefined; + /** + * A callback for session initialization events + * This is called when the server initializes a new session. + * Useful in cases when you need to register multiple mcp sessions + * and need to keep track of them. + * @param sessionId The generated session ID + */ + onsessioninitialized?: (sessionId: string) => void | Promise; + /** + * A callback for session close events + * This is called when the server closes a session due to a DELETE request. + * Useful in cases when you need to clean up resources associated with the session. + * Note that this is different from the transport closing, if you are handling + * HTTP requests from multiple nodes you might want to close each + * StreamableHTTPServerTransport after a request is completed while still keeping the + * session open/running. + * @param sessionId The session ID that was closed + */ + onsessionclosed?: (sessionId: string) => void | Promise; + /** + * If true, the server will return JSON responses instead of starting an SSE stream. + * This can be useful for simple request/response scenarios without streaming. + * Default is false (SSE streams are preferred). + */ + enableJsonResponse?: boolean; + /** + * Event store for resumability support + * If provided, resumability will be enabled, allowing clients to reconnect and resume messages + */ + eventStore?: EventStore; + /** + * List of allowed host header values for DNS rebinding protection. + * If not specified, host validation is disabled. + */ + allowedHosts?: string[]; + /** + * List of allowed origin header values for DNS rebinding protection. + * If not specified, origin validation is disabled. + */ + allowedOrigins?: string[]; + /** + * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). + * Default is false for backwards compatibility. + */ + enableDnsRebindingProtection?: boolean; +} +/** + * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It supports both SSE streaming and direct HTTP responses. + * + * Usage example: + * + * ```typescript + * // Stateful mode - server sets the session ID + * const statefulTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: () => randomUUID(), + * }); + * + * // Stateless mode - explicitly set session ID to undefined + * const statelessTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: undefined, + * }); + * + * // Using with pre-parsed request body + * app.post('/mcp', (req, res) => { + * transport.handleRequest(req, res, req.body); + * }); + * ``` + * + * In stateful mode: + * - Session ID is generated and included in response headers + * - Session ID is always included in initialization responses + * - Requests with invalid session IDs are rejected with 404 Not Found + * - Non-initialization requests without a session ID are rejected with 400 Bad Request + * - State is maintained in-memory (connections, message history) + * + * In stateless mode: + * - No Session ID is included in any responses + * - No session validation is performed + */ +export declare class StreamableHTTPServerTransport implements Transport { + private sessionIdGenerator; + private _started; + private _streamMapping; + private _requestToStreamMapping; + private _requestResponseMap; + private _initialized; + private _enableJsonResponse; + private _standaloneSseStreamId; + private _eventStore?; + private _onsessioninitialized?; + private _onsessionclosed?; + private _allowedHosts?; + private _allowedOrigins?; + private _enableDnsRebindingProtection; + sessionId?: string; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; + constructor(options: StreamableHTTPServerTransportOptions); + /** + * Starts the transport. This is required by the Transport interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + start(): Promise; + /** + * Validates request headers for DNS rebinding protection. + * @returns Error message if validation fails, undefined if validation passes. + */ + private validateRequestHeaders; + /** + * Handles an incoming HTTP request, whether GET or POST + */ + handleRequest(req: IncomingMessage & { + auth?: AuthInfo; + }, res: ServerResponse, parsedBody?: unknown): Promise; + /** + * Handles GET requests for SSE stream + */ + private handleGetRequest; + /** + * Replays events that would have been sent after the specified event ID + * Only used when resumability is enabled + */ + private replayEvents; + /** + * Writes an event to the SSE stream with proper formatting + */ + private writeSSEEvent; + /** + * Handles unsupported requests (PUT, PATCH, etc.) + */ + private handleUnsupportedRequest; + /** + * Handles POST requests containing JSON-RPC messages + */ + private handlePostRequest; + /** + * Handles DELETE requests to terminate sessions + */ + private handleDeleteRequest; + /** + * Validates session ID for non-initialization requests + * Returns true if the session is valid, false otherwise + */ + private validateSession; + private validateProtocolVersion; + close(): Promise; + send(message: JSONRPCMessage, options?: { + relatedRequestId?: RequestId; + }): Promise; +} +//# sourceMappingURL=streamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/streamableHttp.d.ts.map b/dist/cjs/server/streamableHttp.d.ts.map new file mode 100644 index 0000000000..b0b33e921d --- /dev/null +++ b/dist/cjs/server/streamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.d.ts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O,GAAG,OAAO,CAAC,IAAI,CAAC;IA6BzH;;OAEG;YACW,gBAAgB;IAiF9B;;;OAGG;YACW,YAAY;IAmC1B;;OAEG;IACH,OAAO,CAAC,aAAa;IAWrB;;OAEG;YACW,wBAAwB;IAetC;;OAEG;YACW,iBAAiB;IAuL/B;;OAEG;YACW,mBAAmB;IAYjC;;;OAGG;IACH,OAAO,CAAC,eAAe;IAkEvB,OAAO,CAAC,uBAAuB;IAsBzB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAYtB,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,SAAS,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CA+FjG"} \ No newline at end of file diff --git a/dist/cjs/server/streamableHttp.js b/dist/cjs/server/streamableHttp.js new file mode 100644 index 0000000000..c99e9f228a --- /dev/null +++ b/dist/cjs/server/streamableHttp.js @@ -0,0 +1,631 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamableHTTPServerTransport = void 0; +const types_js_1 = require("../types.js"); +const raw_body_1 = __importDefault(require("raw-body")); +const content_type_1 = __importDefault(require("content-type")); +const node_crypto_1 = require("node:crypto"); +const MAXIMUM_MESSAGE_SIZE = '4mb'; +/** + * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It supports both SSE streaming and direct HTTP responses. + * + * Usage example: + * + * ```typescript + * // Stateful mode - server sets the session ID + * const statefulTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: () => randomUUID(), + * }); + * + * // Stateless mode - explicitly set session ID to undefined + * const statelessTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: undefined, + * }); + * + * // Using with pre-parsed request body + * app.post('/mcp', (req, res) => { + * transport.handleRequest(req, res, req.body); + * }); + * ``` + * + * In stateful mode: + * - Session ID is generated and included in response headers + * - Session ID is always included in initialization responses + * - Requests with invalid session IDs are rejected with 404 Not Found + * - Non-initialization requests without a session ID are rejected with 400 Bad Request + * - State is maintained in-memory (connections, message history) + * + * In stateless mode: + * - No Session ID is included in any responses + * - No session validation is performed + */ +class StreamableHTTPServerTransport { + constructor(options) { + var _a, _b; + this._started = false; + this._streamMapping = new Map(); + this._requestToStreamMapping = new Map(); + this._requestResponseMap = new Map(); + this._initialized = false; + this._enableJsonResponse = false; + this._standaloneSseStreamId = '_GET_stream'; + this.sessionIdGenerator = options.sessionIdGenerator; + this._enableJsonResponse = (_a = options.enableJsonResponse) !== null && _a !== void 0 ? _a : false; + this._eventStore = options.eventStore; + this._onsessioninitialized = options.onsessioninitialized; + this._onsessionclosed = options.onsessionclosed; + this._allowedHosts = options.allowedHosts; + this._allowedOrigins = options.allowedOrigins; + this._enableDnsRebindingProtection = (_b = options.enableDnsRebindingProtection) !== null && _b !== void 0 ? _b : false; + } + /** + * Starts the transport. This is required by the Transport interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + async start() { + if (this._started) { + throw new Error('Transport already started'); + } + this._started = true; + } + /** + * Validates request headers for DNS rebinding protection. + * @returns Error message if validation fails, undefined if validation passes. + */ + validateRequestHeaders(req) { + // Skip validation if protection is not enabled + if (!this._enableDnsRebindingProtection) { + return undefined; + } + // Validate Host header if allowedHosts is configured + if (this._allowedHosts && this._allowedHosts.length > 0) { + const hostHeader = req.headers.host; + if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { + return `Invalid Host header: ${hostHeader}`; + } + } + // Validate Origin header if allowedOrigins is configured + if (this._allowedOrigins && this._allowedOrigins.length > 0) { + const originHeader = req.headers.origin; + if (!originHeader || !this._allowedOrigins.includes(originHeader)) { + return `Invalid Origin header: ${originHeader}`; + } + } + return undefined; + } + /** + * Handles an incoming HTTP request, whether GET or POST + */ + async handleRequest(req, res, parsedBody) { + var _a; + // Validate request headers for DNS rebinding protection + const validationError = this.validateRequestHeaders(req); + if (validationError) { + res.writeHead(403).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: validationError + }, + id: null + })); + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(validationError)); + return; + } + if (req.method === 'POST') { + await this.handlePostRequest(req, res, parsedBody); + } + else if (req.method === 'GET') { + await this.handleGetRequest(req, res); + } + else if (req.method === 'DELETE') { + await this.handleDeleteRequest(req, res); + } + else { + await this.handleUnsupportedRequest(res); + } + } + /** + * Handles GET requests for SSE stream + */ + async handleGetRequest(req, res) { + // The client MUST include an Accept header, listing text/event-stream as a supported content type. + const acceptHeader = req.headers.accept; + if (!(acceptHeader === null || acceptHeader === void 0 ? void 0 : acceptHeader.includes('text/event-stream'))) { + res.writeHead(406).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Not Acceptable: Client must accept text/event-stream' + }, + id: null + })); + return; + } + // If an Mcp-Session-Id is returned by the server during initialization, + // clients using the Streamable HTTP transport MUST include it + // in the Mcp-Session-Id header on all of their subsequent HTTP requests. + if (!this.validateSession(req, res)) { + return; + } + if (!this.validateProtocolVersion(req, res)) { + return; + } + // Handle resumability: check for Last-Event-ID header + if (this._eventStore) { + const lastEventId = req.headers['last-event-id']; + if (lastEventId) { + await this.replayEvents(lastEventId, res); + return; + } + } + // The server MUST either return Content-Type: text/event-stream in response to this HTTP GET, + // or else return HTTP 405 Method Not Allowed + const headers = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive' + }; + // After initialization, always include the session ID if we have one + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + // Check if there's already an active standalone SSE stream for this session + if (this._streamMapping.get(this._standaloneSseStreamId) !== undefined) { + // Only one GET SSE stream is allowed per session + res.writeHead(409).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Conflict: Only one SSE stream is allowed per session' + }, + id: null + })); + return; + } + // We need to send headers immediately as messages will arrive much later, + // otherwise the client will just wait for the first message + res.writeHead(200, headers).flushHeaders(); + // Assign the response to the standalone SSE stream + this._streamMapping.set(this._standaloneSseStreamId, res); + // Set up close handler for client disconnects + res.on('close', () => { + this._streamMapping.delete(this._standaloneSseStreamId); + }); + // Add error handler for standalone SSE stream + res.on('error', error => { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }); + } + /** + * Replays events that would have been sent after the specified event ID + * Only used when resumability is enabled + */ + async replayEvents(lastEventId, res) { + var _a, _b; + if (!this._eventStore) { + return; + } + try { + const headers = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive' + }; + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + res.writeHead(200, headers).flushHeaders(); + const streamId = await ((_a = this._eventStore) === null || _a === void 0 ? void 0 : _a.replayEventsAfter(lastEventId, { + send: async (eventId, message) => { + var _a; + if (!this.writeSSEEvent(res, message, eventId)) { + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error('Failed replay events')); + res.end(); + } + } + })); + this._streamMapping.set(streamId, res); + // Add error handler for replay stream + res.on('error', error => { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }); + } + catch (error) { + (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); + } + } + /** + * Writes an event to the SSE stream with proper formatting + */ + writeSSEEvent(res, message, eventId) { + let eventData = `event: message\n`; + // Include event ID if provided - this is important for resumability + if (eventId) { + eventData += `id: ${eventId}\n`; + } + eventData += `data: ${JSON.stringify(message)}\n\n`; + return res.write(eventData); + } + /** + * Handles unsupported requests (PUT, PATCH, etc.) + */ + async handleUnsupportedRequest(res) { + res.writeHead(405, { + Allow: 'GET, POST, DELETE' + }).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Method not allowed.' + }, + id: null + })); + } + /** + * Handles POST requests containing JSON-RPC messages + */ + async handlePostRequest(req, res, parsedBody) { + var _a, _b, _c, _d, _e; + try { + // Validate the Accept header + const acceptHeader = req.headers.accept; + // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types. + if (!(acceptHeader === null || acceptHeader === void 0 ? void 0 : acceptHeader.includes('application/json')) || !acceptHeader.includes('text/event-stream')) { + res.writeHead(406).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Not Acceptable: Client must accept both application/json and text/event-stream' + }, + id: null + })); + return; + } + const ct = req.headers['content-type']; + if (!ct || !ct.includes('application/json')) { + res.writeHead(415).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Unsupported Media Type: Content-Type must be application/json' + }, + id: null + })); + return; + } + const authInfo = req.auth; + const requestInfo = { headers: req.headers }; + let rawMessage; + if (parsedBody !== undefined) { + rawMessage = parsedBody; + } + else { + const parsedCt = content_type_1.default.parse(ct); + const body = await (0, raw_body_1.default)(req, { + limit: MAXIMUM_MESSAGE_SIZE, + encoding: (_a = parsedCt.parameters.charset) !== null && _a !== void 0 ? _a : 'utf-8' + }); + rawMessage = JSON.parse(body.toString()); + } + let messages; + // handle batch and single messages + if (Array.isArray(rawMessage)) { + messages = rawMessage.map(msg => types_js_1.JSONRPCMessageSchema.parse(msg)); + } + else { + messages = [types_js_1.JSONRPCMessageSchema.parse(rawMessage)]; + } + // Check if this is an initialization request + // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/ + const isInitializationRequest = messages.some(types_js_1.isInitializeRequest); + if (isInitializationRequest) { + // If it's a server with session management and the session ID is already set we should reject the request + // to avoid re-initialization. + if (this._initialized && this.sessionId !== undefined) { + res.writeHead(400).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32600, + message: 'Invalid Request: Server already initialized' + }, + id: null + })); + return; + } + if (messages.length > 1) { + res.writeHead(400).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32600, + message: 'Invalid Request: Only one initialization request is allowed' + }, + id: null + })); + return; + } + this.sessionId = (_b = this.sessionIdGenerator) === null || _b === void 0 ? void 0 : _b.call(this); + this._initialized = true; + // If we have a session ID and an onsessioninitialized handler, call it immediately + // This is needed in cases where the server needs to keep track of multiple sessions + if (this.sessionId && this._onsessioninitialized) { + await Promise.resolve(this._onsessioninitialized(this.sessionId)); + } + } + if (!isInitializationRequest) { + // If an Mcp-Session-Id is returned by the server during initialization, + // clients using the Streamable HTTP transport MUST include it + // in the Mcp-Session-Id header on all of their subsequent HTTP requests. + if (!this.validateSession(req, res)) { + return; + } + // Mcp-Protocol-Version header is required for all requests after initialization. + if (!this.validateProtocolVersion(req, res)) { + return; + } + } + // check if it contains requests + const hasRequests = messages.some(types_js_1.isJSONRPCRequest); + if (!hasRequests) { + // if it only contains notifications or responses, return 202 + res.writeHead(202).end(); + // handle each message + for (const message of messages) { + (_c = this.onmessage) === null || _c === void 0 ? void 0 : _c.call(this, message, { authInfo, requestInfo }); + } + } + else if (hasRequests) { + // The default behavior is to use SSE streaming + // but in some cases server will return JSON responses + const streamId = (0, node_crypto_1.randomUUID)(); + if (!this._enableJsonResponse) { + const headers = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive' + }; + // After initialization, always include the session ID if we have one + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + res.writeHead(200, headers); + } + // Store the response for this request to send messages back through this connection + // We need to track by request ID to maintain the connection + for (const message of messages) { + if ((0, types_js_1.isJSONRPCRequest)(message)) { + this._streamMapping.set(streamId, res); + this._requestToStreamMapping.set(message.id, streamId); + } + } + // Set up close handler for client disconnects + res.on('close', () => { + this._streamMapping.delete(streamId); + }); + // Add error handler for stream write errors + res.on('error', error => { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }); + // handle each message + for (const message of messages) { + (_d = this.onmessage) === null || _d === void 0 ? void 0 : _d.call(this, message, { authInfo, requestInfo }); + } + // The server SHOULD NOT close the SSE stream before sending all JSON-RPC responses + // This will be handled by the send() method when responses are ready + } + } + catch (error) { + // return JSON-RPC formatted error + res.writeHead(400).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32700, + message: 'Parse error', + data: String(error) + }, + id: null + })); + (_e = this.onerror) === null || _e === void 0 ? void 0 : _e.call(this, error); + } + } + /** + * Handles DELETE requests to terminate sessions + */ + async handleDeleteRequest(req, res) { + var _a; + if (!this.validateSession(req, res)) { + return; + } + if (!this.validateProtocolVersion(req, res)) { + return; + } + await Promise.resolve((_a = this._onsessionclosed) === null || _a === void 0 ? void 0 : _a.call(this, this.sessionId)); + await this.close(); + res.writeHead(200).end(); + } + /** + * Validates session ID for non-initialization requests + * Returns true if the session is valid, false otherwise + */ + validateSession(req, res) { + if (this.sessionIdGenerator === undefined) { + // If the sessionIdGenerator ID is not set, the session management is disabled + // and we don't need to validate the session ID + return true; + } + if (!this._initialized) { + // If the server has not been initialized yet, reject all requests + res.writeHead(400).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Server not initialized' + }, + id: null + })); + return false; + } + const sessionId = req.headers['mcp-session-id']; + if (!sessionId) { + // Non-initialization requests without a session ID should return 400 Bad Request + res.writeHead(400).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Mcp-Session-Id header is required' + }, + id: null + })); + return false; + } + else if (Array.isArray(sessionId)) { + res.writeHead(400).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Mcp-Session-Id header must be a single value' + }, + id: null + })); + return false; + } + else if (sessionId !== this.sessionId) { + // Reject requests with invalid session ID with 404 Not Found + res.writeHead(404).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32001, + message: 'Session not found' + }, + id: null + })); + return false; + } + return true; + } + validateProtocolVersion(req, res) { + var _a; + let protocolVersion = (_a = req.headers['mcp-protocol-version']) !== null && _a !== void 0 ? _a : types_js_1.DEFAULT_NEGOTIATED_PROTOCOL_VERSION; + if (Array.isArray(protocolVersion)) { + protocolVersion = protocolVersion[protocolVersion.length - 1]; + } + if (!types_js_1.SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) { + res.writeHead(400).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: `Bad Request: Unsupported protocol version (supported versions: ${types_js_1.SUPPORTED_PROTOCOL_VERSIONS.join(', ')})` + }, + id: null + })); + return false; + } + return true; + } + async close() { + var _a; + // Close all SSE connections + this._streamMapping.forEach(response => { + response.end(); + }); + this._streamMapping.clear(); + // Clear any pending responses + this._requestResponseMap.clear(); + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + } + async send(message, options) { + let requestId = options === null || options === void 0 ? void 0 : options.relatedRequestId; + if ((0, types_js_1.isJSONRPCResponse)(message) || (0, types_js_1.isJSONRPCError)(message)) { + // If the message is a response, use the request ID from the message + requestId = message.id; + } + // Check if this message should be sent on the standalone SSE stream (no request ID) + // Ignore notifications from tools (which have relatedRequestId set) + // Those will be sent via dedicated response SSE streams + if (requestId === undefined) { + // For standalone SSE streams, we can only send requests and notifications + if ((0, types_js_1.isJSONRPCResponse)(message) || (0, types_js_1.isJSONRPCError)(message)) { + throw new Error('Cannot send a response on a standalone SSE stream unless resuming a previous client request'); + } + const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); + if (standaloneSse === undefined) { + // The spec says the server MAY send messages on the stream, so it's ok to discard if no stream + return; + } + // Generate and store event ID if event store is provided + let eventId; + if (this._eventStore) { + // Stores the event and gets the generated event ID + eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); + } + // Send the message to the standalone SSE stream + this.writeSSEEvent(standaloneSse, message, eventId); + return; + } + // Get the response for this request + const streamId = this._requestToStreamMapping.get(requestId); + const response = this._streamMapping.get(streamId); + if (!streamId) { + throw new Error(`No connection established for request ID: ${String(requestId)}`); + } + if (!this._enableJsonResponse) { + // For SSE responses, generate event ID if event store is provided + let eventId; + if (this._eventStore) { + eventId = await this._eventStore.storeEvent(streamId, message); + } + if (response) { + // Write the event to the response stream + this.writeSSEEvent(response, message, eventId); + } + } + if ((0, types_js_1.isJSONRPCResponse)(message) || (0, types_js_1.isJSONRPCError)(message)) { + this._requestResponseMap.set(requestId, message); + const relatedIds = Array.from(this._requestToStreamMapping.entries()) + .filter(([_, streamId]) => this._streamMapping.get(streamId) === response) + .map(([id]) => id); + // Check if we have responses for all requests using this connection + const allResponsesReady = relatedIds.every(id => this._requestResponseMap.has(id)); + if (allResponsesReady) { + if (!response) { + throw new Error(`No connection established for request ID: ${String(requestId)}`); + } + if (this._enableJsonResponse) { + // All responses ready, send as JSON + const headers = { + 'Content-Type': 'application/json' + }; + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + const responses = relatedIds.map(id => this._requestResponseMap.get(id)); + response.writeHead(200, headers); + if (responses.length === 1) { + response.end(JSON.stringify(responses[0])); + } + else { + response.end(JSON.stringify(responses)); + } + } + else { + // End the SSE stream + response.end(); + } + // Clean up + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + } + } + } +} +exports.StreamableHTTPServerTransport = StreamableHTTPServerTransport; +//# sourceMappingURL=streamableHttp.js.map \ No newline at end of file diff --git a/dist/cjs/server/streamableHttp.js.map b/dist/cjs/server/streamableHttp.js.map new file mode 100644 index 0000000000..45bfddb41f --- /dev/null +++ b/dist/cjs/server/streamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.js","sourceRoot":"","sources":["../../../src/server/streamableHttp.ts"],"names":[],"mappings":";;;;;;AAEA,0CAYqB;AACrB,wDAAkC;AAClC,gEAAuC;AACvC,6CAAyC;AAGzC,MAAM,oBAAoB,GAAG,KAAK,CAAC;AA4FnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAa,6BAA6B;IAsBtC,YAAY,OAA6C;;QAnBjD,aAAQ,GAAY,KAAK,CAAC;QAC1B,mBAAc,GAAgC,IA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SAAS,CAAC;oBAC/C,CAAC;oBAED,MAAM,SAAS,GAAG,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,EAAE,CAAE,CAAC,CAAC;oBAE1E,QAAQ,CAAC,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;oBACjC,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;wBACzB,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;oBAC/C,CAAC;yBAAM,CAAC;wBACJ,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC;oBAC5C,CAAC;gBACL,CAAC;qBAAM,CAAC;oBACJ,qBAAqB;oBACrB,QAAQ,CAAC,GAAG,EAAE,CAAC;gBACnB,CAAC;gBACD,WAAW;gBACX,KAAK,MAAM,EAAE,IAAI,UAAU,EAAE,CAAC;oBAC1B,IAAI,CAAC,mBAAmB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;oBACpC,IAAI,CAAC,uBAAuB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBAC5C,CAAC;YACL,CAAC;QACL,CAAC;IACL,CAAC;CACJ;AAppBD,sEAopBC"} \ No newline at end of file diff --git a/dist/cjs/server/zod-compat.d.ts b/dist/cjs/server/zod-compat.d.ts new file mode 100644 index 0000000000..13fb9723c5 --- /dev/null +++ b/dist/cjs/server/zod-compat.d.ts @@ -0,0 +1,82 @@ +import type * as z3 from 'zod/v3'; +import type * as z4 from 'zod/v4/core'; +export type AnySchema = z3.ZodTypeAny | z4.$ZodType; +export type AnyObjectSchema = z3.AnyZodObject | z4.$ZodObject | AnySchema; +export type ZodRawShapeCompat = Record; +export interface ZodV3Internal { + _def?: { + typeName?: string; + value?: unknown; + values?: unknown[]; + shape?: Record | (() => Record); + description?: string; + }; + shape?: Record | (() => Record); + value?: unknown; +} +export interface ZodV4Internal { + _zod?: { + def?: { + typeName?: string; + value?: unknown; + values?: unknown[]; + shape?: Record | (() => Record); + description?: string; + }; + }; + value?: unknown; +} +export type SchemaOutput = S extends z3.ZodTypeAny ? z3.infer : S extends z4.$ZodType ? z4.output : never; +export type SchemaInput = S extends z3.ZodTypeAny ? z3.input : S extends z4.$ZodType ? z4.input : never; +/** + * Infers the output type from a ZodRawShapeCompat (raw shape object). + * Maps over each key in the shape and infers the output type from each schema. + */ +export type ShapeOutput = { + [K in keyof Shape]: SchemaOutput; +}; +export declare function isZ4Schema(s: AnySchema): s is z4.$ZodType; +export declare function objectFromShape(shape: ZodRawShapeCompat): AnyObjectSchema; +export declare function safeParse(schema: S, data: unknown): { + success: true; + data: SchemaOutput; +} | { + success: false; + error: unknown; +}; +export declare function safeParseAsync(schema: S, data: unknown): Promise<{ + success: true; + data: SchemaOutput; +} | { + success: false; + error: unknown; +}>; +export declare function getObjectShape(schema: AnyObjectSchema | undefined): Record | undefined; +/** + * Normalizes a schema to an object schema. Handles both: + * - Already-constructed object schemas (v3 or v4) + * - Raw shapes that need to be wrapped into object schemas + */ +export declare function normalizeObjectSchema(schema: AnySchema | ZodRawShapeCompat | undefined): AnyObjectSchema | undefined; +/** + * Safely extracts an error message from a parse result error. + * Zod errors can have different structures, so we handle various cases. + */ +export declare function getParseErrorMessage(error: unknown): string; +/** + * Gets the description from a schema, if available. + * Works with both Zod v3 and v4. + */ +export declare function getSchemaDescription(schema: AnySchema): string | undefined; +/** + * Checks if a schema is optional. + * Works with both Zod v3 and v4. + */ +export declare function isSchemaOptional(schema: AnySchema): boolean; +/** + * Gets the literal value from a schema, if it's a literal schema. + * Works with both Zod v3 and v4. + * Returns undefined if the schema is not a literal or the value cannot be determined. + */ +export declare function getLiteralValue(schema: AnySchema): unknown; +//# sourceMappingURL=zod-compat.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/zod-compat.d.ts.map b/dist/cjs/server/zod-compat.d.ts.map new file mode 100644 index 0000000000..608ca930c3 --- /dev/null +++ b/dist/cjs/server/zod-compat.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"zod-compat.d.ts","sourceRoot":"","sources":["../../../src/server/zod-compat.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,KAAK,EAAE,MAAM,QAAQ,CAAC;AAClC,OAAO,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAMvC,MAAM,MAAM,SAAS,GAAG,EAAE,CAAC,UAAU,GAAG,EAAE,CAAC,QAAQ,CAAC;AACpD,MAAM,MAAM,eAAe,GAAG,EAAE,CAAC,YAAY,GAAG,EAAE,CAAC,UAAU,GAAG,SAAS,CAAC;AAC1E,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AAI1D,MAAM,WAAW,aAAa;IAC1B,IAAI,CAAC,EAAE;QACH,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,KAAK,CAAC,EAAE,OAAO,CAAC;QAChB,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC;QACnB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,CAAC,MAAM,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;QACtE,WAAW,CAAC,EAAE,MAAM,CAAC;KACxB,CAAC;IACF,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,CAAC,MAAM,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;IACtE,KAAK,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,MAAM,WAAW,aAAa;IAC1B,IAAI,CAAC,EAAE;QACH,GAAG,CAAC,EAAE;YACF,QAAQ,CAAC,EAAE,MAAM,CAAC;YAClB,KAAK,CAAC,EAAE,OAAO,CAAC;YAChB,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC;YACnB,KAAK,CAAC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AAC,CAAC,SAAS,SAAS,EACpD,MAAM,EAAE,CAAC,EACT,IAAI,EAAE,OAAO,GACd,OAAO,CAAC;IAAE,OAAO,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC,CAAA;CAAE,GAAG;IAAE,OAAO,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC,CASxF;AAGD,wBAAgB,cAAc,CAAC,MAAM,EAAE,eAAe,GAAG,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,SAAS,CAyBzG;AAGD;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,SAAS,GAAG,iBAAiB,GAAG,SAAS,GAAG,eAAe,GAAG,SAAS,CAiDpH;AAGD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAoB3D;AAGD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,SAAS,GAAG,MAAM,GAAG,SAAS,CAQ1E;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAW3D;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAwB1D"} \ No newline at end of file diff --git a/dist/cjs/server/zod-compat.js b/dist/cjs/server/zod-compat.js new file mode 100644 index 0000000000..602a9bf188 --- /dev/null +++ b/dist/cjs/server/zod-compat.js @@ -0,0 +1,252 @@ +"use strict"; +// zod-compat.ts +// ---------------------------------------------------- +// Unified types + helpers to accept Zod v3 and v4 (Mini) +// ---------------------------------------------------- +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isZ4Schema = isZ4Schema; +exports.objectFromShape = objectFromShape; +exports.safeParse = safeParse; +exports.safeParseAsync = safeParseAsync; +exports.getObjectShape = getObjectShape; +exports.normalizeObjectSchema = normalizeObjectSchema; +exports.getParseErrorMessage = getParseErrorMessage; +exports.getSchemaDescription = getSchemaDescription; +exports.isSchemaOptional = isSchemaOptional; +exports.getLiteralValue = getLiteralValue; +const z3rt = __importStar(require("zod/v3")); +const z4mini = __importStar(require("zod/v4-mini")); +// --- Runtime detection --- +function isZ4Schema(s) { + // Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3 + const schema = s; + return !!schema._zod; +} +// --- Schema construction --- +function objectFromShape(shape) { + const values = Object.values(shape); + if (values.length === 0) + return z4mini.object({}); // default to v4 Mini + const allV4 = values.every(isZ4Schema); + const allV3 = values.every(s => !isZ4Schema(s)); + if (allV4) + return z4mini.object(shape); + if (allV3) + return z3rt.object(shape); + throw new Error('Mixed Zod versions detected in object shape.'); +} +// --- Unified parsing --- +function safeParse(schema, data) { + if (isZ4Schema(schema)) { + // Mini exposes top-level safeParse + const result = z4mini.safeParse(schema, data); + return result; + } + const v3Schema = schema; + const result = v3Schema.safeParse(data); + return result; +} +async function safeParseAsync(schema, data) { + if (isZ4Schema(schema)) { + // Mini exposes top-level safeParseAsync + const result = await z4mini.safeParseAsync(schema, data); + return result; + } + const v3Schema = schema; + const result = await v3Schema.safeParseAsync(data); + return result; +} +// --- Shape extraction --- +function getObjectShape(schema) { + var _a, _b; + if (!schema) + return undefined; + // Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape` + let rawShape; + if (isZ4Schema(schema)) { + const v4Schema = schema; + rawShape = (_b = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def) === null || _b === void 0 ? void 0 : _b.shape; + } + else { + const v3Schema = schema; + rawShape = v3Schema.shape; + } + if (!rawShape) + return undefined; + if (typeof rawShape === 'function') { + try { + return rawShape(); + } + catch (_c) { + return undefined; + } + } + return rawShape; +} +// --- Schema normalization --- +/** + * Normalizes a schema to an object schema. Handles both: + * - Already-constructed object schemas (v3 or v4) + * - Raw shapes that need to be wrapped into object schemas + */ +function normalizeObjectSchema(schema) { + var _a; + if (!schema) + return undefined; + // First check if it's a raw shape (Record) + // Raw shapes don't have _def or _zod properties and aren't schemas themselves + if (typeof schema === 'object') { + // Check if it's actually a ZodRawShapeCompat (not a schema instance) + // by checking if it lacks schema-like internal properties + const asV3 = schema; + const asV4 = schema; + // If it's not a schema instance (no _def or _zod), it might be a raw shape + if (!asV3._def && !asV4._zod) { + // Check if all values are schemas (heuristic to confirm it's a raw shape) + const values = Object.values(schema); + if (values.length > 0 && + values.every(v => typeof v === 'object' && + v !== null && + (v._def !== undefined || + v._zod !== undefined || + typeof v.parse === 'function'))) { + return objectFromShape(schema); + } + } + } + // If we get here, it should be an AnySchema (not a raw shape) + // Check if it's already an object schema + if (isZ4Schema(schema)) { + // Check if it's a v4 object + const v4Schema = schema; + const def = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def; + if (def && (def.typeName === 'object' || def.shape !== undefined)) { + return schema; + } + } + else { + // Check if it's a v3 object + const v3Schema = schema; + if (v3Schema.shape !== undefined) { + return schema; + } + } + return undefined; +} +// --- Error message extraction --- +/** + * Safely extracts an error message from a parse result error. + * Zod errors can have different structures, so we handle various cases. + */ +function getParseErrorMessage(error) { + if (error && typeof error === 'object') { + // Try common error structures + if ('message' in error && typeof error.message === 'string') { + return error.message; + } + if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) { + const firstIssue = error.issues[0]; + if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) { + return String(firstIssue.message); + } + } + // Fallback: try to stringify the error + try { + return JSON.stringify(error); + } + catch (_a) { + return String(error); + } + } + return String(error); +} +// --- Schema metadata access --- +/** + * Gets the description from a schema, if available. + * Works with both Zod v3 and v4. + */ +function getSchemaDescription(schema) { + var _a, _b, _c, _d; + if (isZ4Schema(schema)) { + const v4Schema = schema; + return (_b = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def) === null || _b === void 0 ? void 0 : _b.description; + } + const v3Schema = schema; + // v3 may have description on the schema itself or in _def + return (_c = schema.description) !== null && _c !== void 0 ? _c : (_d = v3Schema._def) === null || _d === void 0 ? void 0 : _d.description; +} +/** + * Checks if a schema is optional. + * Works with both Zod v3 and v4. + */ +function isSchemaOptional(schema) { + var _a, _b, _c; + if (isZ4Schema(schema)) { + const v4Schema = schema; + return ((_b = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def) === null || _b === void 0 ? void 0 : _b.typeName) === 'ZodOptional'; + } + const v3Schema = schema; + // v3 has isOptional() method + if (typeof schema.isOptional === 'function') { + return schema.isOptional(); + } + return ((_c = v3Schema._def) === null || _c === void 0 ? void 0 : _c.typeName) === 'ZodOptional'; +} +/** + * Gets the literal value from a schema, if it's a literal schema. + * Works with both Zod v3 and v4. + * Returns undefined if the schema is not a literal or the value cannot be determined. + */ +function getLiteralValue(schema) { + var _a; + if (isZ4Schema(schema)) { + const v4Schema = schema; + const def = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def; + if (def) { + // Try various ways to get the literal value + if (def.value !== undefined) + return def.value; + if (Array.isArray(def.values) && def.values.length > 0) { + return def.values[0]; + } + } + } + const v3Schema = schema; + const def = v3Schema._def; + if (def) { + if (def.value !== undefined) + return def.value; + if (Array.isArray(def.values) && def.values.length > 0) { + return def.values[0]; + } + } + // Fallback: check for direct value property (some Zod versions) + const directValue = schema.value; + if (directValue !== undefined) + return directValue; + return undefined; +} +//# sourceMappingURL=zod-compat.js.map \ No newline at end of file diff --git a/dist/cjs/server/zod-compat.js.map b/dist/cjs/server/zod-compat.js.map new file mode 100644 index 0000000000..ef6828d204 --- /dev/null +++ b/dist/cjs/server/zod-compat.js.map @@ -0,0 +1 @@ +{"version":3,"file":"zod-compat.js","sourceRoot":"","sources":["../../../src/server/zod-compat.ts"],"names":[],"mappings":";AAAA,gBAAgB;AAChB,uDAAuD;AACvD,yDAAyD;AACzD,uDAAuD;;;;;;;;;;;;;;;;;;;;;;;;;AAsDvD,gCAIC;AAGD,0CAWC;AAGD,8BAYC;AAED,wCAYC;AAGD,wCAyBC;AAQD,sDAiDC;AAOD,oDAoBC;AAOD,oDAQC;AAMD,4CAWC;AAOD,0CAwBC;AA/QD,6CAA+B;AAC/B,oDAAsC;AA+CtC,4BAA4B;AAC5B,SAAgB,UAAU,CAAC,CAAY;IACnC,6DAA6D;IAC7D,MAAM,MAAM,GAAG,CAA6B,CAAC;IAC7C,OAAO,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC;AACzB,CAAC;AAED,8BAA8B;AAC9B,SAAgB,eAAe,CAAC,KAAwB;IACpD,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACpC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,qBAAqB;IAExE,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACvC,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;IAEhD,IAAI,KAAK;QAAE,OAAO,MAAM,CAAC,MAAM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AG,MAAkC,CAAC;QACpD,MAAM,GAAG,GAAG,MAAA,QAAQ,CAAC,IAAI,0CAAE,GAAG,CAAC;QAC/B,IAAI,GAAG,EAAE,CAAC;YACN,4CAA4C;YAC5C,IAAI,GAAG,CAAC,KAAK,KAAK,SAAS;gBAAE,OAAO,GAAG,CAAC,KAAK,CAAC;YAC9C,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACrD,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACzB,CAAC;QACL,CAAC;IACL,CAAC;IACD,MAAM,QAAQ,GAAG,MAAkC,CAAC;IACpD,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC;IAC1B,IAAI,GAAG,EAAE,CAAC;QACN,IAAI,GAAG,CAAC,KAAK,KAAK,SAAS;YAAE,OAAO,GAAG,CAAC,KAAK,CAAC;QAC9C,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACrD,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QACzB,CAAC;IACL,CAAC;IACD,gEAAgE;IAChE,MAAM,WAAW,GAAI,MAA8B,CAAC,KAAK,CAAC;IAC1D,IAAI,WAAW,KAAK,SAAS;QAAE,OAAO,WAAW,CAAC;IAClD,OAAO,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/zod-json-schema-compat.d.ts b/dist/cjs/server/zod-json-schema-compat.d.ts new file mode 100644 index 0000000000..3a04452b47 --- /dev/null +++ b/dist/cjs/server/zod-json-schema-compat.d.ts @@ -0,0 +1,12 @@ +import { AnySchema, AnyObjectSchema } from './zod-compat.js'; +type JsonSchema = Record; +type CommonOpts = { + strictUnions?: boolean; + pipeStrategy?: 'input' | 'output'; + target?: 'jsonSchema7' | 'draft-7' | 'jsonSchema2019-09' | 'draft-2020-12'; +}; +export declare function toJsonSchemaCompat(schema: AnyObjectSchema, opts?: CommonOpts): JsonSchema; +export declare function getMethodLiteral(schema: AnyObjectSchema): string; +export declare function parseWithCompat(schema: AnySchema, data: unknown): unknown; +export {}; +//# sourceMappingURL=zod-json-schema-compat.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/zod-json-schema-compat.d.ts.map b/dist/cjs/server/zod-json-schema-compat.d.ts.map new file mode 100644 index 0000000000..0b851bf50e --- /dev/null +++ b/dist/cjs/server/zod-json-schema-compat.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"zod-json-schema-compat.d.ts","sourceRoot":"","sources":["../../../src/server/zod-json-schema-compat.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,SAAS,EAAE,eAAe,EAA0D,MAAM,iBAAiB,CAAC;AAGrH,KAAK,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAG1C,KAAK,UAAU,GAAG;IACd,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;IAClC,MAAM,CAAC,EAAE,aAAa,GAAG,SAAS,GAAG,mBAAmB,GAAG,eAAe,CAAC;CAC9E,CAAC;AASF,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,eAAe,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,UAAU,CAczF;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,eAAe,GAAG,MAAM,CAahE;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,GAAG,OAAO,CAMzE"} \ No newline at end of file diff --git a/dist/cjs/server/zod-json-schema-compat.js b/dist/cjs/server/zod-json-schema-compat.js new file mode 100644 index 0000000000..e42265d4c6 --- /dev/null +++ b/dist/cjs/server/zod-json-schema-compat.js @@ -0,0 +1,80 @@ +"use strict"; +// zod-json-schema-compat.ts +// ---------------------------------------------------- +// JSON Schema conversion for both Zod v3 and Zod v4 (Mini) +// v3 uses your vendored converter; v4 uses Mini's toJSONSchema +// ---------------------------------------------------- +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.toJsonSchemaCompat = toJsonSchemaCompat; +exports.getMethodLiteral = getMethodLiteral; +exports.parseWithCompat = parseWithCompat; +const z4mini = __importStar(require("zod/v4-mini")); +const zod_compat_js_1 = require("./zod-compat.js"); +const zod_to_json_schema_1 = require("zod-to-json-schema"); +function mapMiniTarget(t) { + if (!t) + return 'draft-7'; + if (t === 'jsonSchema7' || t === 'draft-7') + return 'draft-7'; + if (t === 'jsonSchema2019-09' || t === 'draft-2020-12') + return 'draft-2020-12'; + return 'draft-7'; // fallback +} +function toJsonSchemaCompat(schema, opts) { + var _a, _b, _c; + if ((0, zod_compat_js_1.isZ4Schema)(schema)) { + // v4 branch — use Mini's built-in toJSONSchema + return z4mini.toJSONSchema(schema, { + target: mapMiniTarget(opts === null || opts === void 0 ? void 0 : opts.target), + io: (_a = opts === null || opts === void 0 ? void 0 : opts.pipeStrategy) !== null && _a !== void 0 ? _a : 'input' + }); + } + // v3 branch — use vendored converter + return (0, zod_to_json_schema_1.zodToJsonSchema)(schema, { + strictUnions: (_b = opts === null || opts === void 0 ? void 0 : opts.strictUnions) !== null && _b !== void 0 ? _b : true, + pipeStrategy: (_c = opts === null || opts === void 0 ? void 0 : opts.pipeStrategy) !== null && _c !== void 0 ? _c : 'input' + }); +} +function getMethodLiteral(schema) { + const shape = (0, zod_compat_js_1.getObjectShape)(schema); + const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + const value = (0, zod_compat_js_1.getLiteralValue)(methodSchema); + if (typeof value !== 'string') { + throw new Error('Schema method literal must be a string'); + } + return value; +} +function parseWithCompat(schema, data) { + const result = (0, zod_compat_js_1.safeParse)(schema, data); + if (!result.success) { + throw result.error; + } + return result.data; +} +//# sourceMappingURL=zod-json-schema-compat.js.map \ No newline at end of file diff --git a/dist/cjs/server/zod-json-schema-compat.js.map b/dist/cjs/server/zod-json-schema-compat.js.map new file mode 100644 index 0000000000..4cda29da48 --- /dev/null +++ b/dist/cjs/server/zod-json-schema-compat.js.map @@ -0,0 +1 @@ +{"version":3,"file":"zod-json-schema-compat.js","sourceRoot":"","sources":["../../../src/server/zod-json-schema-compat.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,uDAAuD;AACvD,2DAA2D;AAC3D,+DAA+D;AAC/D,uDAAuD;;;;;;;;;;;;;;;;;;;;;;;;;AA0BvD,gDAcC;AAED,4CAaC;AAED,0CAMC;AA1DD,oDAAsC;AAEtC,mDAAqH;AACrH,2DAAqD;AAWrD,SAAS,aAAa,CAAC,CAAmC;IACtD,IAAI,CAAC,CAAC;QAAE,OAAO,SAAS,CAAC;IACzB,IAAI,CAAC,KAAK,aAAa,IAAI,CAAC,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC7D,IAAI,CAAC,KAAK,mBAAmB,IAAI,CAAC,KAAK,eAAe;QAAE,O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AAG,IAAA,yBAAS,EAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACvC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QAClB,MAAM,MAAM,CAAC,KAAK,CAAC;IACvB,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC;AACvB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/auth-utils.d.ts b/dist/cjs/shared/auth-utils.d.ts new file mode 100644 index 0000000000..c966e30e74 --- /dev/null +++ b/dist/cjs/shared/auth-utils.d.ts @@ -0,0 +1,23 @@ +/** + * Utilities for handling OAuth resource URIs. + */ +/** + * Converts a server URL to a resource URL by removing the fragment. + * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". + * Keeps everything else unchanged (scheme, domain, port, path, query). + */ +export declare function resourceUrlFromServerUrl(url: URL | string): URL; +/** + * Checks if a requested resource URL matches a configured resource URL. + * A requested resource matches if it has the same scheme, domain, port, + * and its path starts with the configured resource's path. + * + * @param requestedResource The resource URL being requested + * @param configuredResource The resource URL that has been configured + * @returns true if the requested resource matches the configured resource, false otherwise + */ +export declare function checkResourceAllowed({ requestedResource, configuredResource }: { + requestedResource: URL | string; + configuredResource: URL | string; +}): boolean; +//# sourceMappingURL=auth-utils.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/auth-utils.d.ts.map b/dist/cjs/shared/auth-utils.d.ts.map new file mode 100644 index 0000000000..30873de552 --- /dev/null +++ b/dist/cjs/shared/auth-utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auth-utils.d.ts","sourceRoot":"","sources":["../../../src/shared/auth-utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,GAAG,GAAG,CAI/D;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,EACjC,iBAAiB,EACjB,kBAAkB,EACrB,EAAE;IACC,iBAAiB,EAAE,GAAG,GAAG,MAAM,CAAC;IAChC,kBAAkB,EAAE,GAAG,GAAG,MAAM,CAAC;CACpC,GAAG,OAAO,CAwBV"} \ No newline at end of file diff --git a/dist/cjs/shared/auth-utils.js b/dist/cjs/shared/auth-utils.js new file mode 100644 index 0000000000..f2fe617344 --- /dev/null +++ b/dist/cjs/shared/auth-utils.js @@ -0,0 +1,48 @@ +"use strict"; +/** + * Utilities for handling OAuth resource URIs. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resourceUrlFromServerUrl = resourceUrlFromServerUrl; +exports.checkResourceAllowed = checkResourceAllowed; +/** + * Converts a server URL to a resource URL by removing the fragment. + * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". + * Keeps everything else unchanged (scheme, domain, port, path, query). + */ +function resourceUrlFromServerUrl(url) { + const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href); + resourceURL.hash = ''; // Remove fragment + return resourceURL; +} +/** + * Checks if a requested resource URL matches a configured resource URL. + * A requested resource matches if it has the same scheme, domain, port, + * and its path starts with the configured resource's path. + * + * @param requestedResource The resource URL being requested + * @param configuredResource The resource URL that has been configured + * @returns true if the requested resource matches the configured resource, false otherwise + */ +function checkResourceAllowed({ requestedResource, configuredResource }) { + const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href); + const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href); + // Compare the origin (scheme, domain, and port) + if (requested.origin !== configured.origin) { + return false; + } + // Handle cases like requested=/foo and configured=/foo/ + if (requested.pathname.length < configured.pathname.length) { + return false; + } + // Check if the requested path starts with the configured path + // Ensure both paths end with / for proper comparison + // This ensures that if we have paths like "/api" and "/api/users", + // we properly detect that "/api/users" is a subpath of "/api" + // By adding a trailing slash if missing, we avoid false positives + // where paths like "/api123" would incorrectly match "/api" + const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/'; + const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/'; + return requestedPath.startsWith(configuredPath); +} +//# sourceMappingURL=auth-utils.js.map \ No newline at end of file diff --git a/dist/cjs/shared/auth-utils.js.map b/dist/cjs/shared/auth-utils.js.map new file mode 100644 index 0000000000..4a71b257bb --- /dev/null +++ b/dist/cjs/shared/auth-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth-utils.js","sourceRoot":"","sources":["../../../src/shared/auth-utils.ts"],"names":[],"mappings":";AAAA;;GAEG;;AAOH,4DAIC;AAWD,oDA8BC;AAlDD;;;;GAIG;AACH,SAAgB,wBAAwB,CAAC,GAAiB;IACtD,MAAM,WAAW,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAC/E,WAAW,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,kBAAkB;IACzC,OAAO,WAAW,CAAC;AACvB,CAAC;AAED;;;;;;;;GAQG;AACH,SAAgB,oBAAoB,CAAC,EACjC,iBAAiB,EACjB,kBAAkB,EAIrB;IACG,MAAM,SAAS,GAAG,OAAO,iBAAiB,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACvH,MAAM,UAAU,GAAG,OAAO,kBAAkB,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;IAE3H,gDAAgD;IAChD,IAAI,SAAS,CAAC,MAAM,KAAK,UAAU,CAAC,MAAM,EAAE,CAAC;QACzC,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,wDAAwD;IACxD,IAAI,SAAS,CAAC,QAAQ,CAAC,MAAM,GAAG,UAAU,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;QACzD,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,8DAA8D;IAC9D,qDAAqD;IACrD,mEAAmE;IACnE,8DAA8D;IAC9D,kEAAkE;IAClE,4DAA4D;IAC5D,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,GAAG,GAAG,CAAC;IACvG,MAAM,cAAc,GAAG,UAAU,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,GAAG,GAAG,CAAC;IAE3G,OAAO,aAAa,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;AACpD,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/auth.d.ts b/dist/cjs/shared/auth.d.ts new file mode 100644 index 0000000000..c9e723a002 --- /dev/null +++ b/dist/cjs/shared/auth.d.ts @@ -0,0 +1,240 @@ +import * as z from 'zod/v4'; +/** + * Reusable URL validation that disallows javascript: scheme + */ +export declare const SafeUrlSchema: z.ZodURL; +/** + * RFC 9728 OAuth Protected Resource Metadata + */ +export declare const OAuthProtectedResourceMetadataSchema: z.ZodObject<{ + resource: z.ZodString; + authorization_servers: z.ZodOptional>; + jwks_uri: z.ZodOptional; + scopes_supported: z.ZodOptional>; + bearer_methods_supported: z.ZodOptional>; + resource_signing_alg_values_supported: z.ZodOptional>; + resource_name: z.ZodOptional; + resource_documentation: z.ZodOptional; + resource_policy_uri: z.ZodOptional; + resource_tos_uri: z.ZodOptional; + tls_client_certificate_bound_access_tokens: z.ZodOptional; + authorization_details_types_supported: z.ZodOptional>; + dpop_signing_alg_values_supported: z.ZodOptional>; + dpop_bound_access_tokens_required: z.ZodOptional; +}, z.core.$loose>; +/** + * RFC 8414 OAuth 2.0 Authorization Server Metadata + */ +export declare const OAuthMetadataSchema: z.ZodObject<{ + issuer: z.ZodString; + authorization_endpoint: z.ZodURL; + token_endpoint: z.ZodURL; + registration_endpoint: z.ZodOptional; + scopes_supported: z.ZodOptional>; + response_types_supported: z.ZodArray; + response_modes_supported: z.ZodOptional>; + grant_types_supported: z.ZodOptional>; + token_endpoint_auth_methods_supported: z.ZodOptional>; + token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + service_documentation: z.ZodOptional; + revocation_endpoint: z.ZodOptional; + revocation_endpoint_auth_methods_supported: z.ZodOptional>; + revocation_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + introspection_endpoint: z.ZodOptional; + introspection_endpoint_auth_methods_supported: z.ZodOptional>; + introspection_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + code_challenge_methods_supported: z.ZodOptional>; + client_id_metadata_document_supported: z.ZodOptional; +}, z.core.$loose>; +/** + * OpenID Connect Discovery 1.0 Provider Metadata + * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata + */ +export declare const OpenIdProviderMetadataSchema: z.ZodObject<{ + issuer: z.ZodString; + authorization_endpoint: z.ZodURL; + token_endpoint: z.ZodURL; + userinfo_endpoint: z.ZodOptional; + jwks_uri: z.ZodURL; + registration_endpoint: z.ZodOptional; + scopes_supported: z.ZodOptional>; + response_types_supported: z.ZodArray; + response_modes_supported: z.ZodOptional>; + grant_types_supported: z.ZodOptional>; + acr_values_supported: z.ZodOptional>; + subject_types_supported: z.ZodArray; + id_token_signing_alg_values_supported: z.ZodArray; + id_token_encryption_alg_values_supported: z.ZodOptional>; + id_token_encryption_enc_values_supported: z.ZodOptional>; + userinfo_signing_alg_values_supported: z.ZodOptional>; + userinfo_encryption_alg_values_supported: z.ZodOptional>; + userinfo_encryption_enc_values_supported: z.ZodOptional>; + request_object_signing_alg_values_supported: z.ZodOptional>; + request_object_encryption_alg_values_supported: z.ZodOptional>; + request_object_encryption_enc_values_supported: z.ZodOptional>; + token_endpoint_auth_methods_supported: z.ZodOptional>; + token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + display_values_supported: z.ZodOptional>; + claim_types_supported: z.ZodOptional>; + claims_supported: z.ZodOptional>; + service_documentation: z.ZodOptional; + claims_locales_supported: z.ZodOptional>; + ui_locales_supported: z.ZodOptional>; + claims_parameter_supported: z.ZodOptional; + request_parameter_supported: z.ZodOptional; + request_uri_parameter_supported: z.ZodOptional; + require_request_uri_registration: z.ZodOptional; + op_policy_uri: z.ZodOptional; + op_tos_uri: z.ZodOptional; + client_id_metadata_document_supported: z.ZodOptional; +}, z.core.$loose>; +/** + * OpenID Connect Discovery metadata that may include OAuth 2.0 fields + * This schema represents the real-world scenario where OIDC providers + * return a mix of OpenID Connect and OAuth 2.0 metadata fields + */ +export declare const OpenIdProviderDiscoveryMetadataSchema: z.ZodObject<{ + code_challenge_methods_supported: z.ZodOptional>; + issuer: z.ZodString; + authorization_endpoint: z.ZodURL; + token_endpoint: z.ZodURL; + userinfo_endpoint: z.ZodOptional; + jwks_uri: z.ZodURL; + registration_endpoint: z.ZodOptional; + scopes_supported: z.ZodOptional>; + response_types_supported: z.ZodArray; + response_modes_supported: z.ZodOptional>; + grant_types_supported: z.ZodOptional>; + acr_values_supported: z.ZodOptional>; + subject_types_supported: z.ZodArray; + id_token_signing_alg_values_supported: z.ZodArray; + id_token_encryption_alg_values_supported: z.ZodOptional>; + id_token_encryption_enc_values_supported: z.ZodOptional>; + userinfo_signing_alg_values_supported: z.ZodOptional>; + userinfo_encryption_alg_values_supported: z.ZodOptional>; + userinfo_encryption_enc_values_supported: z.ZodOptional>; + request_object_signing_alg_values_supported: z.ZodOptional>; + request_object_encryption_alg_values_supported: z.ZodOptional>; + request_object_encryption_enc_values_supported: z.ZodOptional>; + token_endpoint_auth_methods_supported: z.ZodOptional>; + token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + display_values_supported: z.ZodOptional>; + claim_types_supported: z.ZodOptional>; + claims_supported: z.ZodOptional>; + service_documentation: z.ZodOptional; + claims_locales_supported: z.ZodOptional>; + ui_locales_supported: z.ZodOptional>; + claims_parameter_supported: z.ZodOptional; + request_parameter_supported: z.ZodOptional; + request_uri_parameter_supported: z.ZodOptional; + require_request_uri_registration: z.ZodOptional; + op_policy_uri: z.ZodOptional; + op_tos_uri: z.ZodOptional; + client_id_metadata_document_supported: z.ZodOptional; +}, z.core.$strip>; +/** + * OAuth 2.1 token response + */ +export declare const OAuthTokensSchema: z.ZodObject<{ + access_token: z.ZodString; + id_token: z.ZodOptional; + token_type: z.ZodString; + expires_in: z.ZodOptional; + scope: z.ZodOptional; + refresh_token: z.ZodOptional; +}, z.core.$strip>; +/** + * OAuth 2.1 error response + */ +export declare const OAuthErrorResponseSchema: z.ZodObject<{ + error: z.ZodString; + error_description: z.ZodOptional; + error_uri: z.ZodOptional; +}, z.core.$strip>; +/** + * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri + */ +export declare const OptionalSafeUrlSchema: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata + */ +export declare const OAuthClientMetadataSchema: z.ZodObject<{ + redirect_uris: z.ZodArray; + token_endpoint_auth_method: z.ZodOptional; + grant_types: z.ZodOptional>; + response_types: z.ZodOptional>; + client_name: z.ZodOptional; + client_uri: z.ZodOptional; + logo_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + scope: z.ZodOptional; + contacts: z.ZodOptional>; + tos_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + policy_uri: z.ZodOptional; + jwks_uri: z.ZodOptional; + jwks: z.ZodOptional; + software_id: z.ZodOptional; + software_version: z.ZodOptional; + software_statement: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration client information + */ +export declare const OAuthClientInformationSchema: z.ZodObject<{ + client_id: z.ZodString; + client_secret: z.ZodOptional; + client_id_issued_at: z.ZodOptional; + client_secret_expires_at: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) + */ +export declare const OAuthClientInformationFullSchema: z.ZodObject<{ + redirect_uris: z.ZodArray; + token_endpoint_auth_method: z.ZodOptional; + grant_types: z.ZodOptional>; + response_types: z.ZodOptional>; + client_name: z.ZodOptional; + client_uri: z.ZodOptional; + logo_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + scope: z.ZodOptional; + contacts: z.ZodOptional>; + tos_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + policy_uri: z.ZodOptional; + jwks_uri: z.ZodOptional; + jwks: z.ZodOptional; + software_id: z.ZodOptional; + software_version: z.ZodOptional; + software_statement: z.ZodOptional; + client_id: z.ZodString; + client_secret: z.ZodOptional; + client_id_issued_at: z.ZodOptional; + client_secret_expires_at: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration error response + */ +export declare const OAuthClientRegistrationErrorSchema: z.ZodObject<{ + error: z.ZodString; + error_description: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7009 OAuth 2.0 Token Revocation request + */ +export declare const OAuthTokenRevocationRequestSchema: z.ZodObject<{ + token: z.ZodString; + token_type_hint: z.ZodOptional; +}, z.core.$strip>; +export type OAuthMetadata = z.infer; +export type OpenIdProviderMetadata = z.infer; +export type OpenIdProviderDiscoveryMetadata = z.infer; +export type OAuthTokens = z.infer; +export type OAuthErrorResponse = z.infer; +export type OAuthClientMetadata = z.infer; +export type OAuthClientInformation = z.infer; +export type OAuthClientInformationFull = z.infer; +export type OAuthClientInformationMixed = OAuthClientInformation | OAuthClientInformationFull; +export type OAuthClientRegistrationError = z.infer; +export type OAuthTokenRevocationRequest = z.infer; +export type OAuthProtectedResourceMetadata = z.infer; +export type AuthorizationServerMetadata = OAuthMetadata | OpenIdProviderDiscoveryMetadata; +//# sourceMappingURL=auth.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/auth.d.ts.map b/dist/cjs/shared/auth.d.ts.map new file mode 100644 index 0000000000..031a88fb92 --- /dev/null +++ b/dist/cjs/shared/auth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/shared/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B;;GAEG;AACH,eAAO,MAAM,aAAa,UAmBrB,CAAC;AAEN;;GAEG;AACH,eAAO,MAAM,oCAAoC;;;;;;;;;;;;;;;iBAe/C,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;iBAoB9B,CAAC;AAEH;;;GAGG;AACH,eAAO,MAAM,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAqCvC,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,qCAAqC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAKhD,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,iBAAiB;;;;;;;iBASlB,CAAC;AAEb;;GAEG;AACH,eAAO,MAAM,wBAAwB;;;;iBAInC,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,qBAAqB,mGAAwE,CAAC;AAE3G;;GAEG;AACH,eAAO,MAAM,yBAAyB;;;;;;;;;;;;;;;;;iBAmB1B,CAAC;AAEb;;GAEG;AACH,eAAO,MAAM,4BAA4B;;;;;iBAO7B,CAAC;AAEb;;GAEG;AACH,eAAO,MAAM,gCAAgC;;;;;;;;;;;;;;;;;;;;;iBAAgE,CAAC;AAE9G;;GAEG;AACH,eAAO,MAAM,kCAAkC;;;iBAKnC,CAAC;AAEb;;GAEG;AACH,eAAO,MAAM,iCAAiC;;;iBAKlC,CAAC;AAEb,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAChE,MAAM,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,4BAA4B,CAAC,CAAC;AAClF,MAAM,MAAM,+BAA+B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qCAAqC,CAAC,CAAC;AAEpG,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAC5D,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;AAC1E,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,yBAAyB,CAAC,CAAC;AAC5E,MAAM,MAAM,sBAAsB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,4BAA4B,CAAC,CAAC;AAClF,MAAM,MAAM,0BAA0B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,gCAAgC,CAAC,CAAC;AAC1F,MAAM,MAAM,2BAA2B,GAAG,sBAAsB,GAAG,0BAA0B,CAAC;AAC9F,MAAM,MAAM,4BAA4B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kCAAkC,CAAC,CAAC;AAC9F,MAAM,MAAM,2BAA2B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iCAAiC,CAAC,CAAC;AAC5F,MAAM,MAAM,8BAA8B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oCAAoC,CAAC,CAAC;AAGlG,MAAM,MAAM,2BAA2B,GAAG,aAAa,GAAG,+BAA+B,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/auth.js b/dist/cjs/shared/auth.js new file mode 100644 index 0000000000..a3bcf877bd --- /dev/null +++ b/dist/cjs/shared/auth.js @@ -0,0 +1,224 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OAuthTokenRevocationRequestSchema = exports.OAuthClientRegistrationErrorSchema = exports.OAuthClientInformationFullSchema = exports.OAuthClientInformationSchema = exports.OAuthClientMetadataSchema = exports.OptionalSafeUrlSchema = exports.OAuthErrorResponseSchema = exports.OAuthTokensSchema = exports.OpenIdProviderDiscoveryMetadataSchema = exports.OpenIdProviderMetadataSchema = exports.OAuthMetadataSchema = exports.OAuthProtectedResourceMetadataSchema = exports.SafeUrlSchema = void 0; +const z = __importStar(require("zod/v4")); +/** + * Reusable URL validation that disallows javascript: scheme + */ +exports.SafeUrlSchema = z + .url() + .superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'URL must be parseable', + fatal: true + }); + return z.NEVER; + } +}) + .refine(url => { + const u = new URL(url); + return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:'; +}, { message: 'URL cannot use javascript:, data:, or vbscript: scheme' }); +/** + * RFC 9728 OAuth Protected Resource Metadata + */ +exports.OAuthProtectedResourceMetadataSchema = z.looseObject({ + resource: z.string().url(), + authorization_servers: z.array(exports.SafeUrlSchema).optional(), + jwks_uri: z.string().url().optional(), + scopes_supported: z.array(z.string()).optional(), + bearer_methods_supported: z.array(z.string()).optional(), + resource_signing_alg_values_supported: z.array(z.string()).optional(), + resource_name: z.string().optional(), + resource_documentation: z.string().optional(), + resource_policy_uri: z.string().url().optional(), + resource_tos_uri: z.string().url().optional(), + tls_client_certificate_bound_access_tokens: z.boolean().optional(), + authorization_details_types_supported: z.array(z.string()).optional(), + dpop_signing_alg_values_supported: z.array(z.string()).optional(), + dpop_bound_access_tokens_required: z.boolean().optional() +}); +/** + * RFC 8414 OAuth 2.0 Authorization Server Metadata + */ +exports.OAuthMetadataSchema = z.looseObject({ + issuer: z.string(), + authorization_endpoint: exports.SafeUrlSchema, + token_endpoint: exports.SafeUrlSchema, + registration_endpoint: exports.SafeUrlSchema.optional(), + scopes_supported: z.array(z.string()).optional(), + response_types_supported: z.array(z.string()), + response_modes_supported: z.array(z.string()).optional(), + grant_types_supported: z.array(z.string()).optional(), + token_endpoint_auth_methods_supported: z.array(z.string()).optional(), + token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + service_documentation: exports.SafeUrlSchema.optional(), + revocation_endpoint: exports.SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + introspection_endpoint: z.string().optional(), + introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + code_challenge_methods_supported: z.array(z.string()).optional(), + client_id_metadata_document_supported: z.boolean().optional() +}); +/** + * OpenID Connect Discovery 1.0 Provider Metadata + * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata + */ +exports.OpenIdProviderMetadataSchema = z.looseObject({ + issuer: z.string(), + authorization_endpoint: exports.SafeUrlSchema, + token_endpoint: exports.SafeUrlSchema, + userinfo_endpoint: exports.SafeUrlSchema.optional(), + jwks_uri: exports.SafeUrlSchema, + registration_endpoint: exports.SafeUrlSchema.optional(), + scopes_supported: z.array(z.string()).optional(), + response_types_supported: z.array(z.string()), + response_modes_supported: z.array(z.string()).optional(), + grant_types_supported: z.array(z.string()).optional(), + acr_values_supported: z.array(z.string()).optional(), + subject_types_supported: z.array(z.string()), + id_token_signing_alg_values_supported: z.array(z.string()), + id_token_encryption_alg_values_supported: z.array(z.string()).optional(), + id_token_encryption_enc_values_supported: z.array(z.string()).optional(), + userinfo_signing_alg_values_supported: z.array(z.string()).optional(), + userinfo_encryption_alg_values_supported: z.array(z.string()).optional(), + userinfo_encryption_enc_values_supported: z.array(z.string()).optional(), + request_object_signing_alg_values_supported: z.array(z.string()).optional(), + request_object_encryption_alg_values_supported: z.array(z.string()).optional(), + request_object_encryption_enc_values_supported: z.array(z.string()).optional(), + token_endpoint_auth_methods_supported: z.array(z.string()).optional(), + token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + display_values_supported: z.array(z.string()).optional(), + claim_types_supported: z.array(z.string()).optional(), + claims_supported: z.array(z.string()).optional(), + service_documentation: z.string().optional(), + claims_locales_supported: z.array(z.string()).optional(), + ui_locales_supported: z.array(z.string()).optional(), + claims_parameter_supported: z.boolean().optional(), + request_parameter_supported: z.boolean().optional(), + request_uri_parameter_supported: z.boolean().optional(), + require_request_uri_registration: z.boolean().optional(), + op_policy_uri: exports.SafeUrlSchema.optional(), + op_tos_uri: exports.SafeUrlSchema.optional(), + client_id_metadata_document_supported: z.boolean().optional() +}); +/** + * OpenID Connect Discovery metadata that may include OAuth 2.0 fields + * This schema represents the real-world scenario where OIDC providers + * return a mix of OpenID Connect and OAuth 2.0 metadata fields + */ +exports.OpenIdProviderDiscoveryMetadataSchema = z.object({ + ...exports.OpenIdProviderMetadataSchema.shape, + ...exports.OAuthMetadataSchema.pick({ + code_challenge_methods_supported: true + }).shape +}); +/** + * OAuth 2.1 token response + */ +exports.OAuthTokensSchema = z + .object({ + access_token: z.string(), + id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect + token_type: z.string(), + expires_in: z.number().optional(), + scope: z.string().optional(), + refresh_token: z.string().optional() +}) + .strip(); +/** + * OAuth 2.1 error response + */ +exports.OAuthErrorResponseSchema = z.object({ + error: z.string(), + error_description: z.string().optional(), + error_uri: z.string().optional() +}); +/** + * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri + */ +exports.OptionalSafeUrlSchema = exports.SafeUrlSchema.optional().or(z.literal('').transform(() => undefined)); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata + */ +exports.OAuthClientMetadataSchema = z + .object({ + redirect_uris: z.array(exports.SafeUrlSchema), + token_endpoint_auth_method: z.string().optional(), + grant_types: z.array(z.string()).optional(), + response_types: z.array(z.string()).optional(), + client_name: z.string().optional(), + client_uri: exports.SafeUrlSchema.optional(), + logo_uri: exports.OptionalSafeUrlSchema, + scope: z.string().optional(), + contacts: z.array(z.string()).optional(), + tos_uri: exports.OptionalSafeUrlSchema, + policy_uri: z.string().optional(), + jwks_uri: exports.SafeUrlSchema.optional(), + jwks: z.any().optional(), + software_id: z.string().optional(), + software_version: z.string().optional(), + software_statement: z.string().optional() +}) + .strip(); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration client information + */ +exports.OAuthClientInformationSchema = z + .object({ + client_id: z.string(), + client_secret: z.string().optional(), + client_id_issued_at: z.number().optional(), + client_secret_expires_at: z.number().optional() +}) + .strip(); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) + */ +exports.OAuthClientInformationFullSchema = exports.OAuthClientMetadataSchema.merge(exports.OAuthClientInformationSchema); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration error response + */ +exports.OAuthClientRegistrationErrorSchema = z + .object({ + error: z.string(), + error_description: z.string().optional() +}) + .strip(); +/** + * RFC 7009 OAuth 2.0 Token Revocation request + */ +exports.OAuthTokenRevocationRequestSchema = z + .object({ + token: z.string(), + token_type_hint: z.string().optional() +}) + .strip(); +//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/dist/cjs/shared/auth.js.map b/dist/cjs/shared/auth.js.map new file mode 100644 index 0000000000..fda5b3ed9d --- /dev/null +++ b/dist/cjs/shared/auth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/shared/auth.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAA4B;AAE5B;;GAEG;AACU,QAAA,aAAa,GAAG,CAAC;KACzB,GAAG,EAAE;KACL,WAAW,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;IACtB,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACrB,GAAG,CAAC,QAAQ,CAAC;YACT,IAAI,EAAE,CAAC,CAAC,YAAY,CAAC,MAAM;YAC3B,OAAO,EAAE,uBAAuB;YAChC,KAAK,EAAE,IAAI;SACd,CAAC,CAAC;QAEH,OAAO,CAAC,CAAC,KAAK,CAAC;IACnB,CAAC;AACL,CAAC,CAAC;KACD,MAAM,CACH,GAAG,CAAC,EAAE;IACF,MAAM,CAAC,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;IACvB,OAAO,CAAC,CAAC,QAAQ,KAAK,aAAa,IAAI,CAAC,CAAC,QAAQ,KAAK,OAAO,IAAI,CAAC,CAAC,QAAQ,KAAK,WAAW,CAAC;AAChG,CAAC,EACD,EAAE,OAAO,EAAE,wDAAwD,EAAE,CACxE,CAAC;AAEN;;GAEG;AACU,QAAA,oCAAoC,GAAG,CAAC,CAAC,WAAW,CAAC;IAC9D,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE;IAC1B,qBAAqB,EAAE,CAAC,CAAC,KAAK,CAAC,qBAAa,CAAC,CAAC,QAAQ,EAAE;IACxD,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE;IACrC,gBAAgB,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC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E,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IACpC,mBAAmB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC1C,wBAAwB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CAClD,CAAC;KACD,KAAK,EAAE,CAAC;AAEb;;GAEG;AACU,QAAA,gCAAgC,GAAG,iCAAyB,CAAC,KAAK,CAAC,oCAA4B,CAAC,CAAC;AAE9G;;GAEG;AACU,QAAA,kCAAkC,GAAG,CAAC;KAC9C,MAAM,CAAC;IACJ,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE;IACjB,iBAAiB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CAC3C,CAAC;KACD,KAAK,EAAE,CAAC;AAEb;;GAEG;AACU,QAAA,iCAAiC,GAAG,CAAC;KAC7C,MAAM,CAAC;IACJ,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE;IACjB,eAAe,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACzC,CAAC;KACD,KAAK,EAAE,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/metadataUtils.d.ts b/dist/cjs/shared/metadataUtils.d.ts new file mode 100644 index 0000000000..c0e738bab0 --- /dev/null +++ b/dist/cjs/shared/metadataUtils.d.ts @@ -0,0 +1,16 @@ +import { BaseMetadata } from '../types.js'; +/** + * Utilities for working with BaseMetadata objects. + */ +/** + * Gets the display name for an object with BaseMetadata. + * For tools, the precedence is: title → annotations.title → name + * For other objects: title → name + * This implements the spec requirement: "if no title is provided, name should be used for display purposes" + */ +export declare function getDisplayName(metadata: BaseMetadata & { + annotations?: { + title?: string; + }; +}): string; +//# sourceMappingURL=metadataUtils.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/metadataUtils.d.ts.map b/dist/cjs/shared/metadataUtils.d.ts.map new file mode 100644 index 0000000000..596805eb34 --- /dev/null +++ b/dist/cjs/shared/metadataUtils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"metadataUtils.d.ts","sourceRoot":"","sources":["../../../src/shared/metadataUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C;;GAEG;AAEH;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,YAAY,GAAG;IAAE,WAAW,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,GAAG,MAAM,CAapG"} \ No newline at end of file diff --git a/dist/cjs/shared/metadataUtils.js b/dist/cjs/shared/metadataUtils.js new file mode 100644 index 0000000000..07e8ec4c4e --- /dev/null +++ b/dist/cjs/shared/metadataUtils.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getDisplayName = getDisplayName; +/** + * Utilities for working with BaseMetadata objects. + */ +/** + * Gets the display name for an object with BaseMetadata. + * For tools, the precedence is: title → annotations.title → name + * For other objects: title → name + * This implements the spec requirement: "if no title is provided, name should be used for display purposes" + */ +function getDisplayName(metadata) { + var _a; + // First check for title (not undefined and not empty string) + if (metadata.title !== undefined && metadata.title !== '') { + return metadata.title; + } + // Then check for annotations.title (only present in Tool objects) + if ((_a = metadata.annotations) === null || _a === void 0 ? void 0 : _a.title) { + return metadata.annotations.title; + } + // Finally fall back to name + return metadata.name; +} +//# sourceMappingURL=metadataUtils.js.map \ No newline at end of file diff --git a/dist/cjs/shared/metadataUtils.js.map b/dist/cjs/shared/metadataUtils.js.map new file mode 100644 index 0000000000..e9e9cc69e1 --- /dev/null +++ b/dist/cjs/shared/metadataUtils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metadataUtils.js","sourceRoot":"","sources":["../../../src/shared/metadataUtils.ts"],"names":[],"mappings":";;AAYA,wCAaC;AAvBD;;GAEG;AAEH;;;;;GAKG;AACH,SAAgB,cAAc,CAAC,QAA6D;;IACxF,6DAA6D;IAC7D,IAAI,QAAQ,CAAC,KAAK,KAAK,SAAS,IAAI,QAAQ,CAAC,KAAK,KAAK,EAAE,EAAE,CAAC;QACxD,OAAO,QAAQ,CAAC,KAAK,CAAC;IAC1B,CAAC;IAED,kEAAkE;IAClE,IAAI,MAAA,QAAQ,CAAC,WAAW,0CAAE,KAAK,EAAE,CAAC;QAC9B,OAAO,QAAQ,CAAC,WAAW,CAAC,KAAK,CAAC;IACtC,CAAC;IAED,4BAA4B;IAC5B,OAAO,QAAQ,CAAC,IAAI,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/protocol.d.ts b/dist/cjs/shared/protocol.d.ts new file mode 100644 index 0000000000..fb23686184 --- /dev/null +++ b/dist/cjs/shared/protocol.d.ts @@ -0,0 +1,226 @@ +import { AnySchema, AnyObjectSchema, SchemaOutput } from '../server/zod-compat.js'; +import { ClientCapabilities, JSONRPCRequest, Notification, Progress, Request, RequestId, Result, ServerCapabilities, RequestMeta, RequestInfo } from '../types.js'; +import { Transport, TransportSendOptions } from './transport.js'; +import { AuthInfo } from '../server/auth/types.js'; +/** + * Callback for progress notifications. + */ +export type ProgressCallback = (progress: Progress) => void; +/** + * Additional initialization options. + */ +export type ProtocolOptions = { + /** + * Whether to restrict emitted requests to only those that the remote side has indicated that they can handle, through their advertised capabilities. + * + * Note that this DOES NOT affect checking of _local_ side capabilities, as it is considered a logic error to mis-specify those. + * + * Currently this defaults to false, for backwards compatibility with SDK versions that did not advertise capabilities correctly. In future, this will default to true. + */ + enforceStrictCapabilities?: boolean; + /** + * An array of notification method names that should be automatically debounced. + * Any notifications with a method in this list will be coalesced if they + * occur in the same tick of the event loop. + * e.g., ['notifications/tools/list_changed'] + */ + debouncedNotificationMethods?: string[]; +}; +/** + * The default request timeout, in miliseconds. + */ +export declare const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; +/** + * Options that can be given per request. + */ +export type RequestOptions = { + /** + * If set, requests progress notifications from the remote end (if supported). When progress notifications are received, this callback will be invoked. + */ + onprogress?: ProgressCallback; + /** + * Can be used to cancel an in-flight request. This will cause an AbortError to be raised from request(). + */ + signal?: AbortSignal; + /** + * A timeout (in milliseconds) for this request. If exceeded, an McpError with code `RequestTimeout` will be raised from request(). + * + * If not specified, `DEFAULT_REQUEST_TIMEOUT_MSEC` will be used as the timeout. + */ + timeout?: number; + /** + * If true, receiving a progress notification will reset the request timeout. + * This is useful for long-running operations that send periodic progress updates. + * Default: false + */ + resetTimeoutOnProgress?: boolean; + /** + * Maximum total time (in milliseconds) to wait for a response. + * If exceeded, an McpError with code `RequestTimeout` will be raised, regardless of progress notifications. + * If not specified, there is no maximum total timeout. + */ + maxTotalTimeout?: number; +} & TransportSendOptions; +/** + * Options that can be given per notification. + */ +export type NotificationOptions = { + /** + * May be used to indicate to the transport which incoming request to associate this outgoing notification with. + */ + relatedRequestId?: RequestId; +}; +/** + * Extra data given to request handlers. + */ +export type RequestHandlerExtra = { + /** + * An abort signal used to communicate if the request was cancelled from the sender's side. + */ + signal: AbortSignal; + /** + * Information about a validated access token, provided to request handlers. + */ + authInfo?: AuthInfo; + /** + * The session ID from the transport, if available. + */ + sessionId?: string; + /** + * Metadata from the original request. + */ + _meta?: RequestMeta; + /** + * The JSON-RPC ID of the request being handled. + * This can be useful for tracking or logging purposes. + */ + requestId: RequestId; + /** + * The original HTTP request. + */ + requestInfo?: RequestInfo; + /** + * Sends a notification that relates to the current request being handled. + * + * This is used by certain transports to correctly associate related messages. + */ + sendNotification: (notification: SendNotificationT) => Promise; + /** + * Sends a request that relates to the current request being handled. + * + * This is used by certain transports to correctly associate related messages. + */ + sendRequest: (request: SendRequestT, resultSchema: U, options?: RequestOptions) => Promise>; +}; +/** + * Implements MCP protocol framing on top of a pluggable transport, including + * features like request/response linking, notifications, and progress. + */ +export declare abstract class Protocol { + private _options?; + private _transport?; + private _requestMessageId; + private _requestHandlers; + private _requestHandlerAbortControllers; + private _notificationHandlers; + private _responseHandlers; + private _progressHandlers; + private _timeoutInfo; + private _pendingDebouncedNotifications; + /** + * Callback for when the connection is closed for any reason. + * + * This is invoked when close() is called as well. + */ + onclose?: () => void; + /** + * Callback for when an error occurs. + * + * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. + */ + onerror?: (error: Error) => void; + /** + * A handler to invoke for any request types that do not have their own handler installed. + */ + fallbackRequestHandler?: (request: JSONRPCRequest, extra: RequestHandlerExtra) => Promise; + /** + * A handler to invoke for any notification types that do not have their own handler installed. + */ + fallbackNotificationHandler?: (notification: Notification) => Promise; + constructor(_options?: ProtocolOptions | undefined); + private _setupTimeout; + private _resetTimeout; + private _cleanupTimeout; + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + connect(transport: Transport): Promise; + private _onclose; + private _onerror; + private _onnotification; + private _onrequest; + private _onprogress; + private _onresponse; + get transport(): Transport | undefined; + /** + * Closes the connection. + */ + close(): Promise; + /** + * A method to check if a capability is supported by the remote side, for the given method to be called. + * + * This should be implemented by subclasses. + */ + protected abstract assertCapabilityForMethod(method: SendRequestT['method']): void; + /** + * A method to check if a notification is supported by the local side, for the given method to be sent. + * + * This should be implemented by subclasses. + */ + protected abstract assertNotificationCapability(method: SendNotificationT['method']): void; + /** + * A method to check if a request handler is supported by the local side, for the given method to be handled. + * + * This should be implemented by subclasses. + */ + protected abstract assertRequestHandlerCapability(method: string): void; + /** + * Sends a request and wait for a response. + * + * Do not use this method to emit notifications! Use notification() instead. + */ + request(request: SendRequestT, resultSchema: T, options?: RequestOptions): Promise>; + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + notification(notification: SendNotificationT, options?: NotificationOptions): Promise; + /** + * Registers a handler to invoke when this protocol object receives a request with the given method. + * + * Note that this will replace any previous request handler for the same method. + */ + setRequestHandler(requestSchema: T, handler: (request: SchemaOutput, extra: RequestHandlerExtra) => SendResultT | Promise): void; + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method: string): void; + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method: string): void; + /** + * Registers a handler to invoke when this protocol object receives a notification with the given method. + * + * Note that this will replace any previous notification handler for the same method. + */ + setNotificationHandler(notificationSchema: T, handler: (notification: SchemaOutput) => void | Promise): void; + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method: string): void; +} +export declare function mergeCapabilities(base: ServerCapabilities, additional: Partial): ServerCapabilities; +export declare function mergeCapabilities(base: ClientCapabilities, additional: Partial): ClientCapabilities; +//# sourceMappingURL=protocol.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/protocol.d.ts.map b/dist/cjs/shared/protocol.d.ts.map new file mode 100644 index 0000000000..4aa2bd57cb --- /dev/null +++ b/dist/cjs/shared/protocol.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../../../src/shared/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,YAAY,EAAa,MAAM,yBAAyB,CAAC;AAC9F,OAAO,EAEH,kBAAkB,EAQlB,cAAc,EAGd,YAAY,EAEZ,QAAQ,EAGR,OAAO,EACP,SAAS,EACT,MAAM,EACN,kBAAkB,EAClB,WAAW,EAEX,WAAW,EACd,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AAGnD;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,QAAQ,EAAE,QAAQ,KAAK,IAAI,CAAC;AAE5D;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG;IAC1B;;;;;;OAMG;IACH,yBAAyB,CAAC,EAAE,OAAO,CAAC;IACpC;;;;;OAKG;IACH,4BAA4B,CAAC,EAAE,MAAM,EAAE,CAAC;CAC3C,CAAC;AAEF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M,GAAG,IAAI;CAGlD;AAMD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,kBAAkB,CAAC;AACzH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,kBAAkB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/protocol.js b/dist/cjs/shared/protocol.js new file mode 100644 index 0000000000..c684b8bd72 --- /dev/null +++ b/dist/cjs/shared/protocol.js @@ -0,0 +1,442 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Protocol = exports.DEFAULT_REQUEST_TIMEOUT_MSEC = void 0; +exports.mergeCapabilities = mergeCapabilities; +const zod_compat_js_1 = require("../server/zod-compat.js"); +const types_js_1 = require("../types.js"); +const zod_json_schema_compat_js_1 = require("../server/zod-json-schema-compat.js"); +/** + * The default request timeout, in miliseconds. + */ +exports.DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; +/** + * Implements MCP protocol framing on top of a pluggable transport, including + * features like request/response linking, notifications, and progress. + */ +class Protocol { + constructor(_options) { + this._options = _options; + this._requestMessageId = 0; + this._requestHandlers = new Map(); + this._requestHandlerAbortControllers = new Map(); + this._notificationHandlers = new Map(); + this._responseHandlers = new Map(); + this._progressHandlers = new Map(); + this._timeoutInfo = new Map(); + this._pendingDebouncedNotifications = new Set(); + this.setNotificationHandler(types_js_1.CancelledNotificationSchema, notification => { + const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); + controller === null || controller === void 0 ? void 0 : controller.abort(notification.params.reason); + }); + this.setNotificationHandler(types_js_1.ProgressNotificationSchema, notification => { + this._onprogress(notification); + }); + this.setRequestHandler(types_js_1.PingRequestSchema, + // Automatic pong by default. + _request => ({})); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) + return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw types_js_1.McpError.fromError(types_js_1.ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; + } + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + async connect(transport) { + var _a, _b, _c; + this._transport = transport; + const _onclose = (_a = this.transport) === null || _a === void 0 ? void 0 : _a.onclose; + this._transport.onclose = () => { + _onclose === null || _onclose === void 0 ? void 0 : _onclose(); + this._onclose(); + }; + const _onerror = (_b = this.transport) === null || _b === void 0 ? void 0 : _b.onerror; + this._transport.onerror = (error) => { + _onerror === null || _onerror === void 0 ? void 0 : _onerror(error); + this._onerror(error); + }; + const _onmessage = (_c = this._transport) === null || _c === void 0 ? void 0 : _c.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage === null || _onmessage === void 0 ? void 0 : _onmessage(message, extra); + if ((0, types_js_1.isJSONRPCResponse)(message) || (0, types_js_1.isJSONRPCError)(message)) { + this._onresponse(message); + } + else if ((0, types_js_1.isJSONRPCRequest)(message)) { + this._onrequest(message, extra); + } + else if ((0, types_js_1.isJSONRPCNotification)(message)) { + this._onnotification(message); + } + else { + this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); + } + }; + await this._transport.start(); + } + _onclose() { + var _a; + const responseHandlers = this._responseHandlers; + this._responseHandlers = new Map(); + this._progressHandlers.clear(); + this._pendingDebouncedNotifications.clear(); + this._transport = undefined; + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + const error = types_js_1.McpError.fromError(types_js_1.ErrorCode.ConnectionClosed, 'Connection closed'); + for (const handler of responseHandlers.values()) { + handler(error); + } + } + _onerror(error) { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + } + _onnotification(notification) { + var _a; + const handler = (_a = this._notificationHandlers.get(notification.method)) !== null && _a !== void 0 ? _a : this.fallbackNotificationHandler; + // Ignore notifications not being subscribed to. + if (handler === undefined) { + return; + } + // Starting with Promise.resolve() puts any synchronous errors into the monad as well. + Promise.resolve() + .then(() => handler(notification)) + .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`))); + } + _onrequest(request, extra) { + var _a, _b; + const handler = (_a = this._requestHandlers.get(request.method)) !== null && _a !== void 0 ? _a : this.fallbackRequestHandler; + // Capture the current transport at request time to ensure responses go to the correct client + const capturedTransport = this._transport; + if (handler === undefined) { + capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({ + jsonrpc: '2.0', + id: request.id, + error: { + code: types_js_1.ErrorCode.MethodNotFound, + message: 'Method not found' + } + }).catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`))); + return; + } + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const fullExtra = { + signal: abortController.signal, + sessionId: capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId, + _meta: (_b = request.params) === null || _b === void 0 ? void 0 : _b._meta, + sendNotification: notification => this.notification(notification, { relatedRequestId: request.id }), + sendRequest: (r, resultSchema, options) => this.request(r, resultSchema, { ...options, relatedRequestId: request.id }), + authInfo: extra === null || extra === void 0 ? void 0 : extra.authInfo, + requestId: request.id, + requestInfo: extra === null || extra === void 0 ? void 0 : extra.requestInfo + }; + // Starting with Promise.resolve() puts any synchronous errors into the monad as well. + Promise.resolve() + .then(() => handler(request, fullExtra)) + .then(result => { + if (abortController.signal.aborted) { + return; + } + return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({ + result, + jsonrpc: '2.0', + id: request.id + }); + }, error => { + var _a; + if (abortController.signal.aborted) { + return; + } + return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({ + jsonrpc: '2.0', + id: request.id, + error: { + code: Number.isSafeInteger(error['code']) ? error['code'] : types_js_1.ErrorCode.InternalError, + message: (_a = error.message) !== null && _a !== void 0 ? _a : 'Internal error', + ...(error['data'] !== undefined && { data: error['data'] }) + } + }); + }) + .catch(error => this._onerror(new Error(`Failed to send response: ${error}`))) + .finally(() => { + this._requestHandlerAbortControllers.delete(request.id); + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { + try { + this._resetTimeout(messageId); + } + catch (error) { + responseHandler(error); + return; + } + } + handler(params); + } + _onresponse(response) { + const messageId = Number(response.id); + const handler = this._responseHandlers.get(messageId); + if (handler === undefined) { + this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + if ((0, types_js_1.isJSONRPCResponse)(response)) { + handler(response); + } + else { + const error = types_js_1.McpError.fromError(response.error.code, response.error.message, response.error.data); + handler(error); + } + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + var _a; + await ((_a = this._transport) === null || _a === void 0 ? void 0 : _a.close()); + } + /** + * Sends a request and wait for a response. + * + * Do not use this method to emit notifications! Use notification() instead. + */ + request(request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken } = options !== null && options !== void 0 ? options : {}; + return new Promise((resolve, reject) => { + var _a, _b, _c, _d, _e, _f; + if (!this._transport) { + reject(new Error('Not connected')); + return; + } + if (((_a = this._options) === null || _a === void 0 ? void 0 : _a.enforceStrictCapabilities) === true) { + this.assertCapabilityForMethod(request.method); + } + (_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.throwIfAborted(); + const messageId = this._requestMessageId++; + const jsonrpcRequest = { + ...request, + jsonrpc: '2.0', + id: messageId + }; + if (options === null || options === void 0 ? void 0 : options.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...(((_c = request.params) === null || _c === void 0 ? void 0 : _c._meta) || {}), + progressToken: messageId + } + }; + } + const cancel = (reason) => { + var _a; + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + (_a = this._transport) === null || _a === void 0 ? void 0 : _a.send({ + jsonrpc: '2.0', + method: 'notifications/cancelled', + params: { + requestId: messageId, + reason: String(reason) + } + }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`))); + reject(reason); + }; + this._responseHandlers.set(messageId, response => { + var _a; + if ((_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.aborted) { + return; + } + if (response instanceof Error) { + return reject(response); + } + try { + const parseResult = (0, zod_compat_js_1.safeParse)(resultSchema, response.result); + if (!parseResult.success) { + // Type guard: if success is false, error is guaranteed to exist + reject(parseResult.error); + } + else { + resolve(parseResult.data); + } + } + catch (error) { + reject(error); + } + }); + (_d = options === null || options === void 0 ? void 0 : options.signal) === null || _d === void 0 ? void 0 : _d.addEventListener('abort', () => { + var _a; + cancel((_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.reason); + }); + const timeout = (_e = options === null || options === void 0 ? void 0 : options.timeout) !== null && _e !== void 0 ? _e : exports.DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(types_js_1.McpError.fromError(types_js_1.ErrorCode.RequestTimeout, 'Request timed out', { timeout })); + this._setupTimeout(messageId, timeout, options === null || options === void 0 ? void 0 : options.maxTotalTimeout, timeoutHandler, (_f = options === null || options === void 0 ? void 0 : options.resetTimeoutOnProgress) !== null && _f !== void 0 ? _f : false); + this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => { + this._cleanupTimeout(messageId); + reject(error); + }); + }); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + var _a, _b; + if (!this._transport) { + throw new Error('Not connected'); + } + this.assertNotificationCapability(notification.method); + const debouncedMethods = (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.debouncedNotificationMethods) !== null && _b !== void 0 ? _b : []; + // A notification can only be debounced if it's in the list AND it's "simple" + // (i.e., has no parameters and no related request ID that could be lost). + const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !(options === null || options === void 0 ? void 0 : options.relatedRequestId); + if (canDebounce) { + // If a notification of this type is already scheduled, do nothing. + if (this._pendingDebouncedNotifications.has(notification.method)) { + return; + } + // Mark this notification type as pending. + this._pendingDebouncedNotifications.add(notification.method); + // Schedule the actual send to happen in the next microtask. + // This allows all synchronous calls in the current event loop tick to be coalesced. + Promise.resolve().then(() => { + var _a; + // Un-mark the notification so the next one can be scheduled. + this._pendingDebouncedNotifications.delete(notification.method); + // SAFETY CHECK: If the connection was closed while this was pending, abort. + if (!this._transport) { + return; + } + const jsonrpcNotification = { + ...notification, + jsonrpc: '2.0' + }; + // Send the notification, but don't await it here to avoid blocking. + // Handle potential errors with a .catch(). + (_a = this._transport) === null || _a === void 0 ? void 0 : _a.send(jsonrpcNotification, options).catch(error => this._onerror(error)); + }); + // Return immediately. + return; + } + const jsonrpcNotification = { + ...notification, + jsonrpc: '2.0' + }; + await this._transport.send(jsonrpcNotification, options); + } + /** + * Registers a handler to invoke when this protocol object receives a request with the given method. + * + * Note that this will replace any previous request handler for the same method. + */ + setRequestHandler(requestSchema, handler) { + const method = (0, zod_json_schema_compat_js_1.getMethodLiteral)(requestSchema); + this.assertRequestHandlerCapability(method); + this._requestHandlers.set(method, (request, extra) => { + const parsed = (0, zod_json_schema_compat_js_1.parseWithCompat)(requestSchema, request); + return Promise.resolve(handler(parsed, extra)); + }); + } + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) { + throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + } + /** + * Registers a handler to invoke when this protocol object receives a notification with the given method. + * + * Note that this will replace any previous notification handler for the same method. + */ + setNotificationHandler(notificationSchema, handler) { + const method = (0, zod_json_schema_compat_js_1.getMethodLiteral)(notificationSchema); + this._notificationHandlers.set(method, notification => { + const parsed = (0, zod_json_schema_compat_js_1.parseWithCompat)(notificationSchema, notification); + return Promise.resolve(handler(parsed)); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } +} +exports.Protocol = Protocol; +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === undefined) + continue; + const baseValue = result[k]; + if (isPlainObject(baseValue) && isPlainObject(addValue)) { + result[k] = { ...baseValue, ...addValue }; + } + else { + result[k] = addValue; + } + } + return result; +} +//# sourceMappingURL=protocol.js.map \ No newline at end of file diff --git a/dist/cjs/shared/protocol.js.map b/dist/cjs/shared/protocol.js.map new file mode 100644 index 0000000000..3ebb4c7ca0 --- /dev/null +++ b/dist/cjs/shared/protocol.js.map @@ -0,0 +1 @@ +{"version":3,"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c;QACpC,IAAI,CAAC,qBAAqB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC9C,CAAC;CACJ;AA/gBD,4BA+gBC;AAED,SAAS,aAAa,CAAC,KAAc;IACjC,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;AAChF,CAAC;AAID,SAAgB,iBAAiB,CAAoD,IAAO,EAAE,UAAsB;IAChH,MAAM,MAAM,GAAM,EAAE,GAAG,IAAI,EAAE,CAAC;IAC9B,KAAK,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;QAC3B,MAAM,CAAC,GAAG,GAAc,CAAC;QACzB,MAAM,QAAQ,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;QAC/B,IAAI,QAAQ,KAAK,SAAS;YAAE,SAAS;QACrC,MAAM,SAAS,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;QAC5B,IAAI,aAAa,CAAC,SAAS,CAAC,IAAI,aAAa,CAAC,QAAQ,CAAC,EAAE,CAAC;YACtD,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,GAAI,SAAqC,EAAE,GAAI,QAAoC,EAAiB,CAAC;QACvH,CAAC;aAAM,CAAC;YACJ,MAAM,CAAC,CAAC,CAAC,GAAG,QAAuB,CAAC;QACxC,CAAC;IACL,CAAC;IACD,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/stdio.d.ts b/dist/cjs/shared/stdio.d.ts new file mode 100644 index 0000000000..0830a48bc7 --- /dev/null +++ b/dist/cjs/shared/stdio.d.ts @@ -0,0 +1,13 @@ +import { JSONRPCMessage } from '../types.js'; +/** + * Buffers a continuous stdio stream into discrete JSON-RPC messages. + */ +export declare class ReadBuffer { + private _buffer?; + append(chunk: Buffer): void; + readMessage(): JSONRPCMessage | null; + clear(): void; +} +export declare function deserializeMessage(line: string): JSONRPCMessage; +export declare function serializeMessage(message: JSONRPCMessage): string; +//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/stdio.d.ts.map b/dist/cjs/shared/stdio.d.ts.map new file mode 100644 index 0000000000..8f97f2ab10 --- /dev/null +++ b/dist/cjs/shared/stdio.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/shared/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AAEnE;;GAEG;AACH,qBAAa,UAAU;IACnB,OAAO,CAAC,OAAO,CAAC,CAAS;IAEzB,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAI3B,WAAW,IAAI,cAAc,GAAG,IAAI;IAepC,KAAK,IAAI,IAAI;CAGhB;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,CAE/D;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,GAAG,MAAM,CAEhE"} \ No newline at end of file diff --git a/dist/cjs/shared/stdio.js b/dist/cjs/shared/stdio.js new file mode 100644 index 0000000000..540ee56827 --- /dev/null +++ b/dist/cjs/shared/stdio.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ReadBuffer = void 0; +exports.deserializeMessage = deserializeMessage; +exports.serializeMessage = serializeMessage; +const types_js_1 = require("../types.js"); +/** + * Buffers a continuous stdio stream into discrete JSON-RPC messages. + */ +class ReadBuffer { + append(chunk) { + this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; + } + readMessage() { + if (!this._buffer) { + return null; + } + const index = this._buffer.indexOf('\n'); + if (index === -1) { + return null; + } + const line = this._buffer.toString('utf8', 0, index).replace(/\r$/, ''); + this._buffer = this._buffer.subarray(index + 1); + return deserializeMessage(line); + } + clear() { + this._buffer = undefined; + } +} +exports.ReadBuffer = ReadBuffer; +function deserializeMessage(line) { + return types_js_1.JSONRPCMessageSchema.parse(JSON.parse(line)); +} +function serializeMessage(message) { + return JSON.stringify(message) + '\n'; +} +//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/dist/cjs/shared/stdio.js.map b/dist/cjs/shared/stdio.js.map new file mode 100644 index 0000000000..89fbc1a66c --- /dev/null +++ b/dist/cjs/shared/stdio.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/shared/stdio.ts"],"names":[],"mappings":";;;AAgCA,gDAEC;AAED,4CAEC;AAtCD,0CAAmE;AAEnE;;GAEG;AACH,MAAa,UAAU;IAGnB,MAAM,CAAC,KAAa;QAChB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAC/E,CAAC;IAED,WAAW;QACP,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAChB,OAAO,IAAI,CAAC;QAChB,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACzC,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE,CAAC;YACf,OAAO,IAAI,CAAC;QAChB,CAAC;QAED,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACxE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QAChD,OAAO,kBAAkB,CAAC,IAAI,CAAC,CAAC;IACpC,CAAC;IAED,KAAK;QACD,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;IAC7B,CAAC;CACJ;AAzBD,gCAyBC;AAED,SAAgB,kBAAkB,CAAC,IAAY;IAC3C,OAAO,+BAAoB,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;AACxD,CAAC;AAED,SAAgB,gBAAgB,CAAC,OAAuB;IACpD,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;AAC1C,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/toolNameValidation.d.ts b/dist/cjs/shared/toolNameValidation.d.ts new file mode 100644 index 0000000000..3cf94bf78e --- /dev/null +++ b/dist/cjs/shared/toolNameValidation.d.ts @@ -0,0 +1,31 @@ +/** + * Tool name validation utilities according to SEP: Specify Format for Tool Names + * + * Tool names SHOULD be between 1 and 128 characters in length (inclusive). + * Tool names are case-sensitive. + * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits + * (0-9), underscore (_), dash (-), and dot (.). + * Tool names SHOULD NOT contain spaces, commas, or other special characters. + */ +/** + * Validates a tool name according to the SEP specification + * @param name - The tool name to validate + * @returns An object containing validation result and any warnings + */ +export declare function validateToolName(name: string): { + isValid: boolean; + warnings: string[]; +}; +/** + * Issues warnings for non-conforming tool names + * @param name - The tool name that triggered the warnings + * @param warnings - Array of warning messages + */ +export declare function issueToolNameWarning(name: string, warnings: string[]): void; +/** + * Validates a tool name and issues warnings for non-conforming names + * @param name - The tool name to validate + * @returns true if the name is valid, false otherwise + */ +export declare function validateAndWarnToolName(name: string): boolean; +//# sourceMappingURL=toolNameValidation.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/toolNameValidation.d.ts.map b/dist/cjs/shared/toolNameValidation.d.ts.map new file mode 100644 index 0000000000..d81f0156e6 --- /dev/null +++ b/dist/cjs/shared/toolNameValidation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"toolNameValidation.d.ts","sourceRoot":"","sources":["../../../src/shared/toolNameValidation.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAOH;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG;IAC5C,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,MAAM,EAAE,CAAC;CACtB,CA0DA;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,CAY3E;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAO7D"} \ No newline at end of file diff --git a/dist/cjs/shared/toolNameValidation.js b/dist/cjs/shared/toolNameValidation.js new file mode 100644 index 0000000000..cd9d930788 --- /dev/null +++ b/dist/cjs/shared/toolNameValidation.js @@ -0,0 +1,97 @@ +"use strict"; +/** + * Tool name validation utilities according to SEP: Specify Format for Tool Names + * + * Tool names SHOULD be between 1 and 128 characters in length (inclusive). + * Tool names are case-sensitive. + * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits + * (0-9), underscore (_), dash (-), and dot (.). + * Tool names SHOULD NOT contain spaces, commas, or other special characters. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validateToolName = validateToolName; +exports.issueToolNameWarning = issueToolNameWarning; +exports.validateAndWarnToolName = validateAndWarnToolName; +/** + * Regular expression for valid tool names according to SEP-986 specification + */ +const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; +/** + * Validates a tool name according to the SEP specification + * @param name - The tool name to validate + * @returns An object containing validation result and any warnings + */ +function validateToolName(name) { + const warnings = []; + // Check length + if (name.length === 0) { + return { + isValid: false, + warnings: ['Tool name cannot be empty'] + }; + } + if (name.length > 128) { + return { + isValid: false, + warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] + }; + } + // Check for specific problematic patterns (these are warnings, not validation failures) + if (name.includes(' ')) { + warnings.push('Tool name contains spaces, which may cause parsing issues'); + } + if (name.includes(',')) { + warnings.push('Tool name contains commas, which may cause parsing issues'); + } + // Check for potentially confusing patterns (leading/trailing dashes, dots, slashes) + if (name.startsWith('-') || name.endsWith('-')) { + warnings.push('Tool name starts or ends with a dash, which may cause parsing issues in some contexts'); + } + if (name.startsWith('.') || name.endsWith('.')) { + warnings.push('Tool name starts or ends with a dot, which may cause parsing issues in some contexts'); + } + // Check for invalid characters + if (!TOOL_NAME_REGEX.test(name)) { + const invalidChars = name + .split('') + .filter(char => !/[A-Za-z0-9._-]/.test(char)) + .filter((char, index, arr) => arr.indexOf(char) === index); // Remove duplicates + warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c => `"${c}"`).join(', ')}`, 'Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)'); + return { + isValid: false, + warnings + }; + } + return { + isValid: true, + warnings + }; +} +/** + * Issues warnings for non-conforming tool names + * @param name - The tool name that triggered the warnings + * @param warnings - Array of warning messages + */ +function issueToolNameWarning(name, warnings) { + if (warnings.length > 0) { + console.warn(`Tool name validation warning for "${name}":`); + for (const warning of warnings) { + console.warn(` - ${warning}`); + } + console.warn('Tool registration will proceed, but this may cause compatibility issues.'); + console.warn('Consider updating the tool name to conform to the MCP tool naming standard.'); + console.warn('See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.'); + } +} +/** + * Validates a tool name and issues warnings for non-conforming names + * @param name - The tool name to validate + * @returns true if the name is valid, false otherwise + */ +function validateAndWarnToolName(name) { + const result = validateToolName(name); + // Always issue warnings for any validation issues (both invalid names and warnings) + issueToolNameWarning(name, result.warnings); + return result.isValid; +} +//# sourceMappingURL=toolNameValidation.js.map \ No newline at end of file diff --git a/dist/cjs/shared/toolNameValidation.js.map b/dist/cjs/shared/toolNameValidation.js.map new file mode 100644 index 0000000000..ad136cc304 --- /dev/null +++ b/dist/cjs/shared/toolNameValidation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"toolNameValidation.js","sourceRoot":"","sources":["../../../src/shared/toolNameValidation.ts"],"names":[],"mappings":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AI,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;IAE5C,OAAO,MAAM,CAAC,OAAO,CAAC;AAC1B,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/transport.d.ts b/dist/cjs/shared/transport.d.ts new file mode 100644 index 0000000000..7fb5efab77 --- /dev/null +++ b/dist/cjs/shared/transport.d.ts @@ -0,0 +1,89 @@ +import { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types.js'; +export type FetchLike = (url: string | URL, init?: RequestInit) => Promise; +/** + * Normalizes HeadersInit to a plain Record for manipulation. + * Handles Headers objects, arrays of tuples, and plain objects. + */ +export declare function normalizeHeaders(headers: HeadersInit | undefined): Record; +/** + * Creates a fetch function that includes base RequestInit options. + * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. + * + * @param baseFetch - The base fetch function to wrap (defaults to global fetch) + * @param baseInit - The base RequestInit to merge with each request + * @returns A wrapped fetch function that merges base options with call-specific options + */ +export declare function createFetchWithInit(baseFetch?: FetchLike, baseInit?: RequestInit): FetchLike; +/** + * Options for sending a JSON-RPC message. + */ +export type TransportSendOptions = { + /** + * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with. + */ + relatedRequestId?: RequestId; + /** + * The resumption token used to continue long-running requests that were interrupted. + * + * This allows clients to reconnect and continue from where they left off, if supported by the transport. + */ + resumptionToken?: string; + /** + * A callback that is invoked when the resumption token changes, if supported by the transport. + * + * This allows clients to persist the latest token for potential reconnection. + */ + onresumptiontoken?: (token: string) => void; +}; +/** + * Describes the minimal contract for a MCP transport that a client or server can communicate over. + */ +export interface Transport { + /** + * Starts processing messages on the transport, including any connection steps that might need to be taken. + * + * This method should only be called after callbacks are installed, or else messages may be lost. + * + * NOTE: This method should not be called explicitly when using Client, Server, or Protocol classes, as they will implicitly call start(). + */ + start(): Promise; + /** + * Sends a JSON-RPC message (request or response). + * + * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with. + */ + send(message: JSONRPCMessage, options?: TransportSendOptions): Promise; + /** + * Closes the connection. + */ + close(): Promise; + /** + * Callback for when the connection is closed for any reason. + * + * This should be invoked when close() is called as well. + */ + onclose?: () => void; + /** + * Callback for when an error occurs. + * + * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. + */ + onerror?: (error: Error) => void; + /** + * Callback for when a message (request or response) is received over the connection. + * + * Includes the requestInfo and authInfo if the transport is authenticated. + * + * The requestInfo can be used to get the original request information (headers, etc.) + */ + onmessage?: (message: T, extra?: MessageExtraInfo) => void; + /** + * The session ID generated for this connection. + */ + sessionId?: string; + /** + * Sets the protocol version used for the connection (called when the initialize response is received). + */ + setProtocolVersion?: (version: string) => void; +} +//# sourceMappingURL=transport.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/transport.d.ts.map b/dist/cjs/shared/transport.d.ts.map new file mode 100644 index 0000000000..7a3d837df8 --- /dev/null +++ b/dist/cjs/shared/transport.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../../src/shared/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE1E,MAAM,MAAM,SAAS,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAErF;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAYzF;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,SAAS,GAAE,SAAiB,EAAE,QAAQ,CAAC,EAAE,WAAW,GAAG,SAAS,CAenG;AAED;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAAG;IAC/B;;OAEG;IACH,gBAAgB,CAAC,EAAE,SAAS,CAAC;IAE7B;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;CAC/C,CAAC;AACF;;GAEG;AACH,MAAM,WAAW,SAAS;IACtB;;;;;;OAMG;IACH,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEvB;;;;OAIG;IACH,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE,oBAAoB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE7E;;OAEG;IACH,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEvB;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IAErB;;;;OAIG;IACH,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IAEjC;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,CAAC,CAAC,SAAS,cAAc,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAErF;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,kBAAkB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CAClD"} \ No newline at end of file diff --git a/dist/cjs/shared/transport.js b/dist/cjs/shared/transport.js new file mode 100644 index 0000000000..9618d067c8 --- /dev/null +++ b/dist/cjs/shared/transport.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.normalizeHeaders = normalizeHeaders; +exports.createFetchWithInit = createFetchWithInit; +/** + * Normalizes HeadersInit to a plain Record for manipulation. + * Handles Headers objects, arrays of tuples, and plain objects. + */ +function normalizeHeaders(headers) { + if (!headers) + return {}; + if (headers instanceof Headers) { + return Object.fromEntries(headers.entries()); + } + if (Array.isArray(headers)) { + return Object.fromEntries(headers); + } + return { ...headers }; +} +/** + * Creates a fetch function that includes base RequestInit options. + * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. + * + * @param baseFetch - The base fetch function to wrap (defaults to global fetch) + * @param baseInit - The base RequestInit to merge with each request + * @returns A wrapped fetch function that merges base options with call-specific options + */ +function createFetchWithInit(baseFetch = fetch, baseInit) { + if (!baseInit) { + return baseFetch; + } + // Return a wrapped fetch that merges base RequestInit with call-specific init + return async (url, init) => { + const mergedInit = { + ...baseInit, + ...init, + // Headers need special handling - merge instead of replace + headers: (init === null || init === void 0 ? void 0 : init.headers) ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers + }; + return baseFetch(url, mergedInit); + }; +} +//# sourceMappingURL=transport.js.map \ No newline at end of file diff --git a/dist/cjs/shared/transport.js.map b/dist/cjs/shared/transport.js.map new file mode 100644 index 0000000000..3c8cb5f837 --- /dev/null +++ b/dist/cjs/shared/transport.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../src/shared/transport.ts"],"names":[],"mappings":";;AAQA,4CAYC;AAUD,kDAeC;AAzCD;;;GAGG;AACH,SAAgB,gBAAgB,CAAC,OAAgC;IAC7D,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,CAAC;IAExB,IAAI,OAAO,YAAY,OAAO,EAAE,CAAC;QAC7B,OAAO,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IACjD,CAAC;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACzB,OAAO,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,EAAE,GAAI,OAAkC,EAAE,CAAC;AACtD,CAAC;AAED;;;;;;;GAOG;AACH,SAAgB,mBAAmB,CAAC,YAAuB,KAAK,EAAE,QAAsB;IACpF,IAAI,CAAC,QAAQ,EAAE,CAAC;QACZ,OAAO,SAAS,CAAC;IACrB,CAAC;IAED,8EAA8E;IAC9E,OAAO,KAAK,EAAE,GAAiB,EAAE,IAAkB,EAAqB,EAAE;QACtE,MAAM,UAAU,GAAgB;YAC5B,GAAG,QAAQ;YACX,GAAG,IAAI;YACP,2DAA2D;YAC3D,OAAO,EAAE,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,EAAC,CAAC,CAAC,EAAE,GAAG,gBAAgB,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,GAAG,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO;SAC3H,CAAC;QACF,OAAO,SAAS,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC;IACtC,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/uriTemplate.d.ts b/dist/cjs/shared/uriTemplate.d.ts new file mode 100644 index 0000000000..175e329b66 --- /dev/null +++ b/dist/cjs/shared/uriTemplate.d.ts @@ -0,0 +1,25 @@ +export type Variables = Record; +export declare class UriTemplate { + /** + * Returns true if the given string contains any URI template expressions. + * A template expression is a sequence of characters enclosed in curly braces, + * like {foo} or {?bar}. + */ + static isTemplate(str: string): boolean; + private static validateLength; + private readonly template; + private readonly parts; + get variableNames(): string[]; + constructor(template: string); + toString(): string; + private parse; + private getOperator; + private getNames; + private encodeValue; + private expandPart; + expand(variables: Variables): string; + private escapeRegExp; + private partToRegExp; + match(uri: string): Variables | null; +} +//# sourceMappingURL=uriTemplate.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/uriTemplate.d.ts.map b/dist/cjs/shared/uriTemplate.d.ts.map new file mode 100644 index 0000000000..052e91851e --- /dev/null +++ b/dist/cjs/shared/uriTemplate.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"uriTemplate.d.ts","sourceRoot":"","sources":["../../../src/shared/uriTemplate.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC;AAO1D,qBAAa,WAAW;IACpB;;;;OAIG;IACH,MAAM,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAMvC,OAAO,CAAC,MAAM,CAAC,cAAc;IAK7B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAyF;IAE/G,IAAI,aAAa,IAAI,MAAM,EAAE,CAE5B;gBAEW,QAAQ,EAAE,MAAM;IAM5B,QAAQ,IAAI,MAAM;IAIlB,OAAO,CAAC,KAAK;IA8Cb,OAAO,CAAC,WAAW;IAKnB,OAAO,CAAC,QAAQ;IAShB,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,UAAU;IAsDlB,MAAM,CAAC,SAAS,EAAE,SAAS,GAAG,MAAM;IA4BpC,OAAO,CAAC,YAAY;IAIpB,OAAO,CAAC,YAAY;IAkDpB,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;CAuCvC"} \ No newline at end of file diff --git a/dist/cjs/shared/uriTemplate.js b/dist/cjs/shared/uriTemplate.js new file mode 100644 index 0000000000..baad5d9746 --- /dev/null +++ b/dist/cjs/shared/uriTemplate.js @@ -0,0 +1,243 @@ +"use strict"; +// Claude-authored implementation of RFC 6570 URI Templates +Object.defineProperty(exports, "__esModule", { value: true }); +exports.UriTemplate = void 0; +const MAX_TEMPLATE_LENGTH = 1000000; // 1MB +const MAX_VARIABLE_LENGTH = 1000000; // 1MB +const MAX_TEMPLATE_EXPRESSIONS = 10000; +const MAX_REGEX_LENGTH = 1000000; // 1MB +class UriTemplate { + /** + * Returns true if the given string contains any URI template expressions. + * A template expression is a sequence of characters enclosed in curly braces, + * like {foo} or {?bar}. + */ + static isTemplate(str) { + // Look for any sequence of characters between curly braces + // that isn't just whitespace + return /\{[^}\s]+\}/.test(str); + } + static validateLength(str, max, context) { + if (str.length > max) { + throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); + } + } + get variableNames() { + return this.parts.flatMap(part => (typeof part === 'string' ? [] : part.names)); + } + constructor(template) { + UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, 'Template'); + this.template = template; + this.parts = this.parse(template); + } + toString() { + return this.template; + } + parse(template) { + const parts = []; + let currentText = ''; + let i = 0; + let expressionCount = 0; + while (i < template.length) { + if (template[i] === '{') { + if (currentText) { + parts.push(currentText); + currentText = ''; + } + const end = template.indexOf('}', i); + if (end === -1) + throw new Error('Unclosed template expression'); + expressionCount++; + if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) { + throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); + } + const expr = template.slice(i + 1, end); + const operator = this.getOperator(expr); + const exploded = expr.includes('*'); + const names = this.getNames(expr); + const name = names[0]; + // Validate variable name length + for (const name of names) { + UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name'); + } + parts.push({ name, operator, names, exploded }); + i = end + 1; + } + else { + currentText += template[i]; + i++; + } + } + if (currentText) { + parts.push(currentText); + } + return parts; + } + getOperator(expr) { + const operators = ['+', '#', '.', '/', '?', '&']; + return operators.find(op => expr.startsWith(op)) || ''; + } + getNames(expr) { + const operator = this.getOperator(expr); + return expr + .slice(operator.length) + .split(',') + .map(name => name.replace('*', '').trim()) + .filter(name => name.length > 0); + } + encodeValue(value, operator) { + UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, 'Variable value'); + if (operator === '+' || operator === '#') { + return encodeURI(value); + } + return encodeURIComponent(value); + } + expandPart(part, variables) { + if (part.operator === '?' || part.operator === '&') { + const pairs = part.names + .map(name => { + const value = variables[name]; + if (value === undefined) + return ''; + const encoded = Array.isArray(value) + ? value.map(v => this.encodeValue(v, part.operator)).join(',') + : this.encodeValue(value.toString(), part.operator); + return `${name}=${encoded}`; + }) + .filter(pair => pair.length > 0); + if (pairs.length === 0) + return ''; + const separator = part.operator === '?' ? '?' : '&'; + return separator + pairs.join('&'); + } + if (part.names.length > 1) { + const values = part.names.map(name => variables[name]).filter(v => v !== undefined); + if (values.length === 0) + return ''; + return values.map(v => (Array.isArray(v) ? v[0] : v)).join(','); + } + const value = variables[part.name]; + if (value === undefined) + return ''; + const values = Array.isArray(value) ? value : [value]; + const encoded = values.map(v => this.encodeValue(v, part.operator)); + switch (part.operator) { + case '': + return encoded.join(','); + case '+': + return encoded.join(','); + case '#': + return '#' + encoded.join(','); + case '.': + return '.' + encoded.join('.'); + case '/': + return '/' + encoded.join('/'); + default: + return encoded.join(','); + } + } + expand(variables) { + let result = ''; + let hasQueryParam = false; + for (const part of this.parts) { + if (typeof part === 'string') { + result += part; + continue; + } + const expanded = this.expandPart(part, variables); + if (!expanded) + continue; + // Convert ? to & if we already have a query parameter + if ((part.operator === '?' || part.operator === '&') && hasQueryParam) { + result += expanded.replace('?', '&'); + } + else { + result += expanded; + } + if (part.operator === '?' || part.operator === '&') { + hasQueryParam = true; + } + } + return result; + } + escapeRegExp(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + } + partToRegExp(part) { + const patterns = []; + // Validate variable name length for matching + for (const name of part.names) { + UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name'); + } + if (part.operator === '?' || part.operator === '&') { + for (let i = 0; i < part.names.length; i++) { + const name = part.names[i]; + const prefix = i === 0 ? '\\' + part.operator : '&'; + patterns.push({ + pattern: prefix + this.escapeRegExp(name) + '=([^&]+)', + name + }); + } + return patterns; + } + let pattern; + const name = part.name; + switch (part.operator) { + case '': + pattern = part.exploded ? '([^/]+(?:,[^/]+)*)' : '([^/,]+)'; + break; + case '+': + case '#': + pattern = '(.+)'; + break; + case '.': + pattern = '\\.([^/,]+)'; + break; + case '/': + pattern = '/' + (part.exploded ? '([^/]+(?:,[^/]+)*)' : '([^/,]+)'); + break; + default: + pattern = '([^/]+)'; + } + patterns.push({ pattern, name }); + return patterns; + } + match(uri) { + UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, 'URI'); + let pattern = '^'; + const names = []; + for (const part of this.parts) { + if (typeof part === 'string') { + pattern += this.escapeRegExp(part); + } + else { + const patterns = this.partToRegExp(part); + for (const { pattern: partPattern, name } of patterns) { + pattern += partPattern; + names.push({ name, exploded: part.exploded }); + } + } + } + pattern += '$'; + UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, 'Generated regex pattern'); + const regex = new RegExp(pattern); + const match = uri.match(regex); + if (!match) + return null; + const result = {}; + for (let i = 0; i < names.length; i++) { + const { name, exploded } = names[i]; + const value = match[i + 1]; + const cleanName = name.replace('*', ''); + if (exploded && value.includes(',')) { + result[cleanName] = value.split(','); + } + else { + result[cleanName] = value; + } + } + return result; + } +} +exports.UriTemplate = UriTemplate; +//# sourceMappingURL=uriTemplate.js.map \ No newline at end of file diff --git a/dist/cjs/shared/uriTemplate.js.map b/dist/cjs/shared/uriTemplate.js.map new file mode 100644 index 0000000000..75c5c50e2a --- /dev/null +++ b/dist/cjs/shared/uriTemplate.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uriTemplate.js","sourceRoot":"","sources":["../../../src/shared/uriTemplate.ts"],"names":[],"mappings":";AAAA,2DAA2D;;;AAI3D,MAAM,mBAAmB,GAAG,OAAO,CAAC,CAAC,MAAM;AAC3C,MAAM,mBAAmB,GAAG,OAAO,CAAC,CAAC,MAAM;AAC3C,MAAM,wBAAwB,GAAG,KAAK,CAAC;AACvC,MAAM,gBAAgB,GAAG,OAAO,CAAC,CAAC,MAAM;AAExC,MAAa,WAAW;IACpB;;;;OAIG;IACH,MAAM,CAAC,UAAU,CAAC,GAAW;QACzB,2DAA2D;QAC3D,6BAA6B;QAC7B,OAAO,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACnC,CAAC;IAEO,MAAM,CAAC,cAAc,CAAC,GAAW,EAAE,GAAW,EAAE,OAAe;QACnE,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE,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git a/dist/cjs/shared/zodTestMatrix.d.ts b/dist/cjs/shared/zodTestMatrix.d.ts new file mode 100644 index 0000000000..7dafd4ce93 --- /dev/null +++ b/dist/cjs/shared/zodTestMatrix.d.ts @@ -0,0 +1,16 @@ +import * as z3 from 'zod/v3'; +import * as z4 from 'zod/v4'; +export type ZNamespace = typeof z3 & typeof z4; +export declare const zodTestMatrix: readonly [{ + readonly zodVersionLabel: "Zod v3"; + readonly z: ZNamespace; + readonly isV3: true; + readonly isV4: false; +}, { + readonly zodVersionLabel: "Zod v4"; + readonly z: ZNamespace; + readonly isV3: false; + readonly isV4: true; +}]; +export type ZodMatrixEntry = (typeof zodTestMatrix)[number]; +//# sourceMappingURL=zodTestMatrix.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/zodTestMatrix.d.ts.map b/dist/cjs/shared/zodTestMatrix.d.ts.map new file mode 100644 index 0000000000..3842fb1c32 --- /dev/null +++ b/dist/cjs/shared/zodTestMatrix.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"zodTestMatrix.d.ts","sourceRoot":"","sources":["../../../src/shared/zodTestMatrix.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC7B,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAG7B,MAAM,MAAM,UAAU,GAAG,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC;AAE/C,eAAO,MAAM,aAAa;;gBAGT,UAAU;;;;;gBAMV,UAAU;;;EAIjB,CAAC;AAEX,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,aAAa,CAAC,CAAC,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/zodTestMatrix.js b/dist/cjs/shared/zodTestMatrix.js new file mode 100644 index 0000000000..92627ab249 --- /dev/null +++ b/dist/cjs/shared/zodTestMatrix.js @@ -0,0 +1,43 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.zodTestMatrix = void 0; +const z3 = __importStar(require("zod/v3")); +const z4 = __importStar(require("zod/v4")); +exports.zodTestMatrix = [ + { + zodVersionLabel: 'Zod v3', + z: z3, + isV3: true, + isV4: false + }, + { + zodVersionLabel: 'Zod v4', + z: z4, + isV3: false, + isV4: true + } +]; +//# sourceMappingURL=zodTestMatrix.js.map \ No newline at end of file diff --git a/dist/cjs/shared/zodTestMatrix.js.map b/dist/cjs/shared/zodTestMatrix.js.map new file mode 100644 index 0000000000..55cc0b0ace --- /dev/null +++ b/dist/cjs/shared/zodTestMatrix.js.map @@ -0,0 +1 @@ +{"version":3,"file":"zodTestMatrix.js","sourceRoot":"","sources":["../../../src/shared/zodTestMatrix.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA6B;AAC7B,2CAA6B;AAKhB,QAAA,aAAa,GAAG;IACzB;QACI,eAAe,EAAE,QAAQ;QACzB,CAAC,EAAE,EAAgB;QACnB,IAAI,EAAE,IAAa;QACnB,IAAI,EAAE,KAAc;KACvB;IACD;QACI,eAAe,EAAE,QAAQ;QACzB,CAAC,EAAE,EAAgB;QACnB,IAAI,EAAE,KAAc;QACpB,IAAI,EAAE,IAAa;KACtB;CACK,CAAC"} \ No newline at end of file diff --git a/dist/cjs/spec.types.d.ts b/dist/cjs/spec.types.d.ts new file mode 100644 index 0000000000..bf6a90f80c --- /dev/null +++ b/dist/cjs/spec.types.d.ts @@ -0,0 +1,2033 @@ +/** + * This file is automatically generated from the Model Context Protocol specification. + * + * Source: https://github.com/modelcontextprotocol/modelcontextprotocol + * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts + * Last updated from commit: 4528444698f76e6d0337e58d2941d5d3485d779d + * + * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. + * To update this file, run: npm run fetch:spec-types + */ +/** + * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. + * + * @category JSON-RPC + */ +export type JSONRPCMessage = JSONRPCRequest | JSONRPCNotification | JSONRPCResponse | JSONRPCError; +/** @internal */ +export declare const LATEST_PROTOCOL_VERSION = "DRAFT-2025-v3"; +/** @internal */ +export declare const JSONRPC_VERSION = "2.0"; +/** + * A progress token, used to associate progress notifications with the original request. + * + * @category Common Types + */ +export type ProgressToken = string | number; +/** + * An opaque token used to represent a cursor for pagination. + * + * @category Common Types + */ +export type Cursor = string; +/** + * Common params for any request. + * + * @internal + */ +export interface RequestParams { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken?: ProgressToken; + [key: string]: unknown; + }; +} +/** @internal */ +export interface Request { + method: string; + params?: { + [key: string]: any; + }; +} +/** @internal */ +export interface NotificationParams { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** @internal */ +export interface Notification { + method: string; + params?: { + [key: string]: any; + }; +} +/** + * @category Common Types + */ +export interface Result { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; + [key: string]: unknown; +} +/** + * @category Common Types + */ +export interface Error { + /** + * The error type that occurred. + */ + code: number; + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string; + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data?: unknown; +} +/** + * A uniquely identifying ID for a request in JSON-RPC. + * + * @category Common Types + */ +export type RequestId = string | number; +/** + * A request that expects a response. + * + * @category JSON-RPC + */ +export interface JSONRPCRequest extends Request { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; +} +/** + * A notification which does not expect a response. + * + * @category JSON-RPC + */ +export interface JSONRPCNotification extends Notification { + jsonrpc: typeof JSONRPC_VERSION; +} +/** + * A successful (non-error) response to a request. + * + * @category JSON-RPC + */ +export interface JSONRPCResponse { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + result: Result; +} +export declare const PARSE_ERROR = -32700; +export declare const INVALID_REQUEST = -32600; +export declare const METHOD_NOT_FOUND = -32601; +export declare const INVALID_PARAMS = -32602; +export declare const INTERNAL_ERROR = -32603; +/** @internal */ +export declare const URL_ELICITATION_REQUIRED = -32042; +/** + * A response to a request that indicates an error occurred. + * + * @category JSON-RPC + */ +export interface JSONRPCError { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + error: Error; +} +/** + * An error response that indicates that the server requires the client to provide additional information via an elicitation request. + * + * @internal + */ +export interface URLElicitationRequiredError extends Omit { + error: Error & { + code: typeof URL_ELICITATION_REQUIRED; + data: { + elicitations: ElicitRequestURLParams[]; + [key: string]: unknown; + }; + }; +} +/** + * A response that indicates success but carries no data. + * + * @category Common Types + */ +export type EmptyResult = Result; +/** + * Parameters for a `notifications/cancelled` notification. + * + * @category `notifications/cancelled` + */ +export interface CancelledNotificationParams extends NotificationParams { + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestId; + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason?: string; +} +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + * + * @category `notifications/cancelled` + */ +export interface CancelledNotification extends JSONRPCNotification { + method: "notifications/cancelled"; + params: CancelledNotificationParams; +} +/** + * Parameters for an `initialize` request. + * + * @category `initialize` + */ +export interface InitializeRequestParams extends RequestParams { + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string; + capabilities: ClientCapabilities; + clientInfo: Implementation; +} +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + * + * @category `initialize` + */ +export interface InitializeRequest extends JSONRPCRequest { + method: "initialize"; + params: InitializeRequestParams; +} +/** + * After receiving an initialize request from the client, the server sends this response. + * + * @category `initialize` + */ +export interface InitializeResult extends Result { + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: string; + capabilities: ServerCapabilities; + serverInfo: Implementation; + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions?: string; +} +/** + * This notification is sent from the client to the server after initialization has finished. + * + * @category `notifications/initialized` + */ +export interface InitializedNotification extends JSONRPCNotification { + method: "notifications/initialized"; + params?: NotificationParams; +} +/** + * 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. + * + * @category `initialize` + */ +export interface ClientCapabilities { + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental?: { + [key: string]: object; + }; + /** + * Present if the client supports listing roots. + */ + roots?: { + /** + * Whether the client supports notifications for changes to the roots list. + */ + listChanged?: boolean; + }; + /** + * Present if the client supports sampling from an LLM. + */ + sampling?: { + /** + * Whether the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context?: object; + /** + * Whether the client supports tool use via tools and toolChoice parameters. + */ + tools?: object; + }; + /** + * Present if the client supports elicitation from the server. + */ + elicitation?: { + form?: object; + url?: object; + }; +} +/** + * 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. + * + * @category `initialize` + */ +export interface ServerCapabilities { + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental?: { + [key: string]: object; + }; + /** + * Present if the server supports sending log messages to the client. + */ + logging?: object; + /** + * Present if the server supports argument autocompletion suggestions. + */ + completions?: object; + /** + * Present if the server offers any prompt templates. + */ + prompts?: { + /** + * Whether this server supports notifications for changes to the prompt list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any resources to read. + */ + resources?: { + /** + * Whether this server supports subscribing to resource updates. + */ + subscribe?: boolean; + /** + * Whether this server supports notifications for changes to the resource list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any tools to call. + */ + tools?: { + /** + * Whether this server supports notifications for changes to the tool list. + */ + listChanged?: boolean; + }; +} +/** + * An optionally-sized icon that can be displayed in a user interface. + * + * @category Common Types + */ +export interface Icon { + /** + * A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a + * `data:` URI with Base64-encoded image data. + * + * Consumers SHOULD takes steps to ensure URLs serving icons are from the + * same domain as the client/server or a trusted domain. + * + * Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain + * executable JavaScript. + * + * @format uri + */ + src: string; + /** + * Optional MIME type override if the source MIME type is missing or generic. + * For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`. + */ + mimeType?: string; + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes?: string[]; + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme?: "light" | "dark"; +} +/** + * Base interface to add `icons` property. + * + * @internal + */ +export interface Icons { + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons?: Icon[]; +} +/** + * Base interface for metadata with name (identifier) and title (display name) properties. + * + * @internal + */ +export interface BaseMetadata { + /** + * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present). + */ + name: string; + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title?: string; +} +/** + * Describes the MCP implementation. + * + * @category `initialize` + */ +export interface Implementation extends BaseMetadata, Icons { + version: string; + /** + * An optional URL of the website for this implementation. + * + * @format uri + */ + websiteUrl?: string; +} +/** + * 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. + * + * @category `ping` + */ +export interface PingRequest extends JSONRPCRequest { + method: "ping"; + params?: RequestParams; +} +/** + * Parameters for a `notifications/progress` notification. + * + * @category `notifications/progress` + */ +export interface ProgressNotificationParams extends NotificationParams { + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressToken; + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + * + * @TJS-type number + */ + progress: number; + /** + * Total number of items to process (or total progress required), if known. + * + * @TJS-type number + */ + total?: number; + /** + * An optional message describing the current progress. + */ + message?: string; +} +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category `notifications/progress` + */ +export interface ProgressNotification extends JSONRPCNotification { + method: "notifications/progress"; + params: ProgressNotificationParams; +} +/** + * Common parameters for paginated requests. + * + * @internal + */ +export interface PaginatedRequestParams extends RequestParams { + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor?: Cursor; +} +/** @internal */ +export interface PaginatedRequest extends JSONRPCRequest { + params?: PaginatedRequestParams; +} +/** @internal */ +export interface PaginatedResult extends Result { + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor?: Cursor; +} +/** + * Sent from the client to request a list of resources the server has. + * + * @category `resources/list` + */ +export interface ListResourcesRequest extends PaginatedRequest { + method: "resources/list"; +} +/** + * The server's response to a resources/list request from the client. + * + * @category `resources/list` + */ +export interface ListResourcesResult extends PaginatedResult { + resources: Resource[]; +} +/** + * Sent from the client to request a list of resource templates the server has. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesRequest extends PaginatedRequest { + method: "resources/templates/list"; +} +/** + * The server's response to a resources/templates/list request from the client. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesResult extends PaginatedResult { + resourceTemplates: ResourceTemplate[]; +} +/** + * Common parameters when working with resources. + * + * @internal + */ +export interface ResourceRequestParams extends RequestParams { + /** + * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string; +} +/** + * Parameters for a `resources/read` request. + * + * @category `resources/read` + */ +export interface ReadResourceRequestParams extends ResourceRequestParams { +} +/** + * Sent from the client to the server, to read a specific resource URI. + * + * @category `resources/read` + */ +export interface ReadResourceRequest extends JSONRPCRequest { + method: "resources/read"; + params: ReadResourceRequestParams; +} +/** + * The server's response to a resources/read request from the client. + * + * @category `resources/read` + */ +export interface ReadResourceResult extends Result { + contents: (TextResourceContents | BlobResourceContents)[]; +} +/** + * 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. + * + * @category `notifications/resources/list_changed` + */ +export interface ResourceListChangedNotification extends JSONRPCNotification { + method: "notifications/resources/list_changed"; + params?: NotificationParams; +} +/** + * Parameters for a `resources/subscribe` request. + * + * @category `resources/subscribe` + */ +export interface SubscribeRequestParams extends ResourceRequestParams { +} +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + * + * @category `resources/subscribe` + */ +export interface SubscribeRequest extends JSONRPCRequest { + method: "resources/subscribe"; + params: SubscribeRequestParams; +} +/** + * Parameters for a `resources/unsubscribe` request. + * + * @category `resources/unsubscribe` + */ +export interface UnsubscribeRequestParams extends ResourceRequestParams { +} +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + * + * @category `resources/unsubscribe` + */ +export interface UnsubscribeRequest extends JSONRPCRequest { + method: "resources/unsubscribe"; + params: UnsubscribeRequestParams; +} +/** + * Parameters for a `notifications/resources/updated` notification. + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotificationParams extends NotificationParams { + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + * + * @format uri + */ + uri: string; +} +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotification extends JSONRPCNotification { + method: "notifications/resources/updated"; + params: ResourceUpdatedNotificationParams; +} +/** + * A known resource that the server is capable of reading. + * + * @category `resources/list` + */ +export interface Resource extends BaseMetadata, Icons { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size?: number; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * A template description for resources available on the server. + * + * @category `resources/templates/list` + */ +export interface ResourceTemplate extends BaseMetadata, Icons { + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + * + * @format uri-template + */ + uriTemplate: string; + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType?: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * The contents of a specific resource or sub-resource. + * + * @internal + */ +export interface ResourceContents { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * @category Content + */ +export interface TextResourceContents extends ResourceContents { + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string; +} +/** + * @category Content + */ +export interface BlobResourceContents extends ResourceContents { + /** + * A base64-encoded string representing the binary data of the item. + * + * @format byte + */ + blob: string; +} +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + * + * @category `prompts/list` + */ +export interface ListPromptsRequest extends PaginatedRequest { + method: "prompts/list"; +} +/** + * The server's response to a prompts/list request from the client. + * + * @category `prompts/list` + */ +export interface ListPromptsResult extends PaginatedResult { + prompts: Prompt[]; +} +/** + * Parameters for a `prompts/get` request. + * + * @category `prompts/get` + */ +export interface GetPromptRequestParams extends RequestParams { + /** + * The name of the prompt or prompt template. + */ + name: string; + /** + * Arguments to use for templating the prompt. + */ + arguments?: { + [key: string]: string; + }; +} +/** + * Used by the client to get a prompt provided by the server. + * + * @category `prompts/get` + */ +export interface GetPromptRequest extends JSONRPCRequest { + method: "prompts/get"; + params: GetPromptRequestParams; +} +/** + * The server's response to a prompts/get request from the client. + * + * @category `prompts/get` + */ +export interface GetPromptResult extends Result { + /** + * An optional description for the prompt. + */ + description?: string; + messages: PromptMessage[]; +} +/** + * A prompt or prompt template that the server offers. + * + * @category `prompts/list` + */ +export interface Prompt extends BaseMetadata, Icons { + /** + * An optional description of what this prompt provides + */ + description?: string; + /** + * A list of arguments to use for templating the prompt. + */ + arguments?: PromptArgument[]; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * Describes an argument that a prompt can accept. + * + * @category `prompts/list` + */ +export interface PromptArgument extends BaseMetadata { + /** + * A human-readable description of the argument. + */ + description?: string; + /** + * Whether this argument must be provided. + */ + required?: boolean; +} +/** + * The sender or recipient of messages and data in a conversation. + * + * @category Common Types + */ +export type Role = "user" | "assistant"; +/** + * Describes a message returned as part of a prompt. + * + * This is similar to `SamplingMessage`, but also supports the embedding of + * resources from the MCP server. + * + * @category `prompts/get` + */ +export interface PromptMessage { + role: Role; + content: ContentBlock; +} +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + * + * @category Content + */ +export interface ResourceLink extends Resource { + type: "resource_link"; +} +/** + * The contents of a resource, embedded into a prompt or tool call result. + * + * It is up to the client how best to render embedded resources for the benefit + * of the LLM and/or the user. + * + * @category Content + */ +export interface EmbeddedResource { + type: "resource"; + resource: TextResourceContents | BlobResourceContents; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * 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. + * + * @category `notifications/prompts/list_changed` + */ +export interface PromptListChangedNotification extends JSONRPCNotification { + method: "notifications/prompts/list_changed"; + params?: NotificationParams; +} +/** + * Sent from the client to request a list of tools the server has. + * + * @category `tools/list` + */ +export interface ListToolsRequest extends PaginatedRequest { + method: "tools/list"; +} +/** + * The server's response to a tools/list request from the client. + * + * @category `tools/list` + */ +export interface ListToolsResult extends PaginatedResult { + tools: Tool[]; +} +/** + * The server's response to a tool call. + * + * @category `tools/call` + */ +export interface CallToolResult extends Result { + /** + * A list of content objects that represent the unstructured result of the tool call. + */ + content: ContentBlock[]; + /** + * An optional JSON object that represents the structured result of the tool call. + */ + structuredContent?: { + [key: string]: unknown; + }; + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError?: boolean; +} +/** + * Parameters for a `tools/call` request. + * + * @category `tools/call` + */ +export interface CallToolRequestParams extends RequestParams { + /** + * The name of the tool. + */ + name: string; + /** + * Arguments to use for the tool call. + */ + arguments?: { + [key: string]: unknown; + }; +} +/** + * Used by the client to invoke a tool provided by the server. + * + * @category `tools/call` + */ +export interface CallToolRequest extends JSONRPCRequest { + method: "tools/call"; + params: CallToolRequestParams; +} +/** + * 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. + * + * @category `notifications/tools/list_changed` + */ +export interface ToolListChangedNotification extends JSONRPCNotification { + method: "notifications/tools/list_changed"; + params?: NotificationParams; +} +/** + * Security scheme indicating no authentication is required. + * + * @category `tools/list` + */ +export interface NoAuthSecurityScheme { + type: "noauth"; +} +/** + * Security scheme indicating OAuth 2.0 authentication is required. + * + * @category `tools/list` + */ +export interface OAuth2SecurityScheme { + type: "oauth2"; + /** + * Optional list of OAuth 2.0 scopes required for this tool. + */ + scopes?: string[]; +} +/** + * A security scheme that can be used to authenticate tool calls. + * + * @category `tools/list` + */ +export type SecurityScheme = NoAuthSecurityScheme | OAuth2SecurityScheme; +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + * + * @category `tools/list` + */ +export interface ToolAnnotations { + /** + * A human-readable title for the tool. + */ + title?: string; + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint?: boolean; + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint?: boolean; + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint?: boolean; + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint?: boolean; +} +/** + * Definition for a tool the client can call. + * + * @category `tools/list` + */ +export interface Tool extends BaseMetadata, Icons { + /** + * A human-readable description of the tool. + * + * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. + */ + description?: string; + /** + * A JSON Schema object defining the expected parameters for the tool. + */ + inputSchema: { + type: "object"; + properties?: { + [key: string]: object; + }; + required?: string[]; + }; + /** + * An optional JSON Schema object defining the structure of the tool's output returned in + * the structuredContent field of a CallToolResult. + */ + outputSchema?: { + type: "object"; + properties?: { + [key: string]: object; + }; + required?: string[]; + }; + /** + * Optional additional tool information. + * + * Display name precedence order is: title, annotations.title, then name. + */ + annotations?: ToolAnnotations; + /** + * Optional list of security schemes supported by this tool. + * If missing, the tool follows the server's default authentication policy. + * If present, lists the supported authentication schemes (e.g., "noauth", "oauth2"). + */ + securitySchemes?: SecurityScheme[]; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * Parameters for a `logging/setLevel` request. + * + * @category `logging/setLevel` + */ +export interface SetLevelRequestParams extends RequestParams { + /** + * 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/message. + */ + level: LoggingLevel; +} +/** + * A request from the client to the server, to enable or adjust logging. + * + * @category `logging/setLevel` + */ +export interface SetLevelRequest extends JSONRPCRequest { + method: "logging/setLevel"; + params: SetLevelRequestParams; +} +/** + * Parameters for a `notifications/message` notification. + * + * @category `notifications/message` + */ +export interface LoggingMessageNotificationParams extends NotificationParams { + /** + * The severity of this log message. + */ + level: LoggingLevel; + /** + * An optional name of the logger issuing this message. + */ + logger?: string; + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown; +} +/** + * JSONRPCNotification 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. + * + * @category `notifications/message` + */ +export interface LoggingMessageNotification extends JSONRPCNotification { + method: "notifications/message"; + params: LoggingMessageNotificationParams; +} +/** + * The severity of a log message. + * + * These map to syslog message severities, as specified in RFC-5424: + * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 + * + * @category Common Types + */ +export type LoggingLevel = "debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency"; +/** + * Parameters for a `sampling/createMessage` request. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequestParams extends RequestParams { + messages: SamplingMessage[]; + /** + * The server's preferences for which model to select. The client MAY ignore these preferences. + */ + modelPreferences?: ModelPreferences; + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt?: string; + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext?: "none" | "thisServer" | "allServers"; + /** + * @TJS-type number + */ + temperature?: number; + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number; + stopSequences?: string[]; + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata?: object; + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools?: Tool[]; + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice?: ToolChoice; +} +/** + * Controls tool selection behavior for sampling requests. + * + * @category `sampling/createMessage` + */ +export interface ToolChoice { + /** + * Controls the tool use ability of the model: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode?: "auto" | "required" | "none"; +} +/** + * 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. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequest extends JSONRPCRequest { + method: "sampling/createMessage"; + params: CreateMessageRequestParams; +} +/** + * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageResult extends Result, SamplingMessage { + /** + * The name of the model that generated the message. + */ + model: string; + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason?: "endTurn" | "stopSequence" | "maxTokens" | "toolUse" | string; +} +/** + * Describes a message issued to or received from an LLM API. + * + * @category `sampling/createMessage` + */ +export interface SamplingMessage { + role: Role; + content: SamplingMessageContentBlock | SamplingMessageContentBlock[]; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +export type SamplingMessageContentBlock = TextContent | ImageContent | AudioContent | ToolUseContent | ToolResultContent; +/** + * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed + * + * @category Common Types + */ +export interface Annotations { + /** + * Describes who the intended customer of this object or data is. + * + * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). + */ + audience?: Role[]; + /** + * Describes how important this data is for operating the server. + * + * A value of 1 means "most important," and indicates that the data is + * effectively required, while 0 means "least important," and indicates that + * the data is entirely optional. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + priority?: number; + /** + * The moment the resource was last modified, as an ISO 8601 formatted string. + * + * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"). + * + * Examples: last activity timestamp in an open file, timestamp when the resource + * was attached, etc. + */ + lastModified?: string; +} +/** + * @category Content + */ +export type ContentBlock = TextContent | ImageContent | AudioContent | ResourceLink | EmbeddedResource; +/** + * Text provided to or from an LLM. + * + * @category Content + */ +export interface TextContent { + type: "text"; + /** + * The text content of the message. + */ + text: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * An image provided to or from an LLM. + * + * @category Content + */ +export interface ImageContent { + type: "image"; + /** + * The base64-encoded image data. + * + * @format byte + */ + data: string; + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * Audio provided to or from an LLM. + * + * @category Content + */ +export interface AudioContent { + type: "audio"; + /** + * The base64-encoded audio data. + * + * @format byte + */ + data: string; + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * A request from the assistant to call a tool. + * + * @category `sampling/createMessage` + */ +export interface ToolUseContent { + type: "tool_use"; + /** + * A unique identifier for this tool use. + * + * This ID is used to match tool results to their corresponding tool uses. + */ + id: string; + /** + * The name of the tool to call. + */ + name: string; + /** + * The arguments to pass to the tool, conforming to the tool's input schema. + */ + input: { + [key: string]: unknown; + }; + /** + * Optional metadata about the tool use. Clients SHOULD preserve this field when + * including tool uses in subsequent sampling requests to enable caching optimizations. + * + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * The result of a tool use, provided by the user back to the assistant. + * + * @category `sampling/createMessage` + */ +export interface ToolResultContent { + type: "tool_result"; + /** + * The ID of the tool use this result corresponds to. + * + * This MUST match the ID from a previous ToolUseContent. + */ + toolUseId: string; + /** + * The unstructured result content of the tool use. + * + * This has the same format as CallToolResult.content and can include text, images, + * audio, resource links, and embedded resources. + */ + content: ContentBlock[]; + /** + * An optional structured result object. + * + * If the tool defined an outputSchema, this SHOULD conform to that schema. + */ + structuredContent?: { + [key: string]: unknown; + }; + /** + * Whether the tool use resulted in an error. + * + * If true, the content typically describes the error that occurred. + * Default: false + */ + isError?: boolean; + /** + * Optional metadata about the tool result. Clients SHOULD preserve this field when + * including tool results in subsequent sampling requests to enable caching optimizations. + * + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * The server's preferences for model selection, requested of the client during sampling. + * + * Because LLMs can vary along multiple dimensions, choosing the "best" model is + * rarely straightforward. Different models excel in different areas—some are + * faster but less capable, others are more capable but more expensive, and so + * on. This interface allows servers to express their priorities across multiple + * dimensions to help clients make an appropriate selection for their use case. + * + * These preferences are always advisory. The client MAY ignore them. It is also + * up to the client to decide how to interpret these preferences and how to + * balance them against other considerations. + * + * @category `sampling/createMessage` + */ +export interface ModelPreferences { + /** + * Optional hints to use for model selection. + * + * If multiple hints are specified, the client MUST evaluate them in order + * (such that the first match is taken). + * + * The client SHOULD prioritize these hints over the numeric priorities, but + * MAY still use the priorities to select from ambiguous matches. + */ + hints?: ModelHint[]; + /** + * How much to prioritize cost when selecting a model. A value of 0 means cost + * is not important, while a value of 1 means cost is the most important + * factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + costPriority?: number; + /** + * How much to prioritize sampling speed (latency) when selecting a model. A + * value of 0 means speed is not important, while a value of 1 means speed is + * the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + speedPriority?: number; + /** + * How much to prioritize intelligence and capabilities when selecting a + * model. A value of 0 means intelligence is not important, while a value of 1 + * means intelligence is the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + intelligencePriority?: number; +} +/** + * Hints to use for model selection. + * + * Keys not declared here are currently left unspecified by the spec and are up + * to the client to interpret. + * + * @category `sampling/createMessage` + */ +export interface ModelHint { + /** + * A hint for a model name. + * + * The client SHOULD treat this as a substring of a model name; for example: + * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` + * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. + * - `claude` should match any Claude model + * + * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: + * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` + */ + name?: string; +} +/** + * Parameters for a `completion/complete` request. + * + * @category `completion/complete` + */ +export interface CompleteRequestParams extends RequestParams { + ref: PromptReference | ResourceTemplateReference; + /** + * The argument's information + */ + argument: { + /** + * The name of the argument + */ + name: string; + /** + * The value of the argument to use for completion matching. + */ + value: string; + }; + /** + * Additional, optional context for completions + */ + context?: { + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments?: { + [key: string]: string; + }; + }; +} +/** + * A request from the client to the server, to ask for completion options. + * + * @category `completion/complete` + */ +export interface CompleteRequest extends JSONRPCRequest { + method: "completion/complete"; + params: CompleteRequestParams; +} +/** + * The server's response to a completion/complete request + * + * @category `completion/complete` + */ +export interface CompleteResult extends Result { + completion: { + /** + * An array of completion values. Must not exceed 100 items. + */ + values: string[]; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total?: number; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore?: boolean; + }; +} +/** + * A reference to a resource or resource template definition. + * + * @category `completion/complete` + */ +export interface ResourceTemplateReference { + type: "ref/resource"; + /** + * The URI or URI template of the resource. + * + * @format uri-template + */ + uri: string; +} +/** + * Identifies a prompt. + * + * @category `completion/complete` + */ +export interface PromptReference extends BaseMetadata { + type: "ref/prompt"; +} +/** + * Sent from the server to request a list of root URIs from the client. Roots allow + * servers to ask for specific directories or files to operate on. A common example + * for roots is providing a set of repositories or directories a server should operate + * on. + * + * This request is typically used when the server needs to understand the file system + * structure or access specific locations that the client has permission to read from. + * + * @category `roots/list` + */ +export interface ListRootsRequest extends JSONRPCRequest { + method: "roots/list"; + params?: RequestParams; +} +/** + * The client's response to a roots/list request from the server. + * This result contains an array of Root objects, each representing a root directory + * or file that the server can operate on. + * + * @category `roots/list` + */ +export interface ListRootsResult extends Result { + roots: Root[]; +} +/** + * Represents a root directory or file that the server can operate on. + * + * @category `roots/list` + */ +export interface Root { + /** + * The URI identifying the root. This *must* start with file:// for now. + * This restriction may be relaxed in future versions of the protocol to allow + * other URI schemes. + * + * @format uri + */ + uri: string; + /** + * An optional name for the root. This can be used to provide a human-readable + * identifier for the root, which may be useful for display purposes or for + * referencing the root in other parts of the application. + */ + name?: string; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * A notification from the client to the server, informing it that the list of roots has changed. + * This notification should be sent whenever the client adds, removes, or modifies any root. + * The server should then request an updated list of roots using the ListRootsRequest. + * + * @category `notifications/roots/list_changed` + */ +export interface RootsListChangedNotification extends JSONRPCNotification { + method: "notifications/roots/list_changed"; + params?: NotificationParams; +} +/** + * The parameters for a request to elicit non-sensitive information from the user via a form in the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequestFormParams extends RequestParams { + /** + * The elicitation mode. + */ + mode: "form"; + /** + * The message to present to the user describing what information is being requested. + */ + message: string; + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: { + type: "object"; + properties: { + [key: string]: PrimitiveSchemaDefinition; + }; + required?: string[]; + }; +} +/** + * The parameters for a request to elicit information from the user via a URL in the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequestURLParams extends RequestParams { + /** + * The elicitation mode. + */ + mode: "url"; + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: string; + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: string; + /** + * The URL that the user should navigate to. + * + * @format uri + */ + url: string; +} +/** + * The parameters for a request to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export type ElicitRequestParams = ElicitRequestFormParams | ElicitRequestURLParams; +/** + * A request from the server to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequest extends JSONRPCRequest { + method: "elicitation/create"; + params: ElicitRequestParams; +} +/** + * Restricted schema definitions that only allow primitive types + * without nested objects or arrays. + * + * @category `elicitation/create` + */ +export type PrimitiveSchemaDefinition = StringSchema | NumberSchema | BooleanSchema | EnumSchema; +/** + * @category `elicitation/create` + */ +export interface StringSchema { + type: "string"; + title?: string; + description?: string; + minLength?: number; + maxLength?: number; + format?: "email" | "uri" | "date" | "date-time"; + default?: string; +} +/** + * @category `elicitation/create` + */ +export interface NumberSchema { + type: "number" | "integer"; + title?: string; + description?: string; + minimum?: number; + maximum?: number; + default?: number; +} +/** + * @category `elicitation/create` + */ +export interface BooleanSchema { + type: "boolean"; + title?: string; + description?: string; + default?: boolean; +} +/** + * Schema for single-selection enumeration without display titles for options. + * + * @category `elicitation/create` + */ +export interface UntitledSingleSelectEnumSchema { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum values to choose from. + */ + enum: string[]; + /** + * Optional default value. + */ + default?: string; +} +/** + * Schema for single-selection enumeration with display titles for each option. + * + * @category `elicitation/create` + */ +export interface TitledSingleSelectEnumSchema { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum options with values and display labels. + */ + oneOf: Array<{ + /** + * The enum value. + */ + const: string; + /** + * Display label for this option. + */ + title: string; + }>; + /** + * Optional default value. + */ + default?: string; +} +/** + * @category `elicitation/create` + */ +export type SingleSelectEnumSchema = UntitledSingleSelectEnumSchema | TitledSingleSelectEnumSchema; +/** + * Schema for multiple-selection enumeration without display titles for options. + * + * @category `elicitation/create` + */ +export interface UntitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for the array items. + */ + items: { + type: "string"; + /** + * Array of enum values to choose from. + */ + enum: string[]; + }; + /** + * Optional default value. + */ + default?: string[]; +} +/** + * Schema for multiple-selection enumeration with display titles for each option. + * + * @category `elicitation/create` + */ +export interface TitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for array items with enum options and display labels. + */ + items: { + /** + * Array of enum options with values and display labels. + */ + anyOf: Array<{ + /** + * The constant enum value. + */ + const: string; + /** + * Display title for this option. + */ + title: string; + }>; + }; + /** + * Optional default value. + */ + default?: string[]; +} +/** + * @category `elicitation/create` + */ +export type MultiSelectEnumSchema = UntitledMultiSelectEnumSchema | TitledMultiSelectEnumSchema; +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + * + * @category `elicitation/create` + */ +export interface LegacyTitledEnumSchema { + type: "string"; + title?: string; + description?: string; + enum: string[]; + /** + * (Legacy) Display names for enum values. + * Non-standard according to JSON schema 2020-12. + */ + enumNames?: string[]; + default?: string; +} +/** + * @category `elicitation/create` + */ +export type EnumSchema = SingleSelectEnumSchema | MultiSelectEnumSchema | LegacyTitledEnumSchema; +/** + * The client's response to an elicitation request. + * + * @category `elicitation/create` + */ +export interface ElicitResult extends Result { + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: "accept" | "decline" | "cancel"; + /** + * The submitted form data, only present when action is "accept" and mode was "form". + * Contains values matching the requested schema. + * Omitted for out-of-band mode responses. + */ + content?: { + [key: string]: string | number | boolean | string[]; + }; +} +/** + * An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request. + * + * @category `notifications/elicitation/complete` + */ +export interface ElicitationCompleteNotification extends JSONRPCNotification { + method: "notifications/elicitation/complete"; + params: { + /** + * The ID of the elicitation that completed. + */ + elicitationId: string; + }; +} +/** @internal */ +export type ClientRequest = PingRequest | InitializeRequest | CompleteRequest | SetLevelRequest | GetPromptRequest | ListPromptsRequest | ListResourcesRequest | ListResourceTemplatesRequest | ReadResourceRequest | SubscribeRequest | UnsubscribeRequest | CallToolRequest | ListToolsRequest; +/** @internal */ +export type ClientNotification = CancelledNotification | ProgressNotification | InitializedNotification | RootsListChangedNotification; +/** @internal */ +export type ClientResult = EmptyResult | CreateMessageResult | ListRootsResult | ElicitResult; +/** @internal */ +export type ServerRequest = PingRequest | CreateMessageRequest | ListRootsRequest | ElicitRequest; +/** @internal */ +export type ServerNotification = CancelledNotification | ProgressNotification | LoggingMessageNotification | ResourceUpdatedNotification | ResourceListChangedNotification | ToolListChangedNotification | PromptListChangedNotification | ElicitationCompleteNotification; +/** @internal */ +export type ServerResult = EmptyResult | InitializeResult | CompleteResult | GetPromptResult | ListPromptsResult | ListResourceTemplatesResult | ListResourcesResult | ReadResourceResult | CallToolResult | ListToolsResult; +//# sourceMappingURL=spec.types.d.ts.map \ No newline at end of file diff --git a/dist/cjs/spec.types.d.ts.map b/dist/cjs/spec.types.d.ts.map new file mode 100644 index 0000000000..3e44f68e82 --- /dev/null +++ b/dist/cjs/spec.types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"spec.types.d.ts","sourceRoot":"","sources":["../../src/spec.types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH;;;;GAIG;AACH,MAAM,MAAM,cAAc,GACtB,cAAc,GACd,mBAAmB,GACnB,eAAe,GACf,YAAY,CAAC;AAEjB,gBAAgB;AAChB,eAAO,MAAM,uBAAuB,kBAAkB,CAAC;AACvD,gBAAgB;AAChB,eAAO,MAAM,eAAe,QAAQ,CAAC;AAErC;;;;GAIG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,CAAC;AAE5C;;;;GAIG;AACH,MAAM,MAAM,MAAM,GAAG,MAAM,CAAC;AAE5B;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B;;OAEG;IACH,KAAK,CAAC,EAAE;QACN;;WAEG;QACH,aAAa,CAAC,EAAE,aAAa,CAAC;QAC9B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;KACxB,CAAC;CACH;AAED,gBAAgB;AAChB,MAAM,WAAW,OAAO;IACtB,MAAM,EAAE,MAAM,CAAC;IAGf,MAAM,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAC;CACjC;AAED,gBAAgB;AAChB,MAA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,WAAW,GACX,iBAAiB,GACjB,eAAe,GACf,eAAe,GACf,gBAAgB,GAChB,kBAAkB,GAClB,oBAAoB,GACpB,4BAA4B,GAC5B,mBAAmB,GACnB,gBAAgB,GAChB,kBAAkB,GAClB,eAAe,GACf,gBAAgB,CAAC;AAErB,gBAAgB;AAChB,MAAM,MAAM,kBAAkB,GAC1B,qBAAqB,GACrB,oBAAoB,GACpB,uBAAuB,GACvB,4BAA4B,CAAC;AAEjC,gBAAgB;AAChB,MAAM,MAAM,YAAY,GACpB,WAAW,GACX,mBAAmB,GACnB,eAAe,GACf,YAAY,CAAC;AAGjB,gBAAgB;AAChB,MAAM,MAAM,aAAa,GACrB,WAAW,GACX,oBAAoB,GACpB,gBAAgB,GAChB,aAAa,CAAC;AAElB,gBAAgB;AAChB,MAAM,MAAM,kBAAkB,GAC1B,qBAAqB,GACrB,oBAAoB,GACpB,0BAA0B,GAC1B,2BAA2B,GAC3B,+BAA+B,GAC/B,2BAA2B,GAC3B,6BAA6B,GAC7B,+BAA+B,CAAC;AAEpC,gBAAgB;AAChB,MAAM,MAAM,YAAY,GACpB,WAAW,GACX,gBAAgB,GAChB,cAAc,GACd,eAAe,GACf,iBAAiB,GACjB,2BAA2B,GAC3B,mBAAmB,GACnB,kBAAkB,GAClB,cAAc,GACd,eAAe,CAAC"} \ No newline at end of file diff --git a/dist/cjs/spec.types.js b/dist/cjs/spec.types.js new file mode 100644 index 0000000000..77bf7d35e4 --- /dev/null +++ b/dist/cjs/spec.types.js @@ -0,0 +1,27 @@ +"use strict"; +/** + * This file is automatically generated from the Model Context Protocol specification. + * + * Source: https://github.com/modelcontextprotocol/modelcontextprotocol + * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts + * Last updated from commit: 4528444698f76e6d0337e58d2941d5d3485d779d + * + * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. + * To update this file, run: npm run fetch:spec-types + */ /* JSON-RPC types */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.URL_ELICITATION_REQUIRED = exports.INTERNAL_ERROR = exports.INVALID_PARAMS = exports.METHOD_NOT_FOUND = exports.INVALID_REQUEST = exports.PARSE_ERROR = exports.JSONRPC_VERSION = exports.LATEST_PROTOCOL_VERSION = void 0; +/** @internal */ +exports.LATEST_PROTOCOL_VERSION = "DRAFT-2025-v3"; +/** @internal */ +exports.JSONRPC_VERSION = "2.0"; +// Standard JSON-RPC error codes +exports.PARSE_ERROR = -32700; +exports.INVALID_REQUEST = -32600; +exports.METHOD_NOT_FOUND = -32601; +exports.INVALID_PARAMS = -32602; +exports.INTERNAL_ERROR = -32603; +// Implementation-specific JSON-RPC error codes [-32000, -32099] +/** @internal */ +exports.URL_ELICITATION_REQUIRED = -32042; +//# sourceMappingURL=spec.types.js.map \ No newline at end of file diff --git a/dist/cjs/spec.types.js.map b/dist/cjs/spec.types.js.map new file mode 100644 index 0000000000..0a09728c5a --- /dev/null +++ b/dist/cjs/spec.types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"spec.types.js","sourceRoot":"","sources":["../../src/spec.types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG,CAAA,oBAAoB;;;AAavB,gBAAgB;AACH,QAAA,uBAAuB,GAAG,eAAe,CAAC;AACvD,gBAAgB;AACH,QAAA,eAAe,GAAG,KAAK,CAAC;AA4HrC,gCAAgC;AACnB,QAAA,WAAW,GAAG,CAAC,KAAK,CAAC;AACrB,QAAA,eAAe,GAAG,CAAC,KAAK,CAAC;AACzB,QAAA,gBAAgB,GAAG,CAAC,KAAK,CAAC;AAC1B,QAAA,cAAc,GAAG,CAAC,KAAK,CAAC;AACxB,QAAA,cAAc,GAAG,CAAC,KAAK,CAAC;AAErC,gEAAgE;AAChE,gBAAgB;AACH,QAAA,wBAAwB,GAAG,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/dist/cjs/types.d.ts b/dist/cjs/types.d.ts new file mode 100644 index 0000000000..392b544dd5 --- /dev/null +++ b/dist/cjs/types.d.ts @@ -0,0 +1,4390 @@ +import * as z from 'zod/v4'; +import { AuthInfo } from './server/auth/types.js'; +export declare const LATEST_PROTOCOL_VERSION = "2025-06-18"; +export declare const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; +export declare const SUPPORTED_PROTOCOL_VERSIONS: string[]; +export declare const JSONRPC_VERSION = "2.0"; +/** + * Utility types + */ +type ExpandRecursively = T extends object ? (T extends infer O ? { + [K in keyof O]: ExpandRecursively; +} : never) : T; +/** + * A progress token, used to associate progress notifications with the original request. + */ +export declare const ProgressTokenSchema: z.ZodUnion; +/** + * An opaque token used to represent a cursor for pagination. + */ +export declare const CursorSchema: z.ZodString; +declare const RequestMetaSchema: z.ZodObject<{ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: z.ZodOptional>; +}, z.core.$loose>; +/** + * Common params for any request. + */ +declare const BaseRequestParamsSchema: z.ZodObject<{ + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta: z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$loose>; +export declare const RequestSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; +}, z.core.$strip>; +declare const NotificationsParamsSchema: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; +}, z.core.$loose>; +export declare const NotificationSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$strip>; +export declare const ResultSchema: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; +}, z.core.$loose>; +/** + * A uniquely identifying ID for a request in JSON-RPC. + */ +export declare const RequestIdSchema: z.ZodUnion; +/** + * A request that expects a response. + */ +export declare const JSONRPCRequestSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; +}, z.core.$strict>; +export declare const isJSONRPCRequest: (value: unknown) => value is JSONRPCRequest; +/** + * A notification which does not expect a response. + */ +export declare const JSONRPCNotificationSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; +}, z.core.$strict>; +export declare const isJSONRPCNotification: (value: unknown) => value is JSONRPCNotification; +/** + * A successful (non-error) response to a request. + */ +export declare const JSONRPCResponseSchema: z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; + result: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + }, z.core.$loose>; +}, z.core.$strict>; +export declare const isJSONRPCResponse: (value: unknown) => value is JSONRPCResponse; +/** + * Error codes defined by the JSON-RPC specification. + */ +export declare enum ErrorCode { + ConnectionClosed = -32000, + RequestTimeout = -32001, + ParseError = -32700, + InvalidRequest = -32600, + MethodNotFound = -32601, + InvalidParams = -32602, + InternalError = -32603, + UrlElicitationRequired = -32042 +} +/** + * A response to a request that indicates an error occurred. + */ +export declare const JSONRPCErrorSchema: z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; + error: z.ZodObject<{ + code: z.ZodNumber; + message: z.ZodString; + data: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strict>; +export declare const isJSONRPCError: (value: unknown) => value is JSONRPCError; +export declare const JSONRPCMessageSchema: z.ZodUnion>; + }, z.core.$loose>>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; +}, z.core.$strict>, z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; +}, z.core.$strict>, z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; + result: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + }, z.core.$loose>; +}, z.core.$strict>, z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; + error: z.ZodObject<{ + code: z.ZodNumber; + message: z.ZodString; + data: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strict>]>; +/** + * A response that indicates success but carries no data. + */ +export declare const EmptyResultSchema: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; +}, z.core.$strict>; +export declare const CancelledNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + requestId: z.ZodUnion; + reason: z.ZodOptional; +}, z.core.$loose>; +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + */ +export declare const CancelledNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/cancelled">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + requestId: z.ZodUnion; + reason: z.ZodOptional; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * Icon schema for use in tools, prompts, resources, and implementations. + */ +export declare const IconSchema: z.ZodObject<{ + src: z.ZodString; + mimeType: z.ZodOptional; + sizes: z.ZodOptional>; +}, z.core.$strip>; +/** + * Base schema to add `icons` property. + * + */ +export declare const IconsSchema: z.ZodObject<{ + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; +}, z.core.$strip>; +/** + * Base metadata interface for common properties across resources, tools, prompts, and implementations. + */ +export declare const BaseMetadataSchema: z.ZodObject<{ + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Describes the name and version of an MCP implementation. + */ +export declare const ImplementationSchema: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ +export declare const ClientCapabilitiesSchema: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$strip>; +export declare const InitializeRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; + }, z.core.$strip>; + clientInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$loose>; +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ +export declare const InitializeRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"initialize">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; + }, z.core.$strip>; + clientInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + }, z.core.$loose>; +}, z.core.$strip>; +export declare const isInitializeRequest: (value: unknown) => value is InitializeRequest; +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ +export declare const ServerCapabilitiesSchema: z.ZodObject<{ + experimental: z.ZodOptional>>; + logging: z.ZodOptional>; + completions: z.ZodOptional>; + prompts: z.ZodOptional; + }, z.core.$strip>>; + resources: z.ZodOptional; + listChanged: z.ZodOptional; + }, z.core.$strip>>; + tools: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$strip>; +/** + * After receiving an initialize request from the client, the server sends this response. + */ +export declare const InitializeResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + logging: z.ZodOptional>; + completions: z.ZodOptional>; + prompts: z.ZodOptional; + }, z.core.$strip>>; + resources: z.ZodOptional; + listChanged: z.ZodOptional; + }, z.core.$strip>>; + tools: z.ZodOptional; + }, z.core.$strip>>; + }, z.core.$strip>; + serverInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + instructions: z.ZodOptional; +}, z.core.$loose>; +/** + * This notification is sent from the client to the server after initialization has finished. + */ +export declare const InitializedNotificationSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/initialized">; +}, z.core.$strip>; +export declare const isInitializedNotification: (value: unknown) => value is InitializedNotification; +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ +export declare const PingRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + method: z.ZodLiteral<"ping">; +}, z.core.$strip>; +export declare const ProgressSchema: z.ZodObject<{ + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; +}, z.core.$strip>; +export declare const ProgressNotificationParamsSchema: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ +export declare const ProgressNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/progress">; + params: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>; +export declare const PaginatedRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; +}, z.core.$loose>; +export declare const PaginatedRequestSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; +}, z.core.$strip>; +export declare const PaginatedResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; +}, z.core.$loose>; +/** + * The contents of a specific resource or sub-resource. + */ +export declare const ResourceContentsSchema: z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$strip>; +export declare const TextResourceContentsSchema: z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + text: z.ZodString; +}, z.core.$strip>; +export declare const BlobResourceContentsSchema: z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; +}, z.core.$strip>; +/** + * A known resource that the server is capable of reading. + */ +export declare const ResourceSchema: z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * A template description for resources available on the server. + */ +export declare const ResourceTemplateSchema: z.ZodObject<{ + uriTemplate: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Sent from the client to request a list of resources the server has. + */ +export declare const ListResourcesRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"resources/list">; +}, z.core.$strip>; +/** + * The server's response to a resources/list request from the client. + */ +export declare const ListResourcesResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + resources: z.ZodArray; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * Sent from the client to request a list of resource templates the server has. + */ +export declare const ListResourceTemplatesRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"resources/templates/list">; +}, z.core.$strip>; +/** + * The server's response to a resources/templates/list request from the client. + */ +export declare const ListResourceTemplatesResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + resourceTemplates: z.ZodArray; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +export declare const ResourceRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$loose>; +/** + * Parameters for a `resources/read` request. + */ +export declare const ReadResourceRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$loose>; +/** + * Sent from the client to the server, to read a specific resource URI. + */ +export declare const ReadResourceRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"resources/read">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * The server's response to a resources/read request from the client. + */ +export declare const ReadResourceResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + contents: z.ZodArray; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>>; +}, z.core.$loose>; +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ +export declare const ResourceListChangedNotificationSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/resources/list_changed">; +}, z.core.$strip>; +export declare const SubscribeRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$loose>; +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + */ +export declare const SubscribeRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"resources/subscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>; +export declare const UnsubscribeRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$loose>; +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + */ +export declare const UnsubscribeRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"resources/unsubscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * Parameters for a `notifications/resources/updated` notification. + */ +export declare const ResourceUpdatedNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + uri: z.ZodString; +}, z.core.$loose>; +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + */ +export declare const ResourceUpdatedNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/resources/updated">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * Describes an argument that a prompt can accept. + */ +export declare const PromptArgumentSchema: z.ZodObject<{ + name: z.ZodString; + description: z.ZodOptional; + required: z.ZodOptional; +}, z.core.$strip>; +/** + * A prompt or prompt template that the server offers. + */ +export declare const PromptSchema: z.ZodObject<{ + description: z.ZodOptional; + arguments: z.ZodOptional; + required: z.ZodOptional; + }, z.core.$strip>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ +export declare const ListPromptsRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"prompts/list">; +}, z.core.$strip>; +/** + * The server's response to a prompts/list request from the client. + */ +export declare const ListPromptsResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + prompts: z.ZodArray; + arguments: z.ZodOptional; + required: z.ZodOptional; + }, z.core.$strip>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * Parameters for a `prompts/get` request. + */ +export declare const GetPromptRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; +}, z.core.$loose>; +/** + * Used by the client to get a prompt provided by the server. + */ +export declare const GetPromptRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"prompts/get">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * Text provided to or from an LLM. + */ +export declare const TextContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"text">; + text: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * An image provided to or from an LLM. + */ +export declare const ImageContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * An Audio provided to or from an LLM. + */ +export declare const AudioContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + */ +export declare const ToolUseContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; +}, z.core.$loose>; +/** + * The contents of a resource, embedded into a prompt or tool call result. + */ +export declare const EmbeddedResourceSchema: z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + */ +export declare const ResourceLinkSchema: z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; +}, z.core.$strip>; +/** + * A content block that can be used in prompts and tool results. + */ +export declare const ContentBlockSchema: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; +}, z.core.$strip>]>; +/** + * Describes a message returned as part of a prompt. + */ +export declare const PromptMessageSchema: z.ZodObject<{ + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; +}, z.core.$strip>; +/** + * The server's response to a prompts/get request from the client. + */ +export declare const GetPromptResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + description: z.ZodOptional; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export declare const PromptListChangedNotificationSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/prompts/list_changed">; +}, z.core.$strip>; +/** + * Security scheme indicating no authentication is required. + */ +export declare const NoAuthSecuritySchemeSchema: z.ZodObject<{ + type: z.ZodLiteral<"noauth">; +}, z.core.$strip>; +/** + * Security scheme indicating OAuth 2.0 authentication is required. + */ +export declare const OAuth2SecuritySchemeSchema: z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; +}, z.core.$strip>; +/** + * A security scheme that can be used to authenticate tool calls. + */ +export declare const SecuritySchemeSchema: z.ZodUnion; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; +}, z.core.$strip>]>; +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + */ +export declare const ToolAnnotationsSchema: z.ZodObject<{ + title: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; +}, z.core.$strip>; +/** + * Definition for a tool the client can call. + */ +export declare const ToolSchema: z.ZodObject<{ + description: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + securitySchemes: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; + }, z.core.$strip>]>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Sent from the client to request a list of tools the server has. + */ +export declare const ListToolsRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"tools/list">; +}, z.core.$strip>; +/** + * The server's response to a tools/list request from the client. + */ +export declare const ListToolsResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + tools: z.ZodArray; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + securitySchemes: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; + }, z.core.$strip>]>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * The server's response to a tool call. + */ +export declare const CallToolResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; +}, z.core.$loose>; +/** + * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. + */ +export declare const CompatibilityCallToolResultSchema: z.ZodUnion<[z.ZodObject<{ + _meta: z.ZodOptional>; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + toolResult: z.ZodUnknown; +}, z.core.$loose>]>; +/** + * Parameters for a `tools/call` request. + */ +export declare const CallToolRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; +}, z.core.$loose>; +/** + * Used by the client to invoke a tool provided by the server. + */ +export declare const CallToolRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"tools/call">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export declare const ToolListChangedNotificationSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/tools/list_changed">; +}, z.core.$strip>; +/** + * The severity of a log message. + */ +export declare const LoggingLevelSchema: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; +}>; +/** + * Parameters for a `logging/setLevel` request. + */ +export declare const SetLevelRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; +}, z.core.$loose>; +/** + * A request from the client to the server, to enable or adjust logging. + */ +export declare const SetLevelRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"logging/setLevel">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * Parameters for a `notifications/message` notification. + */ +export declare const LoggingMessageNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + logger: z.ZodOptional; + data: z.ZodUnknown; +}, z.core.$loose>; +/** + * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + */ +export declare const LoggingMessageNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/message">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + logger: z.ZodOptional; + data: z.ZodUnknown; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * Hints to use for model selection. + */ +export declare const ModelHintSchema: z.ZodObject<{ + name: z.ZodOptional; +}, z.core.$strip>; +/** + * The server's preferences for model selection, requested of the client during sampling. + */ +export declare const ModelPreferencesSchema: z.ZodObject<{ + hints: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; +}, z.core.$strip>; +/** + * Controls tool usage behavior in sampling requests. + */ +export declare const ToolChoiceSchema: z.ZodObject<{ + mode: z.ZodOptional>; +}, z.core.$strip>; +/** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via ToolUseContent. + */ +export declare const ToolResultContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$loose>; +/** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + */ +export declare const SamplingMessageContentBlockSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ + type: z.ZodLiteral<"text">; + text: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; +}, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$loose>]>; +/** + * Describes a message issued to or received from an LLM API. + */ +export declare const SamplingMessageSchema: z.ZodObject<{ + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>, z.ZodArray; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>>]>; + _meta: z.ZodOptional>; +}, z.core.$loose>; +/** + * Parameters for a `sampling/createMessage` request. + */ +export declare const CreateMessageRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>, z.ZodArray; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>>]>; + _meta: z.ZodOptional>; + }, z.core.$loose>>; + modelPreferences: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; + }, z.core.$strip>>; + systemPrompt: z.ZodOptional; + includeContext: z.ZodOptional>; + temperature: z.ZodOptional; + maxTokens: z.ZodNumber; + stopSequences: z.ZodOptional>; + metadata: z.ZodOptional>; + tools: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + securitySchemes: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; + }, z.core.$strip>]>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>>; + toolChoice: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + */ +export declare const CreateMessageRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"sampling/createMessage">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>, z.ZodArray; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>>]>; + _meta: z.ZodOptional>; + }, z.core.$loose>>; + modelPreferences: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; + }, z.core.$strip>>; + systemPrompt: z.ZodOptional; + includeContext: z.ZodOptional>; + temperature: z.ZodOptional; + maxTokens: z.ZodNumber; + stopSequences: z.ZodOptional>; + metadata: z.ZodOptional>; + tools: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + securitySchemes: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; + }, z.core.$strip>]>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>>; + toolChoice: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. + */ +export declare const CreateMessageResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + model: z.ZodString; + stopReason: z.ZodOptional, z.ZodString]>>; + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>, z.ZodArray; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>>]>; +}, z.core.$loose>; +/** + * Primitive schema definition for boolean fields. + */ +export declare const BooleanSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Primitive schema definition for string fields. + */ +export declare const StringSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Primitive schema definition for number fields. + */ +export declare const NumberSchemaSchema: z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Schema for single-selection enumeration without display titles for options. + */ +export declare const UntitledSingleSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Schema for single-selection enumeration with display titles for each option. + */ +export declare const TitledSingleSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + */ +export declare const LegacyTitledEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>; +export declare const SingleSelectEnumSchemaSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>]>; +/** + * Schema for multiple-selection enumeration without display titles for options. + */ +export declare const UntitledMultiSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>; +/** + * Schema for multiple-selection enumeration with display titles for each option. + */ +export declare const TitledMultiSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>; +/** + * Combined schema for multiple-selection enumeration + */ +export declare const MultiSelectEnumSchemaSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>]>; +/** + * Primitive schema definition for enum fields. + */ +export declare const EnumSchemaSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>]>]>; +/** + * Union of all primitive schema definitions. + */ +export declare const PrimitiveSchemaDefinitionSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>]>; +/** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ +export declare const ElicitRequestFormParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"form">; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$loose>; +/** + * Parameters for an `elicitation/create` request for URL-based elicitation. + */ +export declare const ElicitRequestURLParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; +}, z.core.$loose>; +/** + * The parameters for a request to elicit additional information from the user via the client. + */ +export declare const ElicitRequestParamsSchema: z.ZodUnion>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"form">; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; +}, z.core.$loose>]>; +/** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ +export declare const ElicitRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"elicitation/create">; + params: z.ZodUnion>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"form">; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; + }, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; + }, z.core.$loose>]>; +}, z.core.$strip>; +/** + * Parameters for a `notifications/elicitation/complete` notification. + * + * @category notifications/elicitation/complete + */ +export declare const ElicitationCompleteNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + elicitationId: z.ZodString; +}, z.core.$loose>; +/** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ +export declare const ElicitationCompleteNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/elicitation/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + elicitationId: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * The client's response to an elicitation/create request from the server. + */ +export declare const ElicitResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + action: z.ZodEnum<{ + accept: "accept"; + decline: "decline"; + cancel: "cancel"; + }>; + content: z.ZodOptional]>>>; +}, z.core.$loose>; +/** + * A reference to a resource or resource template definition. + */ +export declare const ResourceTemplateReferenceSchema: z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; +}, z.core.$strip>; +/** + * @deprecated Use ResourceTemplateReferenceSchema instead + */ +export declare const ResourceReferenceSchema: z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; +}, z.core.$strip>; +/** + * Identifies a prompt. + */ +export declare const PromptReferenceSchema: z.ZodObject<{ + type: z.ZodLiteral<"ref/prompt">; + name: z.ZodString; +}, z.core.$strip>; +/** + * Parameters for a `completion/complete` request. + */ +export declare const CompleteRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + ref: z.ZodUnion; + name: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; + }, z.core.$strip>]>; + argument: z.ZodObject<{ + name: z.ZodString; + value: z.ZodString; + }, z.core.$strip>; + context: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * A request from the client to the server, to ask for completion options. + */ +export declare const CompleteRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"completion/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + ref: z.ZodUnion; + name: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; + }, z.core.$strip>]>; + argument: z.ZodObject<{ + name: z.ZodString; + value: z.ZodString; + }, z.core.$strip>; + context: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$loose>; +}, z.core.$strip>; +export declare function assertCompleteRequestPrompt(request: CompleteRequest): asserts request is CompleteRequestPrompt; +export declare function assertCompleteRequestResourceTemplate(request: CompleteRequest): asserts request is CompleteRequestResourceTemplate; +/** + * The server's response to a completion/complete request + */ +export declare const CompleteResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + completion: z.ZodObject<{ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.ZodArray; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.ZodOptional; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.ZodOptional; + }, z.core.$loose>; +}, z.core.$loose>; +/** + * Represents a root directory or file that the server can operate on. + */ +export declare const RootSchema: z.ZodObject<{ + uri: z.ZodString; + name: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * Sent from the server to request a list of root URIs from the client. + */ +export declare const ListRootsRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + method: z.ZodLiteral<"roots/list">; +}, z.core.$strip>; +/** + * The client's response to a roots/list request from the server. + */ +export declare const ListRootsResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + roots: z.ZodArray; + _meta: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * A notification from the client to the server, informing it that the list of roots has changed. + */ +export declare const RootsListChangedNotificationSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/roots/list_changed">; +}, z.core.$strip>; +export declare const ClientRequestSchema: z.ZodUnion>; + }, z.core.$loose>>; + }, z.core.$loose>>; + method: z.ZodLiteral<"ping">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"initialize">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; + }, z.core.$strip>; + clientInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"completion/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + ref: z.ZodUnion; + name: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; + }, z.core.$strip>]>; + argument: z.ZodObject<{ + name: z.ZodString; + value: z.ZodString; + }, z.core.$strip>; + context: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"logging/setLevel">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"prompts/get">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"prompts/list">; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"resources/list">; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"resources/templates/list">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"resources/read">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"resources/subscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"resources/unsubscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tools/call">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"tools/list">; +}, z.core.$strip>]>; +export declare const ClientNotificationSchema: z.ZodUnion; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + requestId: z.ZodUnion; + reason: z.ZodOptional; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/progress">; + params: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/initialized">; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/roots/list_changed">; +}, z.core.$strip>]>; +export declare const ClientResultSchema: z.ZodUnion>; +}, z.core.$strict>, z.ZodObject<{ + _meta: z.ZodOptional>; + model: z.ZodString; + stopReason: z.ZodOptional, z.ZodString]>>; + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>, z.ZodArray; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>>]>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + action: z.ZodEnum<{ + accept: "accept"; + decline: "decline"; + cancel: "cancel"; + }>; + content: z.ZodOptional]>>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + roots: z.ZodArray; + _meta: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$loose>]>; +export declare const ServerRequestSchema: z.ZodUnion>; + }, z.core.$loose>>; + }, z.core.$loose>>; + method: z.ZodLiteral<"ping">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"sampling/createMessage">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>, z.ZodArray; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>>]>; + _meta: z.ZodOptional>; + }, z.core.$loose>>; + modelPreferences: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; + }, z.core.$strip>>; + systemPrompt: z.ZodOptional; + includeContext: z.ZodOptional>; + temperature: z.ZodOptional; + maxTokens: z.ZodNumber; + stopSequences: z.ZodOptional>; + metadata: z.ZodOptional>; + tools: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + securitySchemes: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; + }, z.core.$strip>]>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>>; + toolChoice: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"elicitation/create">; + params: z.ZodUnion>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"form">; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; + }, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; + }, z.core.$loose>]>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + method: z.ZodLiteral<"roots/list">; +}, z.core.$strip>]>; +export declare const ServerNotificationSchema: z.ZodUnion; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + requestId: z.ZodUnion; + reason: z.ZodOptional; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/progress">; + params: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/message">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + logger: z.ZodOptional; + data: z.ZodUnknown; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/resources/updated">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/resources/list_changed">; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/tools/list_changed">; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/prompts/list_changed">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/elicitation/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + elicitationId: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>]>; +export declare const ServerResultSchema: z.ZodUnion>; +}, z.core.$strict>, z.ZodObject<{ + _meta: z.ZodOptional>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + logging: z.ZodOptional>; + completions: z.ZodOptional>; + prompts: z.ZodOptional; + }, z.core.$strip>>; + resources: z.ZodOptional; + listChanged: z.ZodOptional; + }, z.core.$strip>>; + tools: z.ZodOptional; + }, z.core.$strip>>; + }, z.core.$strip>; + serverInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + instructions: z.ZodOptional; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + completion: z.ZodObject<{ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.ZodArray; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.ZodOptional; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.ZodOptional; + }, z.core.$loose>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + description: z.ZodOptional; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + prompts: z.ZodArray; + arguments: z.ZodOptional; + required: z.ZodOptional; + }, z.core.$strip>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + resources: z.ZodArray; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + resourceTemplates: z.ZodArray; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + contents: z.ZodArray; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + tools: z.ZodArray; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + securitySchemes: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; + }, z.core.$strip>]>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>]>; +export declare class McpError extends Error { + readonly code: number; + readonly data?: unknown; + constructor(code: number, message: string, data?: unknown); + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code: number, message: string, data?: unknown): McpError; +} +/** + * Specialized error type when a tool requires a URL mode elicitation. + * 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. + */ +export declare class UrlElicitationRequiredError extends McpError { + constructor(elicitations: ElicitRequestURLParams[], message?: string); + get elicitations(): ElicitRequestURLParams[]; +} +type Primitive = string | number | boolean | bigint | null | undefined; +type Flatten = T extends Primitive ? T : T extends Array ? Array> : T extends Set ? Set> : T extends Map ? Map, Flatten> : T extends object ? { + [K in keyof T]: Flatten; +} : T; +type Infer = Flatten>; +/** + * Headers that are compatible with both Node.js and the browser. + */ +export type IsomorphicHeaders = Record; +/** + * Information about the incoming request. + */ +export interface RequestInfo { + /** + * The headers of the request. + */ + headers: IsomorphicHeaders; +} +/** + * Extra information about a message. + */ +export interface MessageExtraInfo { + /** + * The request information. + */ + requestInfo?: RequestInfo; + /** + * The authentication information. + */ + authInfo?: AuthInfo; +} +export type ProgressToken = Infer; +export type Cursor = Infer; +export type Request = Infer; +export type RequestMeta = Infer; +export type Notification = Infer; +export type Result = Infer; +export type RequestId = Infer; +export type JSONRPCRequest = Infer; +export type JSONRPCNotification = Infer; +export type JSONRPCResponse = Infer; +export type JSONRPCError = Infer; +export type JSONRPCMessage = Infer; +export type RequestParams = Infer; +export type NotificationParams = Infer; +export type EmptyResult = Infer; +export type CancelledNotificationParams = Infer; +export type CancelledNotification = Infer; +export type Icon = Infer; +export type Icons = Infer; +export type BaseMetadata = Infer; +export type Implementation = Infer; +export type ClientCapabilities = Infer; +export type InitializeRequestParams = Infer; +export type InitializeRequest = Infer; +export type ServerCapabilities = Infer; +export type InitializeResult = Infer; +export type InitializedNotification = Infer; +export type PingRequest = Infer; +export type Progress = Infer; +export type ProgressNotificationParams = Infer; +export type ProgressNotification = Infer; +export type PaginatedRequestParams = Infer; +export type PaginatedRequest = Infer; +export type PaginatedResult = Infer; +export type ResourceContents = Infer; +export type TextResourceContents = Infer; +export type BlobResourceContents = Infer; +export type Resource = Infer; +export type ResourceTemplate = Infer; +export type ListResourcesRequest = Infer; +export type ListResourcesResult = Infer; +export type ListResourceTemplatesRequest = Infer; +export type ListResourceTemplatesResult = Infer; +export type ResourceRequestParams = Infer; +export type ReadResourceRequestParams = Infer; +export type ReadResourceRequest = Infer; +export type ReadResourceResult = Infer; +export type ResourceListChangedNotification = Infer; +export type SubscribeRequestParams = Infer; +export type SubscribeRequest = Infer; +export type UnsubscribeRequestParams = Infer; +export type UnsubscribeRequest = Infer; +export type ResourceUpdatedNotificationParams = Infer; +export type ResourceUpdatedNotification = Infer; +export type PromptArgument = Infer; +export type Prompt = Infer; +export type ListPromptsRequest = Infer; +export type ListPromptsResult = Infer; +export type GetPromptRequestParams = Infer; +export type GetPromptRequest = Infer; +export type TextContent = Infer; +export type ImageContent = Infer; +export type AudioContent = Infer; +export type ToolUseContent = Infer; +export type ToolResultContent = Infer; +export type EmbeddedResource = Infer; +export type ResourceLink = Infer; +export type ContentBlock = Infer; +export type PromptMessage = Infer; +export type GetPromptResult = Infer; +export type PromptListChangedNotification = Infer; +export type NoAuthSecurityScheme = Infer; +export type OAuth2SecurityScheme = Infer; +export type SecurityScheme = Infer; +export type ToolAnnotations = Infer; +export type Tool = Infer; +export type ListToolsRequest = Infer; +export type ListToolsResult = Infer; +export type CallToolRequestParams = Infer; +export type CallToolResult = Infer; +export type CompatibilityCallToolResult = Infer; +export type CallToolRequest = Infer; +export type ToolListChangedNotification = Infer; +export type LoggingLevel = Infer; +export type SetLevelRequestParams = Infer; +export type SetLevelRequest = Infer; +export type LoggingMessageNotificationParams = Infer; +export type LoggingMessageNotification = Infer; +export type ToolChoice = Infer; +export type ModelHint = Infer; +export type ModelPreferences = Infer; +export type SamplingMessageContentBlock = Infer; +export type SamplingMessage = Infer; +export type CreateMessageRequestParams = Infer; +export type CreateMessageRequest = Infer; +export type CreateMessageResult = Infer; +export type BooleanSchema = Infer; +export type StringSchema = Infer; +export type NumberSchema = Infer; +export type EnumSchema = Infer; +export type UntitledSingleSelectEnumSchema = Infer; +export type TitledSingleSelectEnumSchema = Infer; +export type LegacyTitledEnumSchema = Infer; +export type UntitledMultiSelectEnumSchema = Infer; +export type TitledMultiSelectEnumSchema = Infer; +export type SingleSelectEnumSchema = Infer; +export type MultiSelectEnumSchema = Infer; +export type PrimitiveSchemaDefinition = Infer; +export type ElicitRequestParams = Infer; +export type ElicitRequestFormParams = Infer; +export type ElicitRequestURLParams = Infer; +export type ElicitRequest = Infer; +export type ElicitationCompleteNotificationParams = Infer; +export type ElicitationCompleteNotification = Infer; +export type ElicitResult = Infer; +export type ResourceTemplateReference = Infer; +/** + * @deprecated Use ResourceTemplateReference instead + */ +export type ResourceReference = ResourceTemplateReference; +export type PromptReference = Infer; +export type CompleteRequestParams = Infer; +export type CompleteRequest = Infer; +export type CompleteRequestResourceTemplate = ExpandRecursively; +export type CompleteRequestPrompt = ExpandRecursively; +export type CompleteResult = Infer; +export type Root = Infer; +export type ListRootsRequest = Infer; +export type ListRootsResult = Infer; +export type RootsListChangedNotification = Infer; +export type ClientRequest = Infer; +export type ClientNotification = Infer; +export type ClientResult = Infer; +export type ServerRequest = Infer; +export type ServerNotification = Infer; +export type ServerResult = Infer; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/cjs/types.d.ts.map b/dist/cjs/types.d.ts.map new file mode 100644 index 0000000000..39761f83d0 --- /dev/null +++ b/dist/cjs/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAElD,eAAO,MAAM,uBAAuB,eAAe,CAAC;AACpD,eAAO,MAAM,mCAAmC,eAAe,CAAC;AAChE,eAAO,MAAM,2BAA2B,UAAsE,CAAC;AAG/G,eAAO,MAAM,eAAe,QAAQ,CAAC;AAErC;;GAEG;AACH,KAAK,iBAAiB,CAAC,CAAC,IAAI,CAAC,SAAS,MAAM,GAAG,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAAE,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;AAO7H;;GAEG;AACH,eAAO,MAAM,mBAAmB,iDAA0C,CAAC;AAE3E;;GAEG;AACH,eAAO,MAAM,YAAY,aAAa,CAAC;AAEvC,QAAA,MAAM,iBAAiB;IACnB;;OAEG;;iBAEL,CAAC;AAEH;;GAEG;AACH,QAAA,MAAM,uBAAuB;IACzB;;OAEG;;QAZH;;WAEG;;;iBAYL,CAAC;AAEH,eAAO,MAAM,aAAa;;;QANtB;;WAEG;;YAZH;;eAEG;;;;iBAiBL,CAAC;AAEH,QAAA,MAAM,yBAAyB;IAC3B;;;OAGG;;iBAEL,CAAC;AAEH,eAAO,MAAM,kBAAkB;;;QAP3B;;;WAGG;;;iBAOL,CAA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AK,CAAC,OAAO,kBAAkB,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/types.js b/dist/cjs/types.js new file mode 100644 index 0000000000..b269cc3a84 --- /dev/null +++ b/dist/cjs/types.js @@ -0,0 +1,1697 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ListResourceTemplatesRequestSchema = exports.ListResourcesResultSchema = exports.ListResourcesRequestSchema = exports.ResourceTemplateSchema = exports.ResourceSchema = exports.BlobResourceContentsSchema = exports.TextResourceContentsSchema = exports.ResourceContentsSchema = exports.PaginatedResultSchema = exports.PaginatedRequestSchema = exports.PaginatedRequestParamsSchema = exports.ProgressNotificationSchema = exports.ProgressNotificationParamsSchema = exports.ProgressSchema = exports.PingRequestSchema = exports.isInitializedNotification = exports.InitializedNotificationSchema = exports.InitializeResultSchema = exports.ServerCapabilitiesSchema = exports.isInitializeRequest = exports.InitializeRequestSchema = exports.InitializeRequestParamsSchema = exports.ClientCapabilitiesSchema = exports.ImplementationSchema = exports.BaseMetadataSchema = exports.IconsSchema = exports.IconSchema = exports.CancelledNotificationSchema = exports.CancelledNotificationParamsSchema = exports.EmptyResultSchema = exports.JSONRPCMessageSchema = exports.isJSONRPCError = exports.JSONRPCErrorSchema = exports.ErrorCode = exports.isJSONRPCResponse = exports.JSONRPCResponseSchema = exports.isJSONRPCNotification = exports.JSONRPCNotificationSchema = exports.isJSONRPCRequest = exports.JSONRPCRequestSchema = exports.RequestIdSchema = exports.ResultSchema = exports.NotificationSchema = exports.RequestSchema = exports.CursorSchema = exports.ProgressTokenSchema = exports.JSONRPC_VERSION = exports.SUPPORTED_PROTOCOL_VERSIONS = exports.DEFAULT_NEGOTIATED_PROTOCOL_VERSION = exports.LATEST_PROTOCOL_VERSION = void 0; +exports.SamplingMessageContentBlockSchema = exports.ToolResultContentSchema = exports.ToolChoiceSchema = exports.ModelPreferencesSchema = exports.ModelHintSchema = exports.LoggingMessageNotificationSchema = exports.LoggingMessageNotificationParamsSchema = exports.SetLevelRequestSchema = exports.SetLevelRequestParamsSchema = exports.LoggingLevelSchema = exports.ToolListChangedNotificationSchema = exports.CallToolRequestSchema = exports.CallToolRequestParamsSchema = exports.CompatibilityCallToolResultSchema = exports.CallToolResultSchema = exports.ListToolsResultSchema = exports.ListToolsRequestSchema = exports.ToolSchema = exports.ToolAnnotationsSchema = exports.SecuritySchemeSchema = exports.OAuth2SecuritySchemeSchema = exports.NoAuthSecuritySchemeSchema = exports.PromptListChangedNotificationSchema = exports.GetPromptResultSchema = exports.PromptMessageSchema = exports.ContentBlockSchema = exports.ResourceLinkSchema = exports.EmbeddedResourceSchema = exports.ToolUseContentSchema = exports.AudioContentSchema = exports.ImageContentSchema = exports.TextContentSchema = exports.GetPromptRequestSchema = exports.GetPromptRequestParamsSchema = exports.ListPromptsResultSchema = exports.ListPromptsRequestSchema = exports.PromptSchema = exports.PromptArgumentSchema = exports.ResourceUpdatedNotificationSchema = exports.ResourceUpdatedNotificationParamsSchema = exports.UnsubscribeRequestSchema = exports.UnsubscribeRequestParamsSchema = exports.SubscribeRequestSchema = exports.SubscribeRequestParamsSchema = exports.ResourceListChangedNotificationSchema = exports.ReadResourceResultSchema = exports.ReadResourceRequestSchema = exports.ReadResourceRequestParamsSchema = exports.ResourceRequestParamsSchema = exports.ListResourceTemplatesResultSchema = void 0; +exports.UrlElicitationRequiredError = exports.McpError = exports.ServerResultSchema = exports.ServerNotificationSchema = exports.ServerRequestSchema = exports.ClientResultSchema = exports.ClientNotificationSchema = exports.ClientRequestSchema = exports.RootsListChangedNotificationSchema = exports.ListRootsResultSchema = exports.ListRootsRequestSchema = exports.RootSchema = exports.CompleteResultSchema = exports.CompleteRequestSchema = exports.CompleteRequestParamsSchema = exports.PromptReferenceSchema = exports.ResourceReferenceSchema = exports.ResourceTemplateReferenceSchema = exports.ElicitResultSchema = exports.ElicitationCompleteNotificationSchema = exports.ElicitationCompleteNotificationParamsSchema = exports.ElicitRequestSchema = exports.ElicitRequestParamsSchema = exports.ElicitRequestURLParamsSchema = exports.ElicitRequestFormParamsSchema = exports.PrimitiveSchemaDefinitionSchema = exports.EnumSchemaSchema = exports.MultiSelectEnumSchemaSchema = exports.TitledMultiSelectEnumSchemaSchema = exports.UntitledMultiSelectEnumSchemaSchema = exports.SingleSelectEnumSchemaSchema = exports.LegacyTitledEnumSchemaSchema = exports.TitledSingleSelectEnumSchemaSchema = exports.UntitledSingleSelectEnumSchemaSchema = exports.NumberSchemaSchema = exports.StringSchemaSchema = exports.BooleanSchemaSchema = exports.CreateMessageResultSchema = exports.CreateMessageRequestSchema = exports.CreateMessageRequestParamsSchema = exports.SamplingMessageSchema = void 0; +exports.assertCompleteRequestPrompt = assertCompleteRequestPrompt; +exports.assertCompleteRequestResourceTemplate = assertCompleteRequestResourceTemplate; +const z = __importStar(require("zod/v4")); +exports.LATEST_PROTOCOL_VERSION = '2025-06-18'; +exports.DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26'; +exports.SUPPORTED_PROTOCOL_VERSIONS = [exports.LATEST_PROTOCOL_VERSION, '2025-03-26', '2024-11-05', '2024-10-07']; +/* JSON-RPC types */ +exports.JSONRPC_VERSION = '2.0'; +/** + * Assert 'object' type schema. + * + * @internal + */ +const AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function')); +/** + * A progress token, used to associate progress notifications with the original request. + */ +exports.ProgressTokenSchema = z.union([z.string(), z.number().int()]); +/** + * An opaque token used to represent a cursor for pagination. + */ +exports.CursorSchema = z.string(); +const RequestMetaSchema = z.looseObject({ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: exports.ProgressTokenSchema.optional() +}); +/** + * Common params for any request. + */ +const BaseRequestParamsSchema = z.looseObject({ + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta: RequestMetaSchema.optional() +}); +exports.RequestSchema = z.object({ + method: z.string(), + params: BaseRequestParamsSchema.optional() +}); +const NotificationsParamsSchema = z.looseObject({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +exports.NotificationSchema = z.object({ + method: z.string(), + params: NotificationsParamsSchema.optional() +}); +exports.ResultSchema = z.looseObject({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * A uniquely identifying ID for a request in JSON-RPC. + */ +exports.RequestIdSchema = z.union([z.string(), z.number().int()]); +/** + * A request that expects a response. + */ +exports.JSONRPCRequestSchema = z + .object({ + jsonrpc: z.literal(exports.JSONRPC_VERSION), + id: exports.RequestIdSchema, + ...exports.RequestSchema.shape +}) + .strict(); +const isJSONRPCRequest = (value) => exports.JSONRPCRequestSchema.safeParse(value).success; +exports.isJSONRPCRequest = isJSONRPCRequest; +/** + * A notification which does not expect a response. + */ +exports.JSONRPCNotificationSchema = z + .object({ + jsonrpc: z.literal(exports.JSONRPC_VERSION), + ...exports.NotificationSchema.shape +}) + .strict(); +const isJSONRPCNotification = (value) => exports.JSONRPCNotificationSchema.safeParse(value).success; +exports.isJSONRPCNotification = isJSONRPCNotification; +/** + * A successful (non-error) response to a request. + */ +exports.JSONRPCResponseSchema = z + .object({ + jsonrpc: z.literal(exports.JSONRPC_VERSION), + id: exports.RequestIdSchema, + result: exports.ResultSchema +}) + .strict(); +const isJSONRPCResponse = (value) => exports.JSONRPCResponseSchema.safeParse(value).success; +exports.isJSONRPCResponse = isJSONRPCResponse; +/** + * Error codes defined by the JSON-RPC specification. + */ +var ErrorCode; +(function (ErrorCode) { + // SDK error codes + ErrorCode[ErrorCode["ConnectionClosed"] = -32000] = "ConnectionClosed"; + ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout"; + // Standard JSON-RPC error codes + ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError"; + ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest"; + ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound"; + ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams"; + ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError"; + // MCP-specific error codes + ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; +})(ErrorCode || (exports.ErrorCode = ErrorCode = {})); +/** + * A response to a request that indicates an error occurred. + */ +exports.JSONRPCErrorSchema = z + .object({ + jsonrpc: z.literal(exports.JSONRPC_VERSION), + id: exports.RequestIdSchema, + error: z.object({ + /** + * The error type that occurred. + */ + code: z.number().int(), + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: z.string(), + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data: z.optional(z.unknown()) + }) +}) + .strict(); +const isJSONRPCError = (value) => exports.JSONRPCErrorSchema.safeParse(value).success; +exports.isJSONRPCError = isJSONRPCError; +exports.JSONRPCMessageSchema = z.union([exports.JSONRPCRequestSchema, exports.JSONRPCNotificationSchema, exports.JSONRPCResponseSchema, exports.JSONRPCErrorSchema]); +/* Empty result */ +/** + * A response that indicates success but carries no data. + */ +exports.EmptyResultSchema = exports.ResultSchema.strict(); +exports.CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: exports.RequestIdSchema, + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason: z.string().optional() +}); +/* Cancellation */ +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + */ +exports.CancelledNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/cancelled'), + params: exports.CancelledNotificationParamsSchema +}); +/* Base Metadata */ +/** + * Icon schema for use in tools, prompts, resources, and implementations. + */ +exports.IconSchema = z.object({ + /** + * URL or data URI for the icon. + */ + src: z.string(), + /** + * Optional MIME type for the icon. + */ + mimeType: z.string().optional(), + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes: z.array(z.string()).optional() +}); +/** + * Base schema to add `icons` property. + * + */ +exports.IconsSchema = z.object({ + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons: z.array(exports.IconSchema).optional() +}); +/** + * Base metadata interface for common properties across resources, tools, prompts, and implementations. + */ +exports.BaseMetadataSchema = z.object({ + /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ + name: z.string(), + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title: z.string().optional() +}); +/* Initialization */ +/** + * Describes the name and version of an MCP implementation. + */ +exports.ImplementationSchema = exports.BaseMetadataSchema.extend({ + ...exports.BaseMetadataSchema.shape, + ...exports.IconsSchema.shape, + version: z.string(), + /** + * An optional URL of the website for this implementation. + */ + websiteUrl: z.string().optional() +}); +const FormElicitationCapabilitySchema = z.intersection(z.object({ + applyDefaults: z.boolean().optional() +}), z.record(z.string(), z.unknown())); +const ElicitationCapabilitySchema = z.preprocess(value => { + if (value && typeof value === 'object' && !Array.isArray(value)) { + if (Object.keys(value).length === 0) { + return { form: {} }; + } + } + return value; +}, z.intersection(z.object({ + form: FormElicitationCapabilitySchema.optional(), + url: AssertObjectSchema.optional() +}), z.record(z.string(), z.unknown()).optional())); +/** + * 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. + */ +exports.ClientCapabilitiesSchema = z.object({ + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental: z.record(z.string(), AssertObjectSchema).optional(), + /** + * Present if the client supports sampling from an LLM. + */ + sampling: z + .object({ + /** + * Present if the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context: AssertObjectSchema.optional(), + /** + * Present if the client supports tool use via tools and toolChoice parameters. + */ + tools: AssertObjectSchema.optional() + }) + .optional(), + /** + * Present if the client supports eliciting user input. + */ + elicitation: ElicitationCapabilitySchema.optional(), + /** + * Present if the client supports listing roots. + */ + roots: z + .object({ + /** + * Whether the client supports issuing notifications for changes to the roots list. + */ + listChanged: z.boolean().optional() + }) + .optional() +}); +exports.InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: z.string(), + capabilities: exports.ClientCapabilitiesSchema, + clientInfo: exports.ImplementationSchema +}); +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ +exports.InitializeRequestSchema = exports.RequestSchema.extend({ + method: z.literal('initialize'), + params: exports.InitializeRequestParamsSchema +}); +const isInitializeRequest = (value) => exports.InitializeRequestSchema.safeParse(value).success; +exports.isInitializeRequest = isInitializeRequest; +/** + * 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. + */ +exports.ServerCapabilitiesSchema = z.object({ + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental: z.record(z.string(), AssertObjectSchema).optional(), + /** + * Present if the server supports sending log messages to the client. + */ + logging: AssertObjectSchema.optional(), + /** + * Present if the server supports sending completions to the client. + */ + completions: AssertObjectSchema.optional(), + /** + * Present if the server offers any prompt templates. + */ + prompts: z.optional(z.object({ + /** + * Whether this server supports issuing notifications for changes to the prompt list. + */ + listChanged: z.optional(z.boolean()) + })), + /** + * Present if the server offers any resources to read. + */ + resources: z + .object({ + /** + * Whether this server supports clients subscribing to resource updates. + */ + subscribe: z.boolean().optional(), + /** + * Whether this server supports issuing notifications for changes to the resource list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server offers any tools to call. + */ + tools: z + .object({ + /** + * Whether this server supports issuing notifications for changes to the tool list. + */ + listChanged: z.boolean().optional() + }) + .optional() +}); +/** + * After receiving an initialize request from the client, the server sends this response. + */ +exports.InitializeResultSchema = exports.ResultSchema.extend({ + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: z.string(), + capabilities: exports.ServerCapabilitiesSchema, + serverInfo: exports.ImplementationSchema, + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions: z.string().optional() +}); +/** + * This notification is sent from the client to the server after initialization has finished. + */ +exports.InitializedNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/initialized') +}); +const isInitializedNotification = (value) => exports.InitializedNotificationSchema.safeParse(value).success; +exports.isInitializedNotification = isInitializedNotification; +/* Ping */ +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ +exports.PingRequestSchema = exports.RequestSchema.extend({ + method: z.literal('ping') +}); +/* Progress notifications */ +exports.ProgressSchema = z.object({ + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + */ + progress: z.number(), + /** + * Total number of items to process (or total progress required), if known. + */ + total: z.optional(z.number()), + /** + * An optional message describing the current progress. + */ + message: z.optional(z.string()) +}); +exports.ProgressNotificationParamsSchema = z.object({ + ...NotificationsParamsSchema.shape, + ...exports.ProgressSchema.shape, + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: exports.ProgressTokenSchema +}); +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ +exports.ProgressNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/progress'), + params: exports.ProgressNotificationParamsSchema +}); +exports.PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor: exports.CursorSchema.optional() +}); +/* Pagination */ +exports.PaginatedRequestSchema = exports.RequestSchema.extend({ + params: exports.PaginatedRequestParamsSchema.optional() +}); +exports.PaginatedResultSchema = exports.ResultSchema.extend({ + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor: z.optional(exports.CursorSchema) +}); +/* Resources */ +/** + * The contents of a specific resource or sub-resource. + */ +exports.ResourceContentsSchema = z.object({ + /** + * The URI of this resource. + */ + uri: z.string(), + /** + * The MIME type of this resource, if known. + */ + mimeType: z.optional(z.string()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +exports.TextResourceContentsSchema = exports.ResourceContentsSchema.extend({ + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: z.string() +}); +/** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ +const Base64Schema = z.string().refine(val => { + try { + // atob throws a DOMException if the string contains characters + // that are not part of the Base64 character set. + atob(val); + return true; + } + catch (_a) { + return false; + } +}, { message: 'Invalid Base64 string' }); +exports.BlobResourceContentsSchema = exports.ResourceContentsSchema.extend({ + /** + * A base64-encoded string representing the binary data of the item. + */ + blob: Base64Schema +}); +/** + * A known resource that the server is capable of reading. + */ +exports.ResourceSchema = z.object({ + ...exports.BaseMetadataSchema.shape, + ...exports.IconsSchema.shape, + /** + * The URI of this resource. + */ + uri: z.string(), + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: z.optional(z.string()), + /** + * The MIME type of this resource, if known. + */ + mimeType: z.optional(z.string()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.looseObject({})) +}); +/** + * A template description for resources available on the server. + */ +exports.ResourceTemplateSchema = z.object({ + ...exports.BaseMetadataSchema.shape, + ...exports.IconsSchema.shape, + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + */ + uriTemplate: z.string(), + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: z.optional(z.string()), + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType: z.optional(z.string()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.looseObject({})) +}); +/** + * Sent from the client to request a list of resources the server has. + */ +exports.ListResourcesRequestSchema = exports.PaginatedRequestSchema.extend({ + method: z.literal('resources/list') +}); +/** + * The server's response to a resources/list request from the client. + */ +exports.ListResourcesResultSchema = exports.PaginatedResultSchema.extend({ + resources: z.array(exports.ResourceSchema) +}); +/** + * Sent from the client to request a list of resource templates the server has. + */ +exports.ListResourceTemplatesRequestSchema = exports.PaginatedRequestSchema.extend({ + method: z.literal('resources/templates/list') +}); +/** + * The server's response to a resources/templates/list request from the client. + */ +exports.ListResourceTemplatesResultSchema = exports.PaginatedResultSchema.extend({ + resourceTemplates: z.array(exports.ResourceTemplateSchema) +}); +exports.ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: z.string() +}); +/** + * Parameters for a `resources/read` request. + */ +exports.ReadResourceRequestParamsSchema = exports.ResourceRequestParamsSchema; +/** + * Sent from the client to the server, to read a specific resource URI. + */ +exports.ReadResourceRequestSchema = exports.RequestSchema.extend({ + method: z.literal('resources/read'), + params: exports.ReadResourceRequestParamsSchema +}); +/** + * The server's response to a resources/read request from the client. + */ +exports.ReadResourceResultSchema = exports.ResultSchema.extend({ + contents: z.array(z.union([exports.TextResourceContentsSchema, exports.BlobResourceContentsSchema])) +}); +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ +exports.ResourceListChangedNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/resources/list_changed') +}); +exports.SubscribeRequestParamsSchema = exports.ResourceRequestParamsSchema; +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + */ +exports.SubscribeRequestSchema = exports.RequestSchema.extend({ + method: z.literal('resources/subscribe'), + params: exports.SubscribeRequestParamsSchema +}); +exports.UnsubscribeRequestParamsSchema = exports.ResourceRequestParamsSchema; +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + */ +exports.UnsubscribeRequestSchema = exports.RequestSchema.extend({ + method: z.literal('resources/unsubscribe'), + params: exports.UnsubscribeRequestParamsSchema +}); +/** + * Parameters for a `notifications/resources/updated` notification. + */ +exports.ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + */ + uri: z.string() +}); +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + */ +exports.ResourceUpdatedNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/resources/updated'), + params: exports.ResourceUpdatedNotificationParamsSchema +}); +/* Prompts */ +/** + * Describes an argument that a prompt can accept. + */ +exports.PromptArgumentSchema = z.object({ + /** + * The name of the argument. + */ + name: z.string(), + /** + * A human-readable description of the argument. + */ + description: z.optional(z.string()), + /** + * Whether this argument must be provided. + */ + required: z.optional(z.boolean()) +}); +/** + * A prompt or prompt template that the server offers. + */ +exports.PromptSchema = z.object({ + ...exports.BaseMetadataSchema.shape, + ...exports.IconsSchema.shape, + /** + * An optional description of what this prompt provides + */ + description: z.optional(z.string()), + /** + * A list of arguments to use for templating the prompt. + */ + arguments: z.optional(z.array(exports.PromptArgumentSchema)), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.looseObject({})) +}); +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ +exports.ListPromptsRequestSchema = exports.PaginatedRequestSchema.extend({ + method: z.literal('prompts/list') +}); +/** + * The server's response to a prompts/list request from the client. + */ +exports.ListPromptsResultSchema = exports.PaginatedResultSchema.extend({ + prompts: z.array(exports.PromptSchema) +}); +/** + * Parameters for a `prompts/get` request. + */ +exports.GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The name of the prompt or prompt template. + */ + name: z.string(), + /** + * Arguments to use for templating the prompt. + */ + arguments: z.record(z.string(), z.string()).optional() +}); +/** + * Used by the client to get a prompt provided by the server. + */ +exports.GetPromptRequestSchema = exports.RequestSchema.extend({ + method: z.literal('prompts/get'), + params: exports.GetPromptRequestParamsSchema +}); +/** + * Text provided to or from an LLM. + */ +exports.TextContentSchema = z.object({ + type: z.literal('text'), + /** + * The text content of the message. + */ + text: z.string(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * An image provided to or from an LLM. + */ +exports.ImageContentSchema = z.object({ + type: z.literal('image'), + /** + * The base64-encoded image data. + */ + data: Base64Schema, + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: z.string(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * An Audio provided to or from an LLM. + */ +exports.AudioContentSchema = z.object({ + type: z.literal('audio'), + /** + * The base64-encoded audio data. + */ + data: Base64Schema, + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: z.string(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + */ +exports.ToolUseContentSchema = z + .object({ + type: z.literal('tool_use'), + /** + * The name of the tool to invoke. + * Must match a tool name from the request's tools array. + */ + name: z.string(), + /** + * Unique identifier for this tool call. + * Used to correlate with ToolResultContent in subsequent messages. + */ + id: z.string(), + /** + * Arguments to pass to the tool. + * Must conform to the tool's inputSchema. + */ + input: z.object({}).passthrough(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()) +}) + .passthrough(); +/** + * The contents of a resource, embedded into a prompt or tool call result. + */ +exports.EmbeddedResourceSchema = z.object({ + type: z.literal('resource'), + resource: z.union([exports.TextResourceContentsSchema, exports.BlobResourceContentsSchema]), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + */ +exports.ResourceLinkSchema = exports.ResourceSchema.extend({ + type: z.literal('resource_link') +}); +/** + * A content block that can be used in prompts and tool results. + */ +exports.ContentBlockSchema = z.union([ + exports.TextContentSchema, + exports.ImageContentSchema, + exports.AudioContentSchema, + exports.ResourceLinkSchema, + exports.EmbeddedResourceSchema +]); +/** + * Describes a message returned as part of a prompt. + */ +exports.PromptMessageSchema = z.object({ + role: z.enum(['user', 'assistant']), + content: exports.ContentBlockSchema +}); +/** + * The server's response to a prompts/get request from the client. + */ +exports.GetPromptResultSchema = exports.ResultSchema.extend({ + /** + * An optional description for the prompt. + */ + description: z.optional(z.string()), + messages: z.array(exports.PromptMessageSchema) +}); +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +exports.PromptListChangedNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/prompts/list_changed') +}); +/* Tools */ +/** + * Security scheme indicating no authentication is required. + */ +exports.NoAuthSecuritySchemeSchema = z.object({ + type: z.literal('noauth') +}); +/** + * Security scheme indicating OAuth 2.0 authentication is required. + */ +exports.OAuth2SecuritySchemeSchema = z.object({ + type: z.literal('oauth2'), + /** + * Optional list of OAuth 2.0 scopes required for this tool. + */ + scopes: z + .array(z.string().min(1)) + .refine((arr) => new Set(arr).size === arr.length, { + message: 'Scopes must be unique' + }) + .optional() +}); +/** + * A security scheme that can be used to authenticate tool calls. + */ +exports.SecuritySchemeSchema = z.union([exports.NoAuthSecuritySchemeSchema, exports.OAuth2SecuritySchemeSchema]); +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + */ +exports.ToolAnnotationsSchema = z.object({ + /** + * A human-readable title for the tool. + */ + title: z.string().optional(), + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint: z.boolean().optional(), + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint: z.boolean().optional(), + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on the its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint: z.boolean().optional(), + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint: z.boolean().optional() +}); +/** + * Definition for a tool the client can call. + */ +exports.ToolSchema = z.object({ + ...exports.BaseMetadataSchema.shape, + ...exports.IconsSchema.shape, + /** + * A human-readable description of the tool. + */ + description: z.string().optional(), + /** + * A JSON Schema 2020-12 object defining the expected parameters for the tool. + * Must have type: 'object' at the root level per MCP spec. + */ + inputSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), AssertObjectSchema).optional(), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()), + /** + * An optional JSON Schema 2020-12 object defining the structure of the tool's output + * returned in the structuredContent field of a CallToolResult. + * Must have type: 'object' at the root level per MCP spec. + */ + outputSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), AssertObjectSchema).optional(), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()) + .optional(), + /** + * Optional additional tool information. + */ + annotations: z.optional(exports.ToolAnnotationsSchema), + /** + * Optional list of security schemes supported by this tool. + * If missing, the tool follows the server's default authentication policy. + * If present, lists the supported authentication schemes (e.g., "noauth", "oauth2"). + */ + securitySchemes: z.array(exports.SecuritySchemeSchema).optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Sent from the client to request a list of tools the server has. + */ +exports.ListToolsRequestSchema = exports.PaginatedRequestSchema.extend({ + method: z.literal('tools/list') +}); +/** + * The server's response to a tools/list request from the client. + */ +exports.ListToolsResultSchema = exports.PaginatedResultSchema.extend({ + tools: z.array(exports.ToolSchema) +}); +/** + * The server's response to a tool call. + */ +exports.CallToolResultSchema = exports.ResultSchema.extend({ + /** + * A list of content objects that represent the result of the tool call. + * + * If the Tool does not define an outputSchema, this field MUST be present in the result. + * For backwards compatibility, this field is always present, but it may be empty. + */ + content: z.array(exports.ContentBlockSchema).default([]), + /** + * An object containing structured tool output. + * + * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. + */ + structuredContent: z.record(z.string(), z.unknown()).optional(), + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError: z.optional(z.boolean()) +}); +/** + * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. + */ +exports.CompatibilityCallToolResultSchema = exports.CallToolResultSchema.or(exports.ResultSchema.extend({ + toolResult: z.unknown() +})); +/** + * Parameters for a `tools/call` request. + */ +exports.CallToolRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The name of the tool to call. + */ + name: z.string(), + /** + * Arguments to pass to the tool. + */ + arguments: z.optional(z.record(z.string(), z.unknown())) +}); +/** + * Used by the client to invoke a tool provided by the server. + */ +exports.CallToolRequestSchema = exports.RequestSchema.extend({ + method: z.literal('tools/call'), + params: exports.CallToolRequestParamsSchema +}); +/** + * 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. + */ +exports.ToolListChangedNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/tools/list_changed') +}); +/* Logging */ +/** + * The severity of a log message. + */ +exports.LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); +/** + * Parameters for a `logging/setLevel` request. + */ +exports.SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. + */ + level: exports.LoggingLevelSchema +}); +/** + * A request from the client to the server, to enable or adjust logging. + */ +exports.SetLevelRequestSchema = exports.RequestSchema.extend({ + method: z.literal('logging/setLevel'), + params: exports.SetLevelRequestParamsSchema +}); +/** + * Parameters for a `notifications/message` notification. + */ +exports.LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The severity of this log message. + */ + level: exports.LoggingLevelSchema, + /** + * An optional name of the logger issuing this message. + */ + logger: z.string().optional(), + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: z.unknown() +}); +/** + * 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. + */ +exports.LoggingMessageNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/message'), + params: exports.LoggingMessageNotificationParamsSchema +}); +/* Sampling */ +/** + * Hints to use for model selection. + */ +exports.ModelHintSchema = z.object({ + /** + * A hint for a model name. + */ + name: z.string().optional() +}); +/** + * The server's preferences for model selection, requested of the client during sampling. + */ +exports.ModelPreferencesSchema = z.object({ + /** + * Optional hints to use for model selection. + */ + hints: z.optional(z.array(exports.ModelHintSchema)), + /** + * How much to prioritize cost when selecting a model. + */ + costPriority: z.optional(z.number().min(0).max(1)), + /** + * How much to prioritize sampling speed (latency) when selecting a model. + */ + speedPriority: z.optional(z.number().min(0).max(1)), + /** + * How much to prioritize intelligence and capabilities when selecting a model. + */ + intelligencePriority: z.optional(z.number().min(0).max(1)) +}); +/** + * Controls tool usage behavior in sampling requests. + */ +exports.ToolChoiceSchema = z.object({ + /** + * Controls when tools are used: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode: z.optional(z.enum(['auto', 'required', 'none'])) +}); +/** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via ToolUseContent. + */ +exports.ToolResultContentSchema = z + .object({ + type: z.literal('tool_result'), + toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'), + content: z.array(exports.ContentBlockSchema).default([]), + structuredContent: z.object({}).passthrough().optional(), + isError: z.optional(z.boolean()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()) +}) + .passthrough(); +/** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + */ +exports.SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ + exports.TextContentSchema, + exports.ImageContentSchema, + exports.AudioContentSchema, + exports.ToolUseContentSchema, + exports.ToolResultContentSchema +]); +/** + * Describes a message issued to or received from an LLM API. + */ +exports.SamplingMessageSchema = z + .object({ + role: z.enum(['user', 'assistant']), + content: z.union([exports.SamplingMessageContentBlockSchema, z.array(exports.SamplingMessageContentBlockSchema)]), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()) +}) + .passthrough(); +/** + * Parameters for a `sampling/createMessage` request. + */ +exports.CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({ + messages: z.array(exports.SamplingMessageSchema), + /** + * The server's preferences for which model to select. The client MAY modify or omit this request. + */ + modelPreferences: exports.ModelPreferencesSchema.optional(), + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt: z.string().optional(), + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(), + temperature: z.number().optional(), + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: z.number().int(), + stopSequences: z.array(z.string()).optional(), + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata: AssertObjectSchema.optional(), + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools: z.optional(z.array(exports.ToolSchema)), + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice: z.optional(exports.ToolChoiceSchema) +}); +/** + * 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. + */ +exports.CreateMessageRequestSchema = exports.RequestSchema.extend({ + method: z.literal('sampling/createMessage'), + params: exports.CreateMessageRequestParamsSchema +}); +/** + * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. + */ +exports.CreateMessageResultSchema = exports.ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: z.string(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())), + role: z.enum(['user', 'assistant']), + /** + * Response content. May be ToolUseContent if stopReason is "toolUse". + */ + content: z.union([exports.SamplingMessageContentBlockSchema, z.array(exports.SamplingMessageContentBlockSchema)]) +}); +/* Elicitation */ +/** + * Primitive schema definition for boolean fields. + */ +exports.BooleanSchemaSchema = z.object({ + type: z.literal('boolean'), + title: z.string().optional(), + description: z.string().optional(), + default: z.boolean().optional() +}); +/** + * Primitive schema definition for string fields. + */ +exports.StringSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + minLength: z.number().optional(), + maxLength: z.number().optional(), + format: z.enum(['email', 'uri', 'date', 'date-time']).optional(), + default: z.string().optional() +}); +/** + * Primitive schema definition for number fields. + */ +exports.NumberSchemaSchema = z.object({ + type: z.enum(['number', 'integer']), + title: z.string().optional(), + description: z.string().optional(), + minimum: z.number().optional(), + maximum: z.number().optional(), + default: z.number().optional() +}); +/** + * Schema for single-selection enumeration without display titles for options. + */ +exports.UntitledSingleSelectEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + enum: z.array(z.string()), + default: z.string().optional() +}); +/** + * Schema for single-selection enumeration with display titles for each option. + */ +exports.TitledSingleSelectEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + oneOf: z.array(z.object({ + const: z.string(), + title: z.string() + })), + default: z.string().optional() +}); +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + */ +exports.LegacyTitledEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + enum: z.array(z.string()), + enumNames: z.array(z.string()).optional(), + default: z.string().optional() +}); +// Combined single selection enumeration +exports.SingleSelectEnumSchemaSchema = z.union([exports.UntitledSingleSelectEnumSchemaSchema, exports.TitledSingleSelectEnumSchemaSchema]); +/** + * Schema for multiple-selection enumeration without display titles for options. + */ +exports.UntitledMultiSelectEnumSchemaSchema = z.object({ + type: z.literal('array'), + title: z.string().optional(), + description: z.string().optional(), + minItems: z.number().optional(), + maxItems: z.number().optional(), + items: z.object({ + type: z.literal('string'), + enum: z.array(z.string()) + }), + default: z.array(z.string()).optional() +}); +/** + * Schema for multiple-selection enumeration with display titles for each option. + */ +exports.TitledMultiSelectEnumSchemaSchema = z.object({ + type: z.literal('array'), + title: z.string().optional(), + description: z.string().optional(), + minItems: z.number().optional(), + maxItems: z.number().optional(), + items: z.object({ + anyOf: z.array(z.object({ + const: z.string(), + title: z.string() + })) + }), + default: z.array(z.string()).optional() +}); +/** + * Combined schema for multiple-selection enumeration + */ +exports.MultiSelectEnumSchemaSchema = z.union([exports.UntitledMultiSelectEnumSchemaSchema, exports.TitledMultiSelectEnumSchemaSchema]); +/** + * Primitive schema definition for enum fields. + */ +exports.EnumSchemaSchema = z.union([exports.LegacyTitledEnumSchemaSchema, exports.SingleSelectEnumSchemaSchema, exports.MultiSelectEnumSchemaSchema]); +/** + * Union of all primitive schema definitions. + */ +exports.PrimitiveSchemaDefinitionSchema = z.union([exports.EnumSchemaSchema, exports.BooleanSchemaSchema, exports.StringSchemaSchema, exports.NumberSchemaSchema]); +/** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ +exports.ElicitRequestFormParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The elicitation mode. + */ + mode: z.literal('form'), + /** + * The message to present to the user describing what information is being requested. + */ + message: z.string(), + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: z.object({ + type: z.literal('object'), + properties: z.record(z.string(), exports.PrimitiveSchemaDefinitionSchema), + required: z.array(z.string()).optional() + }) +}); +/** + * Parameters for an `elicitation/create` request for URL-based elicitation. + */ +exports.ElicitRequestURLParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The elicitation mode. + */ + mode: z.literal('url'), + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: z.string(), + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: z.string(), + /** + * The URL that the user should navigate to. + */ + url: z.string().url() +}); +/** + * The parameters for a request to elicit additional information from the user via the client. + */ +exports.ElicitRequestParamsSchema = z.union([exports.ElicitRequestFormParamsSchema, exports.ElicitRequestURLParamsSchema]); +/** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ +exports.ElicitRequestSchema = exports.RequestSchema.extend({ + method: z.literal('elicitation/create'), + params: exports.ElicitRequestParamsSchema +}); +/** + * Parameters for a `notifications/elicitation/complete` notification. + * + * @category notifications/elicitation/complete + */ +exports.ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the elicitation that completed. + */ + elicitationId: z.string() +}); +/** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ +exports.ElicitationCompleteNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/elicitation/complete'), + params: exports.ElicitationCompleteNotificationParamsSchema +}); +/** + * The client's response to an elicitation/create request from the server. + */ +exports.ElicitResultSchema = exports.ResultSchema.extend({ + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: z.enum(['accept', 'decline', 'cancel']), + /** + * The submitted form data, only present when action is "accept". + * Contains values matching the requested schema. + */ + content: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional() +}); +/* Autocomplete */ +/** + * A reference to a resource or resource template definition. + */ +exports.ResourceTemplateReferenceSchema = z.object({ + type: z.literal('ref/resource'), + /** + * The URI or URI template of the resource. + */ + uri: z.string() +}); +/** + * @deprecated Use ResourceTemplateReferenceSchema instead + */ +exports.ResourceReferenceSchema = exports.ResourceTemplateReferenceSchema; +/** + * Identifies a prompt. + */ +exports.PromptReferenceSchema = z.object({ + type: z.literal('ref/prompt'), + /** + * The name of the prompt or prompt template + */ + name: z.string() +}); +/** + * Parameters for a `completion/complete` request. + */ +exports.CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: z.union([exports.PromptReferenceSchema, exports.ResourceTemplateReferenceSchema]), + /** + * The argument's information + */ + argument: z.object({ + /** + * The name of the argument + */ + name: z.string(), + /** + * The value of the argument to use for completion matching. + */ + value: z.string() + }), + context: z + .object({ + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments: z.record(z.string(), z.string()).optional() + }) + .optional() +}); +/** + * A request from the client to the server, to ask for completion options. + */ +exports.CompleteRequestSchema = exports.RequestSchema.extend({ + method: z.literal('completion/complete'), + params: exports.CompleteRequestParamsSchema +}); +function assertCompleteRequestPrompt(request) { + if (request.params.ref.type !== 'ref/prompt') { + throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); + } + void request; +} +function assertCompleteRequestResourceTemplate(request) { + if (request.params.ref.type !== 'ref/resource') { + throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); + } + void request; +} +/** + * The server's response to a completion/complete request + */ +exports.CompleteResultSchema = exports.ResultSchema.extend({ + completion: z.looseObject({ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.array(z.string()).max(100), + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.optional(z.number().int()), + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.optional(z.boolean()) + }) +}); +/* Roots */ +/** + * Represents a root directory or file that the server can operate on. + */ +exports.RootSchema = z.object({ + /** + * The URI identifying the root. This *must* start with file:// for now. + */ + uri: z.string().startsWith('file://'), + /** + * An optional name for the root. + */ + name: z.string().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Sent from the server to request a list of root URIs from the client. + */ +exports.ListRootsRequestSchema = exports.RequestSchema.extend({ + method: z.literal('roots/list') +}); +/** + * The client's response to a roots/list request from the server. + */ +exports.ListRootsResultSchema = exports.ResultSchema.extend({ + roots: z.array(exports.RootSchema) +}); +/** + * A notification from the client to the server, informing it that the list of roots has changed. + */ +exports.RootsListChangedNotificationSchema = exports.NotificationSchema.extend({ + method: z.literal('notifications/roots/list_changed') +}); +/* Client messages */ +exports.ClientRequestSchema = z.union([ + exports.PingRequestSchema, + exports.InitializeRequestSchema, + exports.CompleteRequestSchema, + exports.SetLevelRequestSchema, + exports.GetPromptRequestSchema, + exports.ListPromptsRequestSchema, + exports.ListResourcesRequestSchema, + exports.ListResourceTemplatesRequestSchema, + exports.ReadResourceRequestSchema, + exports.SubscribeRequestSchema, + exports.UnsubscribeRequestSchema, + exports.CallToolRequestSchema, + exports.ListToolsRequestSchema +]); +exports.ClientNotificationSchema = z.union([ + exports.CancelledNotificationSchema, + exports.ProgressNotificationSchema, + exports.InitializedNotificationSchema, + exports.RootsListChangedNotificationSchema +]); +exports.ClientResultSchema = z.union([exports.EmptyResultSchema, exports.CreateMessageResultSchema, exports.ElicitResultSchema, exports.ListRootsResultSchema]); +/* Server messages */ +exports.ServerRequestSchema = z.union([exports.PingRequestSchema, exports.CreateMessageRequestSchema, exports.ElicitRequestSchema, exports.ListRootsRequestSchema]); +exports.ServerNotificationSchema = z.union([ + exports.CancelledNotificationSchema, + exports.ProgressNotificationSchema, + exports.LoggingMessageNotificationSchema, + exports.ResourceUpdatedNotificationSchema, + exports.ResourceListChangedNotificationSchema, + exports.ToolListChangedNotificationSchema, + exports.PromptListChangedNotificationSchema, + exports.ElicitationCompleteNotificationSchema +]); +exports.ServerResultSchema = z.union([ + exports.EmptyResultSchema, + exports.InitializeResultSchema, + exports.CompleteResultSchema, + exports.GetPromptResultSchema, + exports.ListPromptsResultSchema, + exports.ListResourcesResultSchema, + exports.ListResourceTemplatesResultSchema, + exports.ReadResourceResultSchema, + exports.CallToolResultSchema, + exports.ListToolsResultSchema +]); +class McpError extends Error { + constructor(code, message, data) { + super(`MCP error ${code}: ${message}`); + this.code = code; + this.data = data; + this.name = 'McpError'; + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + // Check for specific error types + if (code === ErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) { + return new UrlElicitationRequiredError(errorData.elicitations, message); + } + } + // Default to generic McpError + return new McpError(code, message, data); + } +} +exports.McpError = McpError; +/** + * Specialized error type when a tool requires a URL mode elicitation. + * 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. + */ +class UrlElicitationRequiredError extends McpError { + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) { + super(ErrorCode.UrlElicitationRequired, message, { + elicitations: elicitations + }); + } + get elicitations() { + var _a, _b; + return (_b = (_a = this.data) === null || _a === void 0 ? void 0 : _a.elicitations) !== null && _b !== void 0 ? _b : []; + } +} +exports.UrlElicitationRequiredError = UrlElicitationRequiredError; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/cjs/types.js.map b/dist/cjs/types.js.map new file mode 100644 index 0000000000..62b44a4f3c --- /dev/null +++ b/dist/cjs/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0oDA,kEAKC;AAED,sFAKC;AAtpDD,0CAA4B;AAGf,QAAA,uBAAuB,GAAG,YAAY,CAAC;AACvC,QAAA,mCAAmC,GAAG,YAAY,CAAC;AACnD,QAAA,2BAA2B,GAAG,CAAC,+BAAuB,EAAE,YAAY,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC;AAE/G,oBAAoB;AACP,QAAA,eAAe,GAAG,KAAK,CAAC;AAMrC;;;;GAIG;AACH,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAS,CAAC,CAAC,EAAe,EAAE,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,UAAU,CAAC,CAAC,CAAC;AAClI;;GAEG;AACU,QAAA,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;AAE3E;;GAEG;AACU,QAAA,YAAY,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC;AAEvC,MAAM,iBAAiB,GAA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,CAAC,CAAC;IAC7C,CAAC;CACJ;AAzBD,4BAyBC;AAED;;;GAGG;AACH,MAAa,2BAA4B,SAAQ,QAAQ;IACrD,YAAY,YAAsC,EAAE,UAAkB,kBAAkB,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,WAAW;QACjI,KAAK,CAAC,SAAS,CAAC,sBAAsB,EAAE,OAAO,EAAE;YAC7C,YAAY,EAAE,YAAY;SAC7B,CAAC,CAAC;IACP,CAAC;IAED,IAAI,YAAY;;QACZ,OAAO,MAAA,MAAC,IAAI,CAAC,IAAmD,0CAAE,YAAY,mCAAI,EAAE,CAAC;IACzF,CAAC;CACJ;AAVD,kEAUC"} \ No newline at end of file diff --git a/dist/cjs/validation/ajv-provider.d.ts b/dist/cjs/validation/ajv-provider.d.ts new file mode 100644 index 0000000000..43e24ffc93 --- /dev/null +++ b/dist/cjs/validation/ajv-provider.d.ts @@ -0,0 +1,53 @@ +/** + * AJV-based JSON Schema validator provider + */ +import { Ajv } from 'ajv'; +import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from './types.js'; +/** + * @example + * ```typescript + * // Use with default AJV instance (recommended) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Use with custom AJV instance + * import { Ajv } from 'ajv'; + * const ajv = new Ajv({ strict: true, allErrors: true }); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ +export declare class AjvJsonSchemaValidator implements jsonSchemaValidator { + private _ajv; + /** + * Create an AJV validator + * + * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. + * + * @example + * ```typescript + * // Use default configuration (recommended for most cases) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Or provide custom AJV instance for advanced configuration + * import { Ajv } from 'ajv'; + * import addFormats from 'ajv-formats'; + * + * const ajv = new Ajv({ validateFormats: true }); + * addFormats(ajv); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ + constructor(ajv?: Ajv); + /** + * Create a validator for the given JSON Schema + * + * The validator is compiled once and can be reused multiple times. + * If the schema has an $id, it will be cached by AJV automatically. + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema: JsonSchemaType): JsonSchemaValidator; +} +//# sourceMappingURL=ajv-provider.d.ts.map \ No newline at end of file diff --git a/dist/cjs/validation/ajv-provider.d.ts.map b/dist/cjs/validation/ajv-provider.d.ts.map new file mode 100644 index 0000000000..4e955a3b32 --- /dev/null +++ b/dist/cjs/validation/ajv-provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ajv-provider.d.ts","sourceRoot":"","sources":["../../../src/validation/ajv-provider.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAE1B,OAAO,KAAK,EAAE,cAAc,EAAE,mBAAmB,EAA6B,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAgBtH;;;;;;;;;;;;GAYG;AACH,qBAAa,sBAAuB,YAAW,mBAAmB;IAC9D,OAAO,CAAC,IAAI,CAAM;IAElB;;;;;;;;;;;;;;;;;;;OAmBG;gBACS,GAAG,CAAC,EAAE,GAAG;IAIrB;;;;;;;;OAQG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC;CAyBlE"} \ No newline at end of file diff --git a/dist/cjs/validation/ajv-provider.js b/dist/cjs/validation/ajv-provider.js new file mode 100644 index 0000000000..7356bfa303 --- /dev/null +++ b/dist/cjs/validation/ajv-provider.js @@ -0,0 +1,95 @@ +"use strict"; +/** + * AJV-based JSON Schema validator provider + */ +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AjvJsonSchemaValidator = void 0; +const ajv_1 = require("ajv"); +const ajv_formats_1 = __importDefault(require("ajv-formats")); +function createDefaultAjvInstance() { + const ajv = new ajv_1.Ajv({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + const addFormats = ajv_formats_1.default; + addFormats(ajv); + return ajv; +} +/** + * @example + * ```typescript + * // Use with default AJV instance (recommended) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Use with custom AJV instance + * import { Ajv } from 'ajv'; + * const ajv = new Ajv({ strict: true, allErrors: true }); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ +class AjvJsonSchemaValidator { + /** + * Create an AJV validator + * + * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. + * + * @example + * ```typescript + * // Use default configuration (recommended for most cases) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Or provide custom AJV instance for advanced configuration + * import { Ajv } from 'ajv'; + * import addFormats from 'ajv-formats'; + * + * const ajv = new Ajv({ validateFormats: true }); + * addFormats(ajv); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ + constructor(ajv) { + this._ajv = ajv !== null && ajv !== void 0 ? ajv : createDefaultAjvInstance(); + } + /** + * Create a validator for the given JSON Schema + * + * The validator is compiled once and can be reused multiple times. + * If the schema has an $id, it will be cached by AJV automatically. + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema) { + var _a; + // Check if schema has $id and is already compiled/cached + const ajvValidator = '$id' in schema && typeof schema.$id === 'string' + ? ((_a = this._ajv.getSchema(schema.$id)) !== null && _a !== void 0 ? _a : this._ajv.compile(schema)) + : this._ajv.compile(schema); + return (input) => { + const valid = ajvValidator(input); + if (valid) { + return { + valid: true, + data: input, + errorMessage: undefined + }; + } + else { + return { + valid: false, + data: undefined, + errorMessage: this._ajv.errorsText(ajvValidator.errors) + }; + } + }; + } +} +exports.AjvJsonSchemaValidator = AjvJsonSchemaValidator; +//# sourceMappingURL=ajv-provider.js.map \ No newline at end of file diff --git a/dist/cjs/validation/ajv-provider.js.map b/dist/cjs/validation/ajv-provider.js.map new file mode 100644 index 0000000000..fcaa27e9f5 --- /dev/null +++ b/dist/cjs/validation/ajv-provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ajv-provider.js","sourceRoot":"","sources":["../../../src/validation/ajv-provider.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;;AAEH,6BAA0B;AAC1B,8DAAsC;AAGtC,SAAS,wBAAwB;IAC7B,MAAM,GAAG,GAAG,IAAI,SAAG,CAAC;QAChB,MAAM,EAAE,KAAK;QACb,eAAe,EAAE,IAAI;QACrB,cAAc,EAAE,KAAK;QACrB,SAAS,EAAE,IAAI;KAClB,CAAC,CAAC;IAEH,MAAM,UAAU,GAAG,qBAAoD,CAAC;IACxE,UAAU,CAAC,GAAG,CAAC,CAAC;IAEhB,OAAO,GAAG,CAAC;AACf,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAa,sBAAsB;IAG/B;;;;;;;;;;;;;;;;;;;OAmBG;IACH,YAAY,GAAS;QACjB,IAAI,CAAC,IAAI,GAAG,GAAG,aAAH,GAAG,cAAH,GAAG,GAAI,wBAAwB,EAAE,CAAC;IAClD,CAAC;IAED;;;;;;;;OAQG;IACH,YAAY,CAAI,MAAsB;;QAClC,yDAAyD;QACzD,MAAM,YAAY,GACd,KAAK,IAAI,MAAM,IAAI,OAAO,MAAM,CAAC,GAAG,KAAK,QAAQ;YAC7C,CAAC,CAAC,CAAC,MAAA,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,mCAAI,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YAChE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAEpC,OAAO,CAAC,KAAc,EAAgC,EAAE;YACpD,MAAM,KAAK,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;YAElC,IAAI,KAAK,EAAE,CAAC;gBACR,OAAO;oBACH,KAAK,EAAE,IAAI;oBACX,IAAI,EAAE,KAAU;oBAChB,YAAY,EAAE,SAAS;iBAC1B,CAAC;YACN,CAAC;iBAAM,CAAC;gBACJ,OAAO;oBACH,KAAK,EAAE,KAAK;oBACZ,IAAI,EAAE,SAAS;oBACf,YAAY,EAAE,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,MAAM,CAAC;iBAC1D,CAAC;YACN,CAAC;QACL,CAAC,CAAC;IACN,CAAC;CACJ;AA7DD,wDA6DC"} \ No newline at end of file diff --git a/dist/cjs/validation/cfworker-provider.d.ts b/dist/cjs/validation/cfworker-provider.d.ts new file mode 100644 index 0000000000..89c244a609 --- /dev/null +++ b/dist/cjs/validation/cfworker-provider.d.ts @@ -0,0 +1,51 @@ +/** + * Cloudflare Worker-compatible JSON Schema validator provider + * + * This provider uses @cfworker/json-schema for validation without code generation, + * making it compatible with edge runtimes like Cloudflare Workers that restrict + * eval and new Function. + */ +import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from './types.js'; +/** + * JSON Schema draft version supported by @cfworker/json-schema + */ +export type CfWorkerSchemaDraft = '4' | '7' | '2019-09' | '2020-12'; +/** + * + * @example + * ```typescript + * // Use with default configuration (2020-12, shortcircuit) + * const validator = new CfWorkerJsonSchemaValidator(); + * + * // Use with custom configuration + * const validator = new CfWorkerJsonSchemaValidator({ + * draft: '2020-12', + * shortcircuit: false // Report all errors + * }); + * ``` + */ +export declare class CfWorkerJsonSchemaValidator implements jsonSchemaValidator { + private shortcircuit; + private draft; + /** + * Create a validator + * + * @param options - Configuration options + * @param options.shortcircuit - If true, stop validation after first error (default: true) + * @param options.draft - JSON Schema draft version to use (default: '2020-12') + */ + constructor(options?: { + shortcircuit?: boolean; + draft?: CfWorkerSchemaDraft; + }); + /** + * Create a validator for the given JSON Schema + * + * Unlike AJV, this validator is not cached internally + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema: JsonSchemaType): JsonSchemaValidator; +} +//# sourceMappingURL=cfworker-provider.d.ts.map \ No newline at end of file diff --git a/dist/cjs/validation/cfworker-provider.d.ts.map b/dist/cjs/validation/cfworker-provider.d.ts.map new file mode 100644 index 0000000000..ce404d92fc --- /dev/null +++ b/dist/cjs/validation/cfworker-provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cfworker-provider.d.ts","sourceRoot":"","sources":["../../../src/validation/cfworker-provider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,mBAAmB,EAA6B,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtH;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG,GAAG,GAAG,GAAG,GAAG,SAAS,GAAG,SAAS,CAAC;AAEpE;;;;;;;;;;;;;GAaG;AACH,qBAAa,2BAA4B,YAAW,mBAAmB;IACnE,OAAO,CAAC,YAAY,CAAU;IAC9B,OAAO,CAAC,KAAK,CAAsB;IAEnC;;;;;;OAMG;gBACS,OAAO,CAAC,EAAE;QAAE,YAAY,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,mBAAmB,CAAA;KAAE;IAK7E;;;;;;;OAOG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC;CAsBlE"} \ No newline at end of file diff --git a/dist/cjs/validation/cfworker-provider.js b/dist/cjs/validation/cfworker-provider.js new file mode 100644 index 0000000000..a080a373bd --- /dev/null +++ b/dist/cjs/validation/cfworker-provider.js @@ -0,0 +1,70 @@ +"use strict"; +/** + * Cloudflare Worker-compatible JSON Schema validator provider + * + * This provider uses @cfworker/json-schema for validation without code generation, + * making it compatible with edge runtimes like Cloudflare Workers that restrict + * eval and new Function. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CfWorkerJsonSchemaValidator = void 0; +const json_schema_1 = require("@cfworker/json-schema"); +/** + * + * @example + * ```typescript + * // Use with default configuration (2020-12, shortcircuit) + * const validator = new CfWorkerJsonSchemaValidator(); + * + * // Use with custom configuration + * const validator = new CfWorkerJsonSchemaValidator({ + * draft: '2020-12', + * shortcircuit: false // Report all errors + * }); + * ``` + */ +class CfWorkerJsonSchemaValidator { + /** + * Create a validator + * + * @param options - Configuration options + * @param options.shortcircuit - If true, stop validation after first error (default: true) + * @param options.draft - JSON Schema draft version to use (default: '2020-12') + */ + constructor(options) { + var _a, _b; + this.shortcircuit = (_a = options === null || options === void 0 ? void 0 : options.shortcircuit) !== null && _a !== void 0 ? _a : true; + this.draft = (_b = options === null || options === void 0 ? void 0 : options.draft) !== null && _b !== void 0 ? _b : '2020-12'; + } + /** + * Create a validator for the given JSON Schema + * + * Unlike AJV, this validator is not cached internally + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema) { + const cfSchema = schema; + const validator = new json_schema_1.Validator(cfSchema, this.draft, this.shortcircuit); + return (input) => { + const result = validator.validate(input); + if (result.valid) { + return { + valid: true, + data: input, + errorMessage: undefined + }; + } + else { + return { + valid: false, + data: undefined, + errorMessage: result.errors.map(err => `${err.instanceLocation}: ${err.error}`).join('; ') + }; + } + }; + } +} +exports.CfWorkerJsonSchemaValidator = CfWorkerJsonSchemaValidator; +//# sourceMappingURL=cfworker-provider.js.map \ No newline at end of file diff --git a/dist/cjs/validation/cfworker-provider.js.map b/dist/cjs/validation/cfworker-provider.js.map new file mode 100644 index 0000000000..b83afb3244 --- /dev/null +++ b/dist/cjs/validation/cfworker-provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cfworker-provider.js","sourceRoot":"","sources":["../../../src/validation/cfworker-provider.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,uDAA+D;AAQ/D;;;;;;;;;;;;;GAaG;AACH,MAAa,2BAA2B;IAIpC;;;;;;OAMG;IACH,YAAY,OAAiE;;QACzE,IAAI,CAAC,YAAY,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,mCAAI,IAAI,CAAC;QAClD,IAAI,CAAC,KAAK,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,KAAK,mCAAI,SAAS,CAAC;IAC7C,CAAC;IAED;;;;;;;OAOG;IACH,YAAY,CAAI,MAAsB;QAClC,MAAM,QAAQ,GAAG,MAA2B,CAAC;QAC7C,MAAM,SAAS,GAAG,IAAI,uBAAS,CAAC,QAAQ,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;QAEzE,OAAO,CAAC,KAAc,EAAgC,EAAE;YACpD,MAAM,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;YAEzC,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;gBACf,OAAO;oBACH,KAAK,EAAE,IAAI;oBACX,IAAI,EAAE,KAAU;oBAChB,YAAY,EAAE,SAAS;iBAC1B,CAAC;YACN,CAAC;iBAAM,CAAC;gBACJ,OAAO;oBACH,KAAK,EAAE,KAAK;oBACZ,IAAI,EAAE,SAAS;oBACf,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,gBAAgB,KAAK,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;iBAC7F,CAAC;YACN,CAAC;QACL,CAAC,CAAC;IACN,CAAC;CACJ;AA9CD,kEA8CC"} \ No newline at end of file diff --git a/dist/cjs/validation/index.d.ts b/dist/cjs/validation/index.d.ts new file mode 100644 index 0000000000..99e993967f --- /dev/null +++ b/dist/cjs/validation/index.d.ts @@ -0,0 +1,29 @@ +/** + * JSON Schema validation + * + * This module provides configurable JSON Schema validation for the MCP SDK. + * Choose a validator based on your runtime environment: + * + * - AjvJsonSchemaValidator: Best for Node.js (default, fastest) + * Import from: @modelcontextprotocol/sdk/validation/ajv + * Requires peer dependencies: ajv, ajv-formats + * + * - CfWorkerJsonSchemaValidator: Best for edge runtimes + * Import from: @modelcontextprotocol/sdk/validation/cfworker + * Requires peer dependency: @cfworker/json-schema + * + * @example + * ```typescript + * // For Node.js with AJV + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // For Cloudflare Workers + * import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker'; + * const validator = new CfWorkerJsonSchemaValidator(); + * ``` + * + * @module validation + */ +export type { JsonSchemaType, JsonSchemaValidator, JsonSchemaValidatorResult, jsonSchemaValidator } from './types.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/cjs/validation/index.d.ts.map b/dist/cjs/validation/index.d.ts.map new file mode 100644 index 0000000000..a8845b96e7 --- /dev/null +++ b/dist/cjs/validation/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/validation/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAGH,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC"} \ No newline at end of file diff --git a/dist/cjs/validation/index.js b/dist/cjs/validation/index.js new file mode 100644 index 0000000000..c8be9256d5 --- /dev/null +++ b/dist/cjs/validation/index.js @@ -0,0 +1,30 @@ +"use strict"; +/** + * JSON Schema validation + * + * This module provides configurable JSON Schema validation for the MCP SDK. + * Choose a validator based on your runtime environment: + * + * - AjvJsonSchemaValidator: Best for Node.js (default, fastest) + * Import from: @modelcontextprotocol/sdk/validation/ajv + * Requires peer dependencies: ajv, ajv-formats + * + * - CfWorkerJsonSchemaValidator: Best for edge runtimes + * Import from: @modelcontextprotocol/sdk/validation/cfworker + * Requires peer dependency: @cfworker/json-schema + * + * @example + * ```typescript + * // For Node.js with AJV + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // For Cloudflare Workers + * import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker'; + * const validator = new CfWorkerJsonSchemaValidator(); + * ``` + * + * @module validation + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/cjs/validation/index.js.map b/dist/cjs/validation/index.js.map new file mode 100644 index 0000000000..1d5874d998 --- /dev/null +++ b/dist/cjs/validation/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/validation/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG"} \ No newline at end of file diff --git a/dist/cjs/validation/types.d.ts b/dist/cjs/validation/types.d.ts new file mode 100644 index 0000000000..5872215c78 --- /dev/null +++ b/dist/cjs/validation/types.d.ts @@ -0,0 +1,55 @@ +import type { Schema } from '@cfworker/json-schema'; +/** + * Result of a JSON Schema validation operation + */ +export type JsonSchemaValidatorResult = { + valid: true; + data: T; + errorMessage: undefined; +} | { + valid: false; + data: undefined; + errorMessage: string; +}; +/** + * A validator function that validates data against a JSON Schema + */ +export type JsonSchemaValidator = (input: unknown) => JsonSchemaValidatorResult; +/** + * Provider interface for creating validators from JSON Schemas + * + * This is the main extension point for custom validator implementations. + * Implementations should: + * - Support JSON Schema Draft 2020-12 (or be compatible with it) + * - Return validator functions that can be called multiple times + * - Handle schema compilation/caching internally + * - Provide clear error messages on validation failure + * + * @example + * ```typescript + * class MyValidatorProvider implements jsonSchemaValidator { + * getValidator(schema: JsonSchemaType): JsonSchemaValidator { + * // Compile/cache validator from schema + * return (input: unknown) => { + * // Validate input against schema + * if (valid) { + * return { valid: true, data: input as T, errorMessage: undefined }; + * } else { + * return { valid: false, data: undefined, errorMessage: 'Error details' }; + * } + * }; + * } + * } + * ``` + */ +export interface jsonSchemaValidator { + /** + * Create a validator for the given JSON Schema + * + * @param schema - Standard JSON Schema object + * @returns A validator function that can be called multiple times + */ + getValidator(schema: JsonSchemaType): JsonSchemaValidator; +} +export type JsonSchemaType = Schema; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/cjs/validation/types.d.ts.map b/dist/cjs/validation/types.d.ts.map new file mode 100644 index 0000000000..3bdf64e589 --- /dev/null +++ b/dist/cjs/validation/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/validation/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAEpD;;GAEG;AACH,MAAM,MAAM,yBAAyB,CAAC,CAAC,IACjC;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,CAAC,CAAC;IAAC,YAAY,EAAE,SAAS,CAAA;CAAE,GACjD;IAAE,KAAK,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,SAAS,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC;AAE9D;;GAEG;AACH,MAAM,MAAM,mBAAmB,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,KAAK,yBAAyB,CAAC,CAAC,CAAC,CAAC;AAEtF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,WAAW,mBAAmB;IAChC;;;;;OAKG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAAC;CACnE;AAED,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/dist/cjs/validation/types.js b/dist/cjs/validation/types.js new file mode 100644 index 0000000000..11e638d1ee --- /dev/null +++ b/dist/cjs/validation/types.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/cjs/validation/types.js.map b/dist/cjs/validation/types.js.map new file mode 100644 index 0000000000..51361cf6a4 --- /dev/null +++ b/dist/cjs/validation/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/validation/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/client/auth.d.ts b/dist/esm/client/auth.d.ts new file mode 100644 index 0000000000..0bf7a645e4 --- /dev/null +++ b/dist/esm/client/auth.d.ts @@ -0,0 +1,280 @@ +import { OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens, OAuthMetadata, OAuthClientInformationFull, OAuthProtectedResourceMetadata, AuthorizationServerMetadata } from '../shared/auth.js'; +import { OAuthError } from '../server/auth/errors.js'; +import { FetchLike } from '../shared/transport.js'; +/** + * Implements an end-to-end OAuth client to be used with one MCP server. + * + * This client relies upon a concept of an authorized "session," the exact + * meaning of which is application-defined. Tokens, authorization codes, and + * code verifiers should not cross different sessions. + */ +export interface OAuthClientProvider { + /** + * The URL to redirect the user agent to after authorization. + */ + get redirectUrl(): string | URL; + /** + * External URL the server should use to fetch client metadata document + */ + clientMetadataUrl?: string; + /** + * Metadata about this OAuth client. + */ + get clientMetadata(): OAuthClientMetadata; + /** + * Returns a OAuth2 state parameter. + */ + state?(): string | Promise; + /** + * Loads information about this OAuth client, as registered already with the + * server, or returns `undefined` if the client is not registered with the + * server. + */ + clientInformation(): OAuthClientInformationMixed | undefined | Promise; + /** + * If implemented, this permits the OAuth client to dynamically register with + * the server. Client information saved this way should later be read via + * `clientInformation()`. + * + * This method is not required to be implemented if client information is + * statically known (e.g., pre-registered). + */ + saveClientInformation?(clientInformation: OAuthClientInformationMixed): void | Promise; + /** + * Loads any existing OAuth tokens for the current session, or returns + * `undefined` if there are no saved tokens. + */ + tokens(): OAuthTokens | undefined | Promise; + /** + * Stores new OAuth tokens for the current session, after a successful + * authorization. + */ + saveTokens(tokens: OAuthTokens): void | Promise; + /** + * Invoked to redirect the user agent to the given URL to begin the authorization flow. + */ + redirectToAuthorization(authorizationUrl: URL): void | Promise; + /** + * Saves a PKCE code verifier for the current session, before redirecting to + * the authorization flow. + */ + saveCodeVerifier(codeVerifier: string): void | Promise; + /** + * Loads the PKCE code verifier for the current session, necessary to validate + * the authorization result. + */ + codeVerifier(): string | Promise; + /** + * Adds custom client authentication to OAuth token requests. + * + * This optional method allows implementations to customize how client credentials + * are included in token exchange and refresh requests. When provided, this method + * is called instead of the default authentication logic, giving full control over + * the authentication mechanism. + * + * Common use cases include: + * - Supporting authentication methods beyond the standard OAuth 2.0 methods + * - Adding custom headers for proprietary authentication schemes + * - Implementing client assertion-based authentication (e.g., JWT bearer tokens) + * + * @param headers - The request headers (can be modified to add authentication) + * @param params - The request body parameters (can be modified to add credentials) + * @param url - The token endpoint URL being called + * @param metadata - Optional OAuth metadata for the server, which may include supported authentication methods + */ + addClientAuthentication?(headers: Headers, params: URLSearchParams, url: string | URL, metadata?: AuthorizationServerMetadata): void | Promise; + /** + * If defined, overrides the selection and validation of the + * RFC 8707 Resource Indicator. If left undefined, default + * validation behavior will be used. + * + * Implementations must verify the returned resource matches the MCP server. + */ + validateResourceURL?(serverUrl: string | URL, resource?: string): Promise; + /** + * If implemented, provides a way for the client to invalidate (e.g. delete) the specified + * credentials, in the case where the server has indicated that they are no longer valid. + * This avoids requiring the user to intervene manually. + */ + invalidateCredentials?(scope: 'all' | 'client' | 'tokens' | 'verifier'): void | Promise; +} +export type AuthResult = 'AUTHORIZED' | 'REDIRECT'; +export declare class UnauthorizedError extends Error { + constructor(message?: string); +} +type ClientAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'none'; +/** + * Determines the best client authentication method to use based on server support and client configuration. + * + * Priority order (highest to lowest): + * 1. client_secret_basic (if client secret is available) + * 2. client_secret_post (if client secret is available) + * 3. none (for public clients) + * + * @param clientInformation - OAuth client information containing credentials + * @param supportedMethods - Authentication methods supported by the authorization server + * @returns The selected authentication method + */ +export declare function selectClientAuthMethod(clientInformation: OAuthClientInformationMixed, supportedMethods: string[]): ClientAuthMethod; +/** + * Parses an OAuth error response from a string or Response object. + * + * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec + * and an instance of the appropriate OAuthError subclass will be returned. + * If parsing fails, it falls back to a generic ServerError that includes + * the response status (if available) and original content. + * + * @param input - A Response object or string containing the error response + * @returns A Promise that resolves to an OAuthError instance + */ +export declare function parseErrorResponse(input: Response | string): Promise; +/** + * Orchestrates the full auth flow with a server. + * + * This can be used as a single entry point for all authorization functionality, + * instead of linking together the other lower-level functions in this module. + */ +export declare function auth(provider: OAuthClientProvider, options: { + serverUrl: string | URL; + authorizationCode?: string; + scope?: string; + resourceMetadataUrl?: URL; + fetchFn?: FetchLike; +}): Promise; +/** + * SEP-991: URL-based Client IDs + * Validate that the client_id is a valid URL with https scheme + */ +export declare function isHttpsUrl(value?: string): boolean; +export declare function selectResourceURL(serverUrl: string | URL, provider: OAuthClientProvider, resourceMetadata?: OAuthProtectedResourceMetadata): Promise; +/** + * Extract resource_metadata, scope, and error from WWW-Authenticate header. + */ +export declare function extractWWWAuthenticateParams(res: Response): { + resourceMetadataUrl?: URL; + scope?: string; + error?: string; +}; +/** + * Extract resource_metadata from response header. + * @deprecated Use `extractWWWAuthenticateParams` instead. + */ +export declare function extractResourceMetadataUrl(res: Response): URL | undefined; +/** + * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + */ +export declare function discoverOAuthProtectedResourceMetadata(serverUrl: string | URL, opts?: { + protocolVersion?: string; + resourceMetadataUrl?: string | URL; +}, fetchFn?: FetchLike): Promise; +/** + * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + * + * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`. + */ +export declare function discoverOAuthMetadata(issuer: string | URL, { authorizationServerUrl, protocolVersion }?: { + authorizationServerUrl?: string | URL; + protocolVersion?: string; +}, fetchFn?: FetchLike): Promise; +/** + * Builds a list of discovery URLs to try for authorization server metadata. + * URLs are returned in priority order: + * 1. OAuth metadata at the given URL + * 2. OIDC metadata endpoints at the given URL + */ +export declare function buildDiscoveryUrls(authorizationServerUrl: string | URL): { + url: URL; + type: 'oauth' | 'oidc'; +}[]; +/** + * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata + * and OpenID Connect Discovery 1.0 specifications. + * + * This function implements a fallback strategy for authorization server discovery: + * 1. Attempts RFC 8414 OAuth metadata discovery first + * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery + * + * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's + * protected resource metadata, or the MCP server's URL if the + * metadata was not found. + * @param options - Configuration options + * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch + * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION + * @returns Promise resolving to authorization server metadata, or undefined if discovery fails + */ +export declare function discoverAuthorizationServerMetadata(authorizationServerUrl: string | URL, { fetchFn, protocolVersion }?: { + fetchFn?: FetchLike; + protocolVersion?: string; +}): Promise; +/** + * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL. + */ +export declare function startAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, redirectUrl, scope, state, resource }: { + metadata?: AuthorizationServerMetadata; + clientInformation: OAuthClientInformationMixed; + redirectUrl: string | URL; + scope?: string; + state?: string; + resource?: URL; +}): Promise<{ + authorizationUrl: URL; + codeVerifier: string; +}>; +/** + * Exchanges an authorization code for an access token with the given server. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Falls back to appropriate defaults when server metadata is unavailable + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, auth code, etc. + * @returns Promise resolving to OAuth tokens + * @throws {Error} When token exchange fails or authentication is invalid + */ +export declare function exchangeAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }: { + metadata?: AuthorizationServerMetadata; + clientInformation: OAuthClientInformationMixed; + authorizationCode: string; + codeVerifier: string; + redirectUri: string | URL; + resource?: URL; + addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; + fetchFn?: FetchLike; +}): Promise; +/** + * Exchange a refresh token for an updated access token. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Preserves the original refresh token if a new one is not returned + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, refresh token, etc. + * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced) + * @throws {Error} When token refresh fails or authentication is invalid + */ +export declare function refreshAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }: { + metadata?: AuthorizationServerMetadata; + clientInformation: OAuthClientInformationMixed; + refreshToken: string; + resource?: URL; + addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; + fetchFn?: FetchLike; +}): Promise; +/** + * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. + */ +export declare function registerClient(authorizationServerUrl: string | URL, { metadata, clientMetadata, fetchFn }: { + metadata?: AuthorizationServerMetadata; + clientMetadata: OAuthClientMetadata; + fetchFn?: FetchLike; +}): Promise; +export {}; +//# sourceMappingURL=auth.d.ts.map \ No newline at end of file diff --git a/dist/esm/client/auth.d.ts.map b/dist/esm/client/auth.d.ts.map new file mode 100644 index 0000000000..ef03546f80 --- /dev/null +++ b/dist/esm/client/auth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/client/auth.ts"],"names":[],"mappings":"AAEA,OAAO,EACH,mBAA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CAAC,EAAE,mBAAmB,CAAC,yBAAyB,CAAC,CAAC;IACzE,OAAO,CAAC,EAAE,SAAS,CAAC;CACvB,GACF,OAAO,CAAC,WAAW,CAAC,CA8CtB;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,oBAAoB,CACtC,sBAAsB,EAAE,MAAM,GAAG,GAAG,EACpC,EACI,QAAQ,EACR,iBAAiB,EACjB,YAAY,EACZ,QAAQ,EACR,uBAAuB,EACvB,OAAO,EACV,EAAE;IACC,QAAQ,CAAC,EAAE,2BAA2B,CAAC;IACvC,iBAAiB,EAAE,2BAA2B,CAAC;IAC/C,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,GAAG,CAAC;IACf,uBAAuB,CAAC,EAAE,mBAAmB,CAAC,yBAAyB,CAAC,CAAC;IACzE,OAAO,CAAC,EAAE,SAAS,CAAC;CACvB,GACF,OAAO,CAAC,WAAW,CAAC,CA+CtB;AAED;;GAEG;AACH,wBAAsB,cAAc,CAChC,sBAAsB,EAAE,MAAM,GAAG,GAAG,EACpC,EACI,QAAQ,EACR,cAAc,EACd,OAAO,EACV,EAAE;IACC,QAAQ,CAAC,EAAE,2BAA2B,CAAC;IACvC,cAAc,EAAE,mBAAmB,CAAC;IACpC,OAAO,CAAC,EAAE,SAAS,CAAC;CACvB,GACF,OAAO,CAAC,0BAA0B,CAAC,CA0BrC"} \ No newline at end of file diff --git a/dist/esm/client/auth.js b/dist/esm/client/auth.js new file mode 100644 index 0000000000..9c1daedfdf --- /dev/null +++ b/dist/esm/client/auth.js @@ -0,0 +1,777 @@ +import pkceChallenge from 'pkce-challenge'; +import { LATEST_PROTOCOL_VERSION } from '../types.js'; +import { OAuthErrorResponseSchema, OpenIdProviderDiscoveryMetadataSchema } from '../shared/auth.js'; +import { OAuthClientInformationFullSchema, OAuthMetadataSchema, OAuthProtectedResourceMetadataSchema, OAuthTokensSchema } from '../shared/auth.js'; +import { checkResourceAllowed, resourceUrlFromServerUrl } from '../shared/auth-utils.js'; +import { InvalidClientError, InvalidClientMetadataError, InvalidGrantError, OAUTH_ERRORS, OAuthError, ServerError, UnauthorizedClientError } from '../server/auth/errors.js'; +export class UnauthorizedError extends Error { + constructor(message) { + super(message !== null && message !== void 0 ? message : 'Unauthorized'); + } +} +function isClientAuthMethod(method) { + return ['client_secret_basic', 'client_secret_post', 'none'].includes(method); +} +const AUTHORIZATION_CODE_RESPONSE_TYPE = 'code'; +const AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256'; +/** + * Determines the best client authentication method to use based on server support and client configuration. + * + * Priority order (highest to lowest): + * 1. client_secret_basic (if client secret is available) + * 2. client_secret_post (if client secret is available) + * 3. none (for public clients) + * + * @param clientInformation - OAuth client information containing credentials + * @param supportedMethods - Authentication methods supported by the authorization server + * @returns The selected authentication method + */ +export function selectClientAuthMethod(clientInformation, supportedMethods) { + const hasClientSecret = clientInformation.client_secret !== undefined; + // If server doesn't specify supported methods, use RFC 6749 defaults + if (supportedMethods.length === 0) { + return hasClientSecret ? 'client_secret_post' : 'none'; + } + // Prefer the method returned by the server during client registration if valid and supported + if ('token_endpoint_auth_method' in clientInformation && + clientInformation.token_endpoint_auth_method && + isClientAuthMethod(clientInformation.token_endpoint_auth_method) && + supportedMethods.includes(clientInformation.token_endpoint_auth_method)) { + return clientInformation.token_endpoint_auth_method; + } + // Try methods in priority order (most secure first) + if (hasClientSecret && supportedMethods.includes('client_secret_basic')) { + return 'client_secret_basic'; + } + if (hasClientSecret && supportedMethods.includes('client_secret_post')) { + return 'client_secret_post'; + } + if (supportedMethods.includes('none')) { + return 'none'; + } + // Fallback: use what we have + return hasClientSecret ? 'client_secret_post' : 'none'; +} +/** + * Applies client authentication to the request based on the specified method. + * + * Implements OAuth 2.1 client authentication methods: + * - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1) + * - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1) + * - none: Public client authentication (RFC 6749 Section 2.1) + * + * @param method - The authentication method to use + * @param clientInformation - OAuth client information containing credentials + * @param headers - HTTP headers object to modify + * @param params - URL search parameters to modify + * @throws {Error} When required credentials are missing + */ +function applyClientAuthentication(method, clientInformation, headers, params) { + const { client_id, client_secret } = clientInformation; + switch (method) { + case 'client_secret_basic': + applyBasicAuth(client_id, client_secret, headers); + return; + case 'client_secret_post': + applyPostAuth(client_id, client_secret, params); + return; + case 'none': + applyPublicAuth(client_id, params); + return; + default: + throw new Error(`Unsupported client authentication method: ${method}`); + } +} +/** + * Applies HTTP Basic authentication (RFC 6749 Section 2.3.1) + */ +function applyBasicAuth(clientId, clientSecret, headers) { + if (!clientSecret) { + throw new Error('client_secret_basic authentication requires a client_secret'); + } + const credentials = btoa(`${clientId}:${clientSecret}`); + headers.set('Authorization', `Basic ${credentials}`); +} +/** + * Applies POST body authentication (RFC 6749 Section 2.3.1) + */ +function applyPostAuth(clientId, clientSecret, params) { + params.set('client_id', clientId); + if (clientSecret) { + params.set('client_secret', clientSecret); + } +} +/** + * Applies public client authentication (RFC 6749 Section 2.1) + */ +function applyPublicAuth(clientId, params) { + params.set('client_id', clientId); +} +/** + * Parses an OAuth error response from a string or Response object. + * + * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec + * and an instance of the appropriate OAuthError subclass will be returned. + * If parsing fails, it falls back to a generic ServerError that includes + * the response status (if available) and original content. + * + * @param input - A Response object or string containing the error response + * @returns A Promise that resolves to an OAuthError instance + */ +export async function parseErrorResponse(input) { + const statusCode = input instanceof Response ? input.status : undefined; + const body = input instanceof Response ? await input.text() : input; + try { + const result = OAuthErrorResponseSchema.parse(JSON.parse(body)); + const { error, error_description, error_uri } = result; + const errorClass = OAUTH_ERRORS[error] || ServerError; + return new errorClass(error_description || '', error_uri); + } + catch (error) { + // Not a valid OAuth error response, but try to inform the user of the raw data anyway + const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}Invalid OAuth error response: ${error}. Raw body: ${body}`; + return new ServerError(errorMessage); + } +} +/** + * Orchestrates the full auth flow with a server. + * + * This can be used as a single entry point for all authorization functionality, + * instead of linking together the other lower-level functions in this module. + */ +export async function auth(provider, options) { + var _a, _b; + try { + return await authInternal(provider, options); + } + catch (error) { + // Handle recoverable error types by invalidating credentials and retrying + if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) { + await ((_a = provider.invalidateCredentials) === null || _a === void 0 ? void 0 : _a.call(provider, 'all')); + return await authInternal(provider, options); + } + else if (error instanceof InvalidGrantError) { + await ((_b = provider.invalidateCredentials) === null || _b === void 0 ? void 0 : _b.call(provider, 'tokens')); + return await authInternal(provider, options); + } + // Throw otherwise + throw error; + } +} +async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) { + var _a, _b; + let resourceMetadata; + let authorizationServerUrl; + try { + resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn); + if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { + authorizationServerUrl = resourceMetadata.authorization_servers[0]; + } + } + catch (_c) { + // Ignore errors and fall back to /.well-known/oauth-authorization-server + } + /** + * If we don't get a valid authorization server metadata from protected resource metadata, + * fallback to the legacy MCP spec's implementation (version 2025-03-26): MCP server base URL acts as the Authorization server. + */ + if (!authorizationServerUrl) { + authorizationServerUrl = new URL('/', serverUrl); + } + const resource = await selectResourceURL(serverUrl, provider, resourceMetadata); + const metadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { + fetchFn + }); + // Handle client registration if needed + let clientInformation = await Promise.resolve(provider.clientInformation()); + if (!clientInformation) { + if (authorizationCode !== undefined) { + throw new Error('Existing OAuth client information is required when exchanging an authorization code'); + } + const supportsUrlBasedClientId = (metadata === null || metadata === void 0 ? void 0 : metadata.client_id_metadata_document_supported) === true; + const clientMetadataUrl = provider.clientMetadataUrl; + if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) { + throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`); + } + const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl; + if (shouldUseUrlBasedClientId) { + // SEP-991: URL-based Client IDs + clientInformation = { + client_id: clientMetadataUrl + }; + await ((_a = provider.saveClientInformation) === null || _a === void 0 ? void 0 : _a.call(provider, clientInformation)); + } + else { + // Fallback to dynamic registration + if (!provider.saveClientInformation) { + throw new Error('OAuth client information must be saveable for dynamic registration'); + } + const fullInformation = await registerClient(authorizationServerUrl, { + metadata, + clientMetadata: provider.clientMetadata, + fetchFn + }); + await provider.saveClientInformation(fullInformation); + clientInformation = fullInformation; + } + } + // Exchange authorization code for tokens + if (authorizationCode !== undefined) { + const codeVerifier = await provider.codeVerifier(); + const tokens = await exchangeAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + authorizationCode, + codeVerifier, + redirectUri: provider.redirectUrl, + resource, + addClientAuthentication: provider.addClientAuthentication, + fetchFn: fetchFn + }); + await provider.saveTokens(tokens); + return 'AUTHORIZED'; + } + const tokens = await provider.tokens(); + // Handle token refresh or new authorization + if (tokens === null || tokens === void 0 ? void 0 : tokens.refresh_token) { + try { + // Attempt to refresh the token + const newTokens = await refreshAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + refreshToken: tokens.refresh_token, + resource, + addClientAuthentication: provider.addClientAuthentication, + fetchFn + }); + await provider.saveTokens(newTokens); + return 'AUTHORIZED'; + } + catch (error) { + // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry. + if (!(error instanceof OAuthError) || error instanceof ServerError) { + // Could not refresh OAuth tokens + } + else { + // Refresh failed for another reason, re-throw + throw error; + } + } + } + const state = provider.state ? await provider.state() : undefined; + // Start new authorization flow + const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, { + metadata, + clientInformation, + state, + redirectUrl: provider.redirectUrl, + scope: scope || ((_b = resourceMetadata === null || resourceMetadata === void 0 ? void 0 : resourceMetadata.scopes_supported) === null || _b === void 0 ? void 0 : _b.join(' ')) || provider.clientMetadata.scope, + resource + }); + await provider.saveCodeVerifier(codeVerifier); + await provider.redirectToAuthorization(authorizationUrl); + return 'REDIRECT'; +} +/** + * SEP-991: URL-based Client IDs + * Validate that the client_id is a valid URL with https scheme + */ +export function isHttpsUrl(value) { + if (!value) + return false; + try { + const url = new URL(value); + return url.protocol === 'https:' && url.pathname !== '/'; + } + catch (_a) { + return false; + } +} +export async function selectResourceURL(serverUrl, provider, resourceMetadata) { + const defaultResource = resourceUrlFromServerUrl(serverUrl); + // If provider has custom validation, delegate to it + if (provider.validateResourceURL) { + return await provider.validateResourceURL(defaultResource, resourceMetadata === null || resourceMetadata === void 0 ? void 0 : resourceMetadata.resource); + } + // Only include resource parameter when Protected Resource Metadata is present + if (!resourceMetadata) { + return undefined; + } + // Validate that the metadata's resource is compatible with our request + if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) { + throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`); + } + // Prefer the resource from metadata since it's what the server is telling us to request + return new URL(resourceMetadata.resource); +} +/** + * Extract resource_metadata, scope, and error from WWW-Authenticate header. + */ +export function extractWWWAuthenticateParams(res) { + const authenticateHeader = res.headers.get('WWW-Authenticate'); + if (!authenticateHeader) { + return {}; + } + const [type, scheme] = authenticateHeader.split(' '); + if (type.toLowerCase() !== 'bearer' || !scheme) { + return {}; + } + const resourceMetadataMatch = extractFieldFromWwwAuth(res, 'resource_metadata') || undefined; + let resourceMetadataUrl; + if (resourceMetadataMatch) { + try { + resourceMetadataUrl = new URL(resourceMetadataMatch); + } + catch (_a) { + // Ignore invalid URL + } + } + const scope = extractFieldFromWwwAuth(res, 'scope') || undefined; + const error = extractFieldFromWwwAuth(res, 'error') || undefined; + return { + resourceMetadataUrl, + scope, + error + }; +} +/** + * Extracts a specific field's value from the WWW-Authenticate header string. + * + * @param response The HTTP response object containing the headers. + * @param fieldName The name of the field to extract (e.g., "realm", "nonce"). + * @returns The field value + */ +function extractFieldFromWwwAuth(response, fieldName) { + const wwwAuthHeader = response.headers.get('WWW-Authenticate'); + if (!wwwAuthHeader) { + return null; + } + const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`); + const match = wwwAuthHeader.match(pattern); + if (match) { + // Pattern matches: field_name="value" or field_name=value (unquoted) + return match[1] || match[2]; + } + return null; +} +/** + * Extract resource_metadata from response header. + * @deprecated Use `extractWWWAuthenticateParams` instead. + */ +export function extractResourceMetadataUrl(res) { + const authenticateHeader = res.headers.get('WWW-Authenticate'); + if (!authenticateHeader) { + return undefined; + } + const [type, scheme] = authenticateHeader.split(' '); + if (type.toLowerCase() !== 'bearer' || !scheme) { + return undefined; + } + const regex = /resource_metadata="([^"]*)"/; + const match = regex.exec(authenticateHeader); + if (!match) { + return undefined; + } + try { + return new URL(match[1]); + } + catch (_a) { + return undefined; + } +} +/** + * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + */ +export async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) { + const response = await discoverMetadataWithFallback(serverUrl, 'oauth-protected-resource', fetchFn, { + protocolVersion: opts === null || opts === void 0 ? void 0 : opts.protocolVersion, + metadataUrl: opts === null || opts === void 0 ? void 0 : opts.resourceMetadataUrl + }); + if (!response || response.status === 404) { + throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`); + } + if (!response.ok) { + throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`); + } + return OAuthProtectedResourceMetadataSchema.parse(await response.json()); +} +/** + * Helper function to handle fetch with CORS retry logic + */ +async function fetchWithCorsRetry(url, headers, fetchFn = fetch) { + try { + return await fetchFn(url, { headers }); + } + catch (error) { + if (error instanceof TypeError) { + if (headers) { + // CORS errors come back as TypeError, retry without headers + return fetchWithCorsRetry(url, undefined, fetchFn); + } + else { + // We're getting CORS errors on retry too, return undefined + return undefined; + } + } + throw error; + } +} +/** + * Constructs the well-known path for auth-related metadata discovery + */ +function buildWellKnownPath(wellKnownPrefix, pathname = '', options = {}) { + // Strip trailing slash from pathname to avoid double slashes + if (pathname.endsWith('/')) { + pathname = pathname.slice(0, -1); + } + return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`; +} +/** + * Tries to discover OAuth metadata at a specific URL + */ +async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) { + const headers = { + 'MCP-Protocol-Version': protocolVersion + }; + return await fetchWithCorsRetry(url, headers, fetchFn); +} +/** + * Determines if fallback to root discovery should be attempted + */ +function shouldAttemptFallback(response, pathname) { + return !response || (response.status >= 400 && response.status < 500 && pathname !== '/'); +} +/** + * Generic function for discovering OAuth metadata with fallback support + */ +async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) { + var _a, _b; + const issuer = new URL(serverUrl); + const protocolVersion = (_a = opts === null || opts === void 0 ? void 0 : opts.protocolVersion) !== null && _a !== void 0 ? _a : LATEST_PROTOCOL_VERSION; + let url; + if (opts === null || opts === void 0 ? void 0 : opts.metadataUrl) { + url = new URL(opts.metadataUrl); + } + else { + // Try path-aware discovery first + const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname); + url = new URL(wellKnownPath, (_b = opts === null || opts === void 0 ? void 0 : opts.metadataServerUrl) !== null && _b !== void 0 ? _b : issuer); + url.search = issuer.search; + } + let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn); + // If path-aware discovery fails with 404 and we're not already at root, try fallback to root discovery + if (!(opts === null || opts === void 0 ? void 0 : opts.metadataUrl) && shouldAttemptFallback(response, issuer.pathname)) { + const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer); + response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn); + } + return response; +} +/** + * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata. + * + * If the server returns a 404 for the well-known endpoint, this function will + * return `undefined`. Any other errors will be thrown as exceptions. + * + * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`. + */ +export async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) { + if (typeof issuer === 'string') { + issuer = new URL(issuer); + } + if (!authorizationServerUrl) { + authorizationServerUrl = issuer; + } + if (typeof authorizationServerUrl === 'string') { + authorizationServerUrl = new URL(authorizationServerUrl); + } + protocolVersion !== null && protocolVersion !== void 0 ? protocolVersion : (protocolVersion = LATEST_PROTOCOL_VERSION); + const response = await discoverMetadataWithFallback(authorizationServerUrl, 'oauth-authorization-server', fetchFn, { + protocolVersion, + metadataServerUrl: authorizationServerUrl + }); + if (!response || response.status === 404) { + return undefined; + } + if (!response.ok) { + throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`); + } + return OAuthMetadataSchema.parse(await response.json()); +} +/** + * Builds a list of discovery URLs to try for authorization server metadata. + * URLs are returned in priority order: + * 1. OAuth metadata at the given URL + * 2. OIDC metadata endpoints at the given URL + */ +export function buildDiscoveryUrls(authorizationServerUrl) { + const url = typeof authorizationServerUrl === 'string' ? new URL(authorizationServerUrl) : authorizationServerUrl; + const hasPath = url.pathname !== '/'; + const urlsToTry = []; + if (!hasPath) { + // Root path: https://example.com/.well-known/oauth-authorization-server + urlsToTry.push({ + url: new URL('/.well-known/oauth-authorization-server', url.origin), + type: 'oauth' + }); + // OIDC: https://example.com/.well-known/openid-configuration + urlsToTry.push({ + url: new URL(`/.well-known/openid-configuration`, url.origin), + type: 'oidc' + }); + return urlsToTry; + } + // Strip trailing slash from pathname to avoid double slashes + let pathname = url.pathname; + if (pathname.endsWith('/')) { + pathname = pathname.slice(0, -1); + } + // 1. OAuth metadata at the given URL + // Insert well-known before the path: https://example.com/.well-known/oauth-authorization-server/tenant1 + urlsToTry.push({ + url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin), + type: 'oauth' + }); + // 2. OIDC metadata endpoints + // RFC 8414 style: Insert /.well-known/openid-configuration before the path + urlsToTry.push({ + url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin), + type: 'oidc' + }); + // OIDC Discovery 1.0 style: Append /.well-known/openid-configuration after the path + urlsToTry.push({ + url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin), + type: 'oidc' + }); + return urlsToTry; +} +/** + * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata + * and OpenID Connect Discovery 1.0 specifications. + * + * This function implements a fallback strategy for authorization server discovery: + * 1. Attempts RFC 8414 OAuth metadata discovery first + * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery + * + * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's + * protected resource metadata, or the MCP server's URL if the + * metadata was not found. + * @param options - Configuration options + * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch + * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION + * @returns Promise resolving to authorization server metadata, or undefined if discovery fails + */ +export async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) { + const headers = { + 'MCP-Protocol-Version': protocolVersion, + Accept: 'application/json' + }; + // Get the list of URLs to try + const urlsToTry = buildDiscoveryUrls(authorizationServerUrl); + // Try each URL in order + for (const { url: endpointUrl, type } of urlsToTry) { + const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn); + if (!response) { + /** + * CORS error occurred - don't throw as the endpoint may not allow CORS, + * continue trying other possible endpoints + */ + continue; + } + if (!response.ok) { + // Continue looking for any 4xx response code. + if (response.status >= 400 && response.status < 500) { + continue; // Try next URL + } + throw new Error(`HTTP ${response.status} trying to load ${type === 'oauth' ? 'OAuth' : 'OpenID provider'} metadata from ${endpointUrl}`); + } + // Parse and validate based on type + if (type === 'oauth') { + return OAuthMetadataSchema.parse(await response.json()); + } + else { + return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json()); + } + } + return undefined; +} +/** + * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL. + */ +export async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) { + let authorizationUrl; + if (metadata) { + authorizationUrl = new URL(metadata.authorization_endpoint); + if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) { + throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`); + } + if (metadata.code_challenge_methods_supported && + !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) { + throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`); + } + } + else { + authorizationUrl = new URL('/authorize', authorizationServerUrl); + } + // Generate PKCE challenge + const challenge = await pkceChallenge(); + const codeVerifier = challenge.code_verifier; + const codeChallenge = challenge.code_challenge; + authorizationUrl.searchParams.set('response_type', AUTHORIZATION_CODE_RESPONSE_TYPE); + authorizationUrl.searchParams.set('client_id', clientInformation.client_id); + authorizationUrl.searchParams.set('code_challenge', codeChallenge); + authorizationUrl.searchParams.set('code_challenge_method', AUTHORIZATION_CODE_CHALLENGE_METHOD); + authorizationUrl.searchParams.set('redirect_uri', String(redirectUrl)); + if (state) { + authorizationUrl.searchParams.set('state', state); + } + if (scope) { + authorizationUrl.searchParams.set('scope', scope); + } + if (scope === null || scope === void 0 ? void 0 : scope.includes('offline_access')) { + // if the request includes the OIDC-only "offline_access" scope, + // we need to set the prompt to "consent" to ensure the user is prompted to grant offline access + // https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess + authorizationUrl.searchParams.append('prompt', 'consent'); + } + if (resource) { + authorizationUrl.searchParams.set('resource', resource.href); + } + return { authorizationUrl, codeVerifier }; +} +/** + * Exchanges an authorization code for an access token with the given server. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Falls back to appropriate defaults when server metadata is unavailable + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, auth code, etc. + * @returns Promise resolving to OAuth tokens + * @throws {Error} When token exchange fails or authentication is invalid + */ +export async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) { + var _a; + const grantType = 'authorization_code'; + const tokenUrl = (metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL('/token', authorizationServerUrl); + if ((metadata === null || metadata === void 0 ? void 0 : metadata.grant_types_supported) && !metadata.grant_types_supported.includes(grantType)) { + throw new Error(`Incompatible auth server: does not support grant type ${grantType}`); + } + // Exchange code for tokens + const headers = new Headers({ + 'Content-Type': 'application/x-www-form-urlencoded', + Accept: 'application/json' + }); + const params = new URLSearchParams({ + grant_type: grantType, + code: authorizationCode, + code_verifier: codeVerifier, + redirect_uri: String(redirectUri) + }); + if (addClientAuthentication) { + addClientAuthentication(headers, params, authorizationServerUrl, metadata); + } + else { + // Determine and apply client authentication method + const supportedMethods = (_a = metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint_auth_methods_supported) !== null && _a !== void 0 ? _a : []; + const authMethod = selectClientAuthMethod(clientInformation, supportedMethods); + applyClientAuthentication(authMethod, clientInformation, headers, params); + } + if (resource) { + params.set('resource', resource.href); + } + const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, { + method: 'POST', + headers, + body: params + }); + if (!response.ok) { + throw await parseErrorResponse(response); + } + return OAuthTokensSchema.parse(await response.json()); +} +/** + * Exchange a refresh token for an updated access token. + * + * Supports multiple client authentication methods as specified in OAuth 2.1: + * - Automatically selects the best authentication method based on server support + * - Preserves the original refresh token if a new one is not returned + * + * @param authorizationServerUrl - The authorization server's base URL + * @param options - Configuration object containing client info, refresh token, etc. + * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced) + * @throws {Error} When token refresh fails or authentication is invalid + */ +export async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) { + var _a; + const grantType = 'refresh_token'; + let tokenUrl; + if (metadata) { + tokenUrl = new URL(metadata.token_endpoint); + if (metadata.grant_types_supported && !metadata.grant_types_supported.includes(grantType)) { + throw new Error(`Incompatible auth server: does not support grant type ${grantType}`); + } + } + else { + tokenUrl = new URL('/token', authorizationServerUrl); + } + // Exchange refresh token + const headers = new Headers({ + 'Content-Type': 'application/x-www-form-urlencoded' + }); + const params = new URLSearchParams({ + grant_type: grantType, + refresh_token: refreshToken + }); + if (addClientAuthentication) { + addClientAuthentication(headers, params, authorizationServerUrl, metadata); + } + else { + // Determine and apply client authentication method + const supportedMethods = (_a = metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint_auth_methods_supported) !== null && _a !== void 0 ? _a : []; + const authMethod = selectClientAuthMethod(clientInformation, supportedMethods); + applyClientAuthentication(authMethod, clientInformation, headers, params); + } + if (resource) { + params.set('resource', resource.href); + } + const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, { + method: 'POST', + headers, + body: params + }); + if (!response.ok) { + throw await parseErrorResponse(response); + } + return OAuthTokensSchema.parse({ refresh_token: refreshToken, ...(await response.json()) }); +} +/** + * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. + */ +export async function registerClient(authorizationServerUrl, { metadata, clientMetadata, fetchFn }) { + let registrationUrl; + if (metadata) { + if (!metadata.registration_endpoint) { + throw new Error('Incompatible auth server: does not support dynamic client registration'); + } + registrationUrl = new URL(metadata.registration_endpoint); + } + else { + registrationUrl = new URL('/register', authorizationServerUrl); + } + const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(registrationUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(clientMetadata) + }); + if (!response.ok) { + throw await parseErrorResponse(response); + } + return OAuthClientInformationFullSchema.parse(await response.json()); +} +//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/dist/esm/client/auth.js.map b/dist/esm/client/auth.js.map new file mode 100644 index 0000000000..a778750d04 --- /dev/null +++ b/dist/esm/client/auth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/client/auth.ts"],"names":[],"mappings":"AAAA,OAAO,aAAa,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAQH,wBAAwB,EAExB,qCAAqC,EACxC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACH,gCAAgC,EAChC,mBAAmB,EACnB,oCAAoC,EACpC,iBAAiB,EACpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EACH,kBAAkB,EAClB,0BAA0B,EAC1B,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,WAAW,EACX,uBAAuB,EAC1B,MAAM,0BAA0B,CAAC;AAyHlC,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IACxC,YAAY,OAAgB;QACxB,KAAK,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,cAAc,CAAC,CAAC;IACrC,CAAC;CACJ;AAID,SAAS,kBAAkB,CAAC,MAAc;IACtC,OAAO,CAAC,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAClF,CAAC;AAED,MAAM,gCAAgC,GAAG,MAAM,CAAC;AAChD,MAAM,mCAAmC,GAAG,MAAM,CAAC;AAEnD;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,sBAAsB,CAAC,iBAA8C,EAAE,gBAA0B;IAC7G,MAAM,eAAe,GAAG,iBAAiB,CAAC,aAAa,KAAK,SAAS,CAAC;IAEtE,qEAAqE;IACrE,IAAI,gBAAgB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAChC,OAAO,eAAe,CAAC,CAAC,CA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G,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc,CAChC,sBAAoC,EACpC,EACI,QAAQ,EACR,cAAc,EACd,OAAO,EAKV;IAED,IAAI,eAAoB,CAAC;IAEzB,IAAI,QAAQ,EAAE,CAAC;QACX,IAAI,CAAC,QAAQ,CAAC,qBAAqB,EAAE,CAAC;YAClC,MAAM,IAAI,KAAK,CAAC,wEAAwE,CAAC,CAAC;QAC9F,CAAC;QAED,eAAe,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC;IAC9D,CAAC;SAAM,CAAC;QACJ,eAAe,GAAG,IAAI,GAAG,CAAC,WAAW,EAAE,sBAAsB,CAAC,CAAC;IACnE,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,KAAK,CAAC,CAAC,eAAe,EAAE;QACvD,MAAM,EAAE,MAAM;QACd,OAAO,EAAE;YACL,cAAc,EAAE,kBAAkB;SACrC;QACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC;KACvC,CAAC,CAAC;IAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACf,MAAM,MAAM,kBAAkB,CAAC,QAAQ,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,gCAAgC,CAAC,KAAK,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;AACzE,CAAC"} \ No newline at end of file diff --git a/dist/esm/client/index.d.ts b/dist/esm/client/index.d.ts new file mode 100644 index 0000000000..03148dd89b --- /dev/null +++ b/dist/esm/client/index.d.ts @@ -0,0 +1,379 @@ +import { Protocol, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; +import type { Transport } from '../shared/transport.js'; +import { type CallToolRequest, CallToolResultSchema, type ClientCapabilities, type ClientNotification, type ClientRequest, type ClientResult, type CompatibilityCallToolResultSchema, type CompleteRequest, type GetPromptRequest, type Implementation, type ListPromptsRequest, type ListResourcesRequest, type ListResourceTemplatesRequest, type ListToolsRequest, type LoggingLevel, type Notification, type ReadResourceRequest, type Request, type Result, type ServerCapabilities, type SubscribeRequest, type UnsubscribeRequest } from '../types.js'; +import type { jsonSchemaValidator } from '../validation/types.js'; +import { AnyObjectSchema, SchemaOutput } from '../server/zod-compat.js'; +import type { RequestHandlerExtra } from '../shared/protocol.js'; +/** + * Determines which elicitation modes are supported based on declared client capabilities. + * + * According to the spec: + * - An empty elicitation capability object defaults to form mode support (backwards compatibility) + * - URL mode is only supported if explicitly declared + * + * @param capabilities - The client's elicitation capabilities + * @returns An object indicating which modes are supported + */ +export declare function getSupportedElicitationModes(capabilities: ClientCapabilities['elicitation']): { + supportsFormMode: boolean; + supportsUrlMode: boolean; +}; +export type ClientOptions = ProtocolOptions & { + /** + * Capabilities to advertise as being supported by this client. + */ + capabilities?: ClientCapabilities; + /** + * JSON Schema validator for tool output validation. + * + * The validator is used to validate structured content returned by tools + * against their declared output schemas. + * + * @default AjvJsonSchemaValidator + * + * @example + * ```typescript + * // ajv + * const client = new Client( + * { name: 'my-client', version: '1.0.0' }, + * { + * capabilities: {}, + * jsonSchemaValidator: new AjvJsonSchemaValidator() + * } + * ); + * + * // @cfworker/json-schema + * const client = new Client( + * { name: 'my-client', version: '1.0.0' }, + * { + * capabilities: {}, + * jsonSchemaValidator: new CfWorkerJsonSchemaValidator() + * } + * ); + * ``` + */ + jsonSchemaValidator?: jsonSchemaValidator; +}; +/** + * An MCP client on top of a pluggable transport. + * + * The client will automatically begin the initialization flow with the server when connect() is called. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed client + * const client = new Client({ + * name: "CustomClient", + * version: "1.0.0" + * }) + * ``` + */ +export declare class Client extends Protocol { + private _clientInfo; + private _serverCapabilities?; + private _serverVersion?; + private _capabilities; + private _instructions?; + private _jsonSchemaValidator; + private _cachedToolOutputValidators; + /** + * Initializes this client with the given name and version information. + */ + constructor(_clientInfo: Implementation, options?: ClientOptions); + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities: ClientCapabilities): void; + /** + * Override request handler registration to enforce client-side validation for elicitation. + */ + setRequestHandler(requestSchema: T, handler: (request: SchemaOutput, extra: RequestHandlerExtra) => ClientResult | ResultT | Promise): void; + protected assertCapability(capability: keyof ServerCapabilities, method: string): void; + connect(transport: Transport, options?: RequestOptions): Promise; + /** + * After initialization has completed, this will be populated with the server's reported capabilities. + */ + getServerCapabilities(): ServerCapabilities | undefined; + /** + * After initialization has completed, this will be populated with information about the server's name and version. + */ + getServerVersion(): Implementation | undefined; + /** + * After initialization has completed, this may be populated with information about the server's instructions. + */ + getInstructions(): string | undefined; + protected assertCapabilityForMethod(method: RequestT['method']): void; + protected assertNotificationCapability(method: NotificationT['method']): void; + protected assertRequestHandlerCapability(method: string): void; + ping(options?: RequestOptions): Promise<{ + _meta?: Record | undefined; + }>; + complete(params: CompleteRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + completion: { + [x: string]: unknown; + values: string[]; + total?: number | undefined; + hasMore?: boolean | undefined; + }; + _meta?: Record | undefined; + }>; + setLoggingLevel(level: LoggingLevel, options?: RequestOptions): Promise<{ + _meta?: Record | undefined; + }>; + getPrompt(params: GetPromptRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + messages: { + role: "user" | "assistant"; + content: { + type: "text"; + text: string; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "resource"; + resource: { + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + }; + _meta?: Record | undefined; + } | { + uri: string; + name: string; + type: "resource_link"; + description?: string | undefined; + mimeType?: string | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + }; + }[]; + _meta?: Record | undefined; + description?: string | undefined; + }>; + listPrompts(params?: ListPromptsRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + prompts: { + name: string; + description?: string | undefined; + arguments?: { + name: string; + description?: string | undefined; + required?: boolean | undefined; + }[] | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: Record | undefined; + nextCursor?: string | undefined; + }>; + listResources(params?: ListResourcesRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + resources: { + uri: string; + name: string; + description?: string | undefined; + mimeType?: string | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: Record | undefined; + nextCursor?: string | undefined; + }>; + listResourceTemplates(params?: ListResourceTemplatesRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + resourceTemplates: { + uriTemplate: string; + name: string; + description?: string | undefined; + mimeType?: string | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: Record | undefined; + nextCursor?: string | undefined; + }>; + readResource(params: ReadResourceRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + contents: ({ + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + })[]; + _meta?: Record | undefined; + }>; + subscribeResource(params: SubscribeRequest['params'], options?: RequestOptions): Promise<{ + _meta?: Record | undefined; + }>; + unsubscribeResource(params: UnsubscribeRequest['params'], options?: RequestOptions): Promise<{ + _meta?: Record | undefined; + }>; + callTool(params: CallToolRequest['params'], resultSchema?: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options?: RequestOptions): Promise<{ + [x: string]: unknown; + content: ({ + type: "text"; + text: string; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "resource"; + resource: { + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + }; + _meta?: Record | undefined; + } | { + uri: string; + name: string; + type: "resource_link"; + description?: string | undefined; + mimeType?: string | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + })[]; + _meta?: Record | undefined; + structuredContent?: Record | undefined; + isError?: boolean | undefined; + } | { + [x: string]: unknown; + toolResult: unknown; + _meta?: Record | undefined; + }>; + /** + * Cache validators for tool output schemas. + * Called after listTools() to pre-compile validators for better performance. + */ + private cacheToolOutputSchemas; + /** + * Get cached validator for a tool + */ + private getToolOutputValidator; + listTools(params?: ListToolsRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + tools: { + inputSchema: { + [x: string]: unknown; + type: "object"; + properties?: Record | undefined; + required?: string[] | undefined; + }; + name: string; + description?: string | undefined; + outputSchema?: { + [x: string]: unknown; + type: "object"; + properties?: Record | undefined; + required?: string[] | undefined; + } | undefined; + annotations?: { + title?: string | undefined; + readOnlyHint?: boolean | undefined; + destructiveHint?: boolean | undefined; + idempotentHint?: boolean | undefined; + openWorldHint?: boolean | undefined; + } | undefined; + securitySchemes?: ({ + type: "noauth"; + } | { + type: "oauth2"; + scopes?: string[] | undefined; + })[] | undefined; + _meta?: Record | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + }[]; + _meta?: Record | undefined; + nextCursor?: string | undefined; + }>; + sendRootsListChanged(): Promise; +} +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/esm/client/index.d.ts.map b/dist/esm/client/index.d.ts.map new file mode 100644 index 0000000000..c19d4ef588 --- /dev/null +++ b/dist/esm/client/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAAE,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC/G,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EACH,KAAK,eAAe,EACpB,oBAAoB,EACpB,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,iCAAiC,EACtC,KAAK,eAAe,EAIpB,KAAK,gBAAgB,EAErB,KAAK,cAAc,EAGnB,KAAK,kBAAkB,EAEvB,KAAK,oBAAoB,EAEzB,KAAK,4BAA4B,EAEjC,KAAK,gBAAgB,EAErB,KAAK,YAAY,EAEjB,KAAK,YAAY,EACjB,KAAK,mBAAmB,EAExB,KAAK,OAAO,EACZ,KAAK,MAAM,EACX,KAAK,kBAAkB,EAEvB,KAAK,gBAAgB,EAErB,KAAK,kBAAkB,EAG1B,MAAM,aAAa,CAAC;AAErB,OAAO,KAAK,EAAuC,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AACvG,OAAO,EACH,eAAe,EACf,YAAY,EAMf,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,mBAAmB,EAA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AC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;IAI/E,qBAAqB,CAAC,MAAM,CAAC,EAAE,4BAA4B,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;IAI/F,YAAY,CAAC,MAAM,EAAE,mBAAmB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;IAI5E,iBAAiB,CAAC,MAAM,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;IAI9E,mBAAmB,CAAC,MAAM,EAAE,kBAAkB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;IAIlF,QAAQ,CACV,MAAM,EAAE,eAAe,CAAC,QAAQ,CAAC,EACjC,YAAY,GAAE,OAAO,oBAAoB,GAAG,OAAO,iCAAwD,EAC3G,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA0C5B;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IAY9B;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAIxB,SAAS,CAAC,MAAM,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IASvE,oBAAoB;CAG7B"} \ No newline at end of file diff --git a/dist/esm/client/index.js b/dist/esm/client/index.js new file mode 100644 index 0000000000..73a55e6afe --- /dev/null +++ b/dist/esm/client/index.js @@ -0,0 +1,418 @@ +import { mergeCapabilities, Protocol } from '../shared/protocol.js'; +import { CallToolResultSchema, CompleteResultSchema, EmptyResultSchema, ErrorCode, GetPromptResultSchema, InitializeResultSchema, LATEST_PROTOCOL_VERSION, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ListToolsResultSchema, McpError, ReadResourceResultSchema, SUPPORTED_PROTOCOL_VERSIONS, ElicitResultSchema, ElicitRequestSchema } from '../types.js'; +import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; +import { getObjectShape, isZ4Schema, safeParse } from '../server/zod-compat.js'; +/** + * Elicitation default application helper. Applies defaults to the data based on the schema. + * + * @param schema - The schema to apply defaults to. + * @param data - The data to apply defaults to. + */ +function applyElicitationDefaults(schema, data) { + if (!schema || data === null || typeof data !== 'object') + return; + // Handle object properties + if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') { + const obj = data; + const props = schema.properties; + for (const key of Object.keys(props)) { + const propSchema = props[key]; + // If missing or explicitly undefined, apply default if present + if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) { + obj[key] = propSchema.default; + } + // Recurse into existing nested objects/arrays + if (obj[key] !== undefined) { + applyElicitationDefaults(propSchema, obj[key]); + } + } + } + if (Array.isArray(schema.anyOf)) { + for (const sub of schema.anyOf) { + applyElicitationDefaults(sub, data); + } + } + // Combine schemas + if (Array.isArray(schema.oneOf)) { + for (const sub of schema.oneOf) { + applyElicitationDefaults(sub, data); + } + } +} +/** + * Determines which elicitation modes are supported based on declared client capabilities. + * + * According to the spec: + * - An empty elicitation capability object defaults to form mode support (backwards compatibility) + * - URL mode is only supported if explicitly declared + * + * @param capabilities - The client's elicitation capabilities + * @returns An object indicating which modes are supported + */ +export function getSupportedElicitationModes(capabilities) { + if (!capabilities) { + return { supportsFormMode: false, supportsUrlMode: false }; + } + const hasFormCapability = capabilities.form !== undefined; + const hasUrlCapability = capabilities.url !== undefined; + // If neither form nor url are explicitly declared, form mode is supported (backwards compatibility) + const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability); + const supportsUrlMode = hasUrlCapability; + return { supportsFormMode, supportsUrlMode }; +} +/** + * An MCP client on top of a pluggable transport. + * + * The client will automatically begin the initialization flow with the server when connect() is called. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed client + * const client = new Client({ + * name: "CustomClient", + * version: "1.0.0" + * }) + * ``` + */ +export class Client extends Protocol { + /** + * Initializes this client with the given name and version information. + */ + constructor(_clientInfo, options) { + var _a, _b; + super(options); + this._clientInfo = _clientInfo; + this._cachedToolOutputValidators = new Map(); + this._capabilities = (_a = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a !== void 0 ? _a : {}; + this._jsonSchemaValidator = (_b = options === null || options === void 0 ? void 0 : options.jsonSchemaValidator) !== null && _b !== void 0 ? _b : new AjvJsonSchemaValidator(); + } + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) { + throw new Error('Cannot register capabilities after connecting to transport'); + } + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + } + /** + * Override request handler registration to enforce client-side validation for elicitation. + */ + setRequestHandler(requestSchema, handler) { + var _a, _b, _c; + const shape = getObjectShape(requestSchema); + const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + // Extract literal value using type-safe property access + let methodValue; + if (isZ4Schema(methodSchema)) { + const v4Schema = methodSchema; + const v4Def = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def; + methodValue = (_b = v4Def === null || v4Def === void 0 ? void 0 : v4Def.value) !== null && _b !== void 0 ? _b : v4Schema.value; + } + else { + const v3Schema = methodSchema; + const legacyDef = v3Schema._def; + methodValue = (_c = legacyDef === null || legacyDef === void 0 ? void 0 : legacyDef.value) !== null && _c !== void 0 ? _c : v3Schema.value; + } + if (typeof methodValue !== 'string') { + throw new Error('Schema method literal must be a string'); + } + const method = methodValue; + if (method === 'elicitation/create') { + const wrappedHandler = async (request, extra) => { + var _a, _b; + const validatedRequest = safeParse(ElicitRequestSchema, request); + if (!validatedRequest.success) { + // Type guard: if success is false, error is guaranteed to exist + const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`); + } + const { params } = validatedRequest.data; + const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation); + if (params.mode === 'form' && !supportsFormMode) { + throw new McpError(ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests'); + } + if (params.mode === 'url' && !supportsUrlMode) { + throw new McpError(ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests'); + } + const result = await Promise.resolve(handler(request, extra)); + const validationResult = safeParse(ElicitResultSchema, result); + if (!validationResult.success) { + // Type guard: if success is false, error is guaranteed to exist + const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); + throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`); + } + const validatedResult = validationResult.data; + const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined; + if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) { + if ((_b = (_a = this._capabilities.elicitation) === null || _a === void 0 ? void 0 : _a.form) === null || _b === void 0 ? void 0 : _b.applyDefaults) { + try { + applyElicitationDefaults(requestedSchema, validatedResult.content); + } + catch (_c) { + // gracefully ignore errors in default application + } + } + } + return validatedResult; + }; + // Install the wrapped handler + return super.setRequestHandler(requestSchema, wrappedHandler); + } + // Non-elicitation handlers use default behavior + return super.setRequestHandler(requestSchema, handler); + } + assertCapability(capability, method) { + var _a; + if (!((_a = this._serverCapabilities) === null || _a === void 0 ? void 0 : _a[capability])) { + throw new Error(`Server does not support ${capability} (required for ${method})`); + } + } + async connect(transport, options) { + await super.connect(transport); + // When transport sessionId is already set this means we are trying to reconnect. + // In this case we don't need to initialize again. + if (transport.sessionId !== undefined) { + return; + } + try { + const result = await this.request({ + method: 'initialize', + params: { + protocolVersion: LATEST_PROTOCOL_VERSION, + capabilities: this._capabilities, + clientInfo: this._clientInfo + } + }, InitializeResultSchema, options); + if (result === undefined) { + throw new Error(`Server sent invalid initialize result: ${result}`); + } + if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) { + throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`); + } + this._serverCapabilities = result.capabilities; + this._serverVersion = result.serverInfo; + // HTTP transports must set the protocol version in each header after initialization. + if (transport.setProtocolVersion) { + transport.setProtocolVersion(result.protocolVersion); + } + this._instructions = result.instructions; + await this.notification({ + method: 'notifications/initialized' + }); + } + catch (error) { + // Disconnect if initialization fails. + void this.close(); + throw error; + } + } + /** + * After initialization has completed, this will be populated with the server's reported capabilities. + */ + getServerCapabilities() { + return this._serverCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the server's name and version. + */ + getServerVersion() { + return this._serverVersion; + } + /** + * After initialization has completed, this may be populated with information about the server's instructions. + */ + getInstructions() { + return this._instructions; + } + assertCapabilityForMethod(method) { + var _a, _b, _c, _d, _e; + switch (method) { + case 'logging/setLevel': + if (!((_a = this._serverCapabilities) === null || _a === void 0 ? void 0 : _a.logging)) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case 'prompts/get': + case 'prompts/list': + if (!((_b = this._serverCapabilities) === null || _b === void 0 ? void 0 : _b.prompts)) { + throw new Error(`Server does not support prompts (required for ${method})`); + } + break; + case 'resources/list': + case 'resources/templates/list': + case 'resources/read': + case 'resources/subscribe': + case 'resources/unsubscribe': + if (!((_c = this._serverCapabilities) === null || _c === void 0 ? void 0 : _c.resources)) { + throw new Error(`Server does not support resources (required for ${method})`); + } + if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) { + throw new Error(`Server does not support resource subscriptions (required for ${method})`); + } + break; + case 'tools/call': + case 'tools/list': + if (!((_d = this._serverCapabilities) === null || _d === void 0 ? void 0 : _d.tools)) { + throw new Error(`Server does not support tools (required for ${method})`); + } + break; + case 'completion/complete': + if (!((_e = this._serverCapabilities) === null || _e === void 0 ? void 0 : _e.completions)) { + throw new Error(`Server does not support completions (required for ${method})`); + } + break; + case 'initialize': + // No specific capability required for initialize + break; + case 'ping': + // No specific capability required for ping + break; + } + } + assertNotificationCapability(method) { + var _a; + switch (method) { + case 'notifications/roots/list_changed': + if (!((_a = this._capabilities.roots) === null || _a === void 0 ? void 0 : _a.listChanged)) { + throw new Error(`Client does not support roots list changed notifications (required for ${method})`); + } + break; + case 'notifications/initialized': + // No specific capability required for initialized + break; + case 'notifications/cancelled': + // Cancellation notifications are always allowed + break; + case 'notifications/progress': + // Progress notifications are always allowed + break; + } + } + assertRequestHandlerCapability(method) { + switch (method) { + case 'sampling/createMessage': + if (!this._capabilities.sampling) { + throw new Error(`Client does not support sampling capability (required for ${method})`); + } + break; + case 'elicitation/create': + if (!this._capabilities.elicitation) { + throw new Error(`Client does not support elicitation capability (required for ${method})`); + } + break; + case 'roots/list': + if (!this._capabilities.roots) { + throw new Error(`Client does not support roots capability (required for ${method})`); + } + break; + case 'ping': + // No specific capability required for ping + break; + } + } + async ping(options) { + return this.request({ method: 'ping' }, EmptyResultSchema, options); + } + async complete(params, options) { + return this.request({ method: 'completion/complete', params }, CompleteResultSchema, options); + } + async setLoggingLevel(level, options) { + return this.request({ method: 'logging/setLevel', params: { level } }, EmptyResultSchema, options); + } + async getPrompt(params, options) { + return this.request({ method: 'prompts/get', params }, GetPromptResultSchema, options); + } + async listPrompts(params, options) { + return this.request({ method: 'prompts/list', params }, ListPromptsResultSchema, options); + } + async listResources(params, options) { + return this.request({ method: 'resources/list', params }, ListResourcesResultSchema, options); + } + async listResourceTemplates(params, options) { + return this.request({ method: 'resources/templates/list', params }, ListResourceTemplatesResultSchema, options); + } + async readResource(params, options) { + return this.request({ method: 'resources/read', params }, ReadResourceResultSchema, options); + } + async subscribeResource(params, options) { + return this.request({ method: 'resources/subscribe', params }, EmptyResultSchema, options); + } + async unsubscribeResource(params, options) { + return this.request({ method: 'resources/unsubscribe', params }, EmptyResultSchema, options); + } + async callTool(params, resultSchema = CallToolResultSchema, options) { + const result = await this.request({ method: 'tools/call', params }, resultSchema, options); + // Check if the tool has an outputSchema + const validator = this.getToolOutputValidator(params.name); + if (validator) { + // If tool has outputSchema, it MUST return structuredContent (unless it's an error) + if (!result.structuredContent && !result.isError) { + throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`); + } + // Only validate structured content if present (not when there's an error) + if (result.structuredContent) { + try { + // Validate the structured content against the schema + const validationResult = validator(result.structuredContent); + if (!validationResult.valid) { + throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`); + } + } + catch (error) { + if (error instanceof McpError) { + throw error; + } + throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`); + } + } + } + return result; + } + /** + * Cache validators for tool output schemas. + * Called after listTools() to pre-compile validators for better performance. + */ + cacheToolOutputSchemas(tools) { + this._cachedToolOutputValidators.clear(); + for (const tool of tools) { + // If the tool has an outputSchema, create and cache the validator + if (tool.outputSchema) { + const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema); + this._cachedToolOutputValidators.set(tool.name, toolValidator); + } + } + } + /** + * Get cached validator for a tool + */ + getToolOutputValidator(toolName) { + return this._cachedToolOutputValidators.get(toolName); + } + async listTools(params, options) { + const result = await this.request({ method: 'tools/list', params }, ListToolsResultSchema, options); + // Cache the tools and their output schemas for future validation + this.cacheToolOutputSchemas(result.tools); + return result; + } + async sendRootsListChanged() { + return this.notification({ method: 'notifications/roots/list_changed' }); + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/esm/client/index.js.map b/dist/esm/client/index.js.map new file mode 100644 index 0000000000..57ca9b491f --- /dev/null +++ b/dist/esm/client/index.js.map @@ -0,0 +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/dist/esm/client/middleware.d.ts new file mode 100644 index 0000000000..726ac578ae --- /dev/null +++ b/dist/esm/client/middleware.d.ts @@ -0,0 +1,169 @@ +import { OAuthClientProvider } from './auth.js'; +import { FetchLike } from '../shared/transport.js'; +/** + * Middleware function that wraps and enhances fetch functionality. + * Takes a fetch handler and returns an enhanced fetch handler. + */ +export type Middleware = (next: FetchLike) => FetchLike; +/** + * Creates a fetch wrapper that handles OAuth authentication automatically. + * + * This wrapper will: + * - Add Authorization headers with access tokens + * - Handle 401 responses by attempting re-authentication + * - Retry the original request after successful auth + * - Handle OAuth errors appropriately (InvalidClientError, etc.) + * + * The baseUrl parameter is optional and defaults to using the domain from the request URL. + * However, you should explicitly provide baseUrl when: + * - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com) + * - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /) + * - The OAuth server is on a different domain than your API requests + * - You want to ensure consistent OAuth behavior regardless of request URLs + * + * For MCP transports, set baseUrl to the same URL you pass to the transport constructor. + * + * Note: This wrapper is designed for general-purpose fetch operations. + * MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling + * and should not need this wrapper. + * + * @param provider - OAuth client provider for authentication + * @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain) + * @returns A fetch middleware function + */ +export declare const withOAuth: (provider: OAuthClientProvider, baseUrl?: string | URL) => Middleware; +/** + * Logger function type for HTTP requests + */ +export type RequestLogger = (input: { + method: string; + url: string | URL; + status: number; + statusText: string; + duration: number; + requestHeaders?: Headers; + responseHeaders?: Headers; + error?: Error; +}) => void; +/** + * Configuration options for the logging middleware + */ +export type LoggingOptions = { + /** + * Custom logger function, defaults to console logging + */ + logger?: RequestLogger; + /** + * Whether to include request headers in logs + * @default false + */ + includeRequestHeaders?: boolean; + /** + * Whether to include response headers in logs + * @default false + */ + includeResponseHeaders?: boolean; + /** + * Status level filter - only log requests with status >= this value + * Set to 0 to log all requests, 400 to log only errors + * @default 0 + */ + statusLevel?: number; +}; +/** + * Creates a fetch middleware that logs HTTP requests and responses. + * + * When called without arguments `withLogging()`, it uses the default logger that: + * - Logs successful requests (2xx) to `console.log` + * - Logs error responses (4xx/5xx) and network errors to `console.error` + * - Logs all requests regardless of status (statusLevel: 0) + * - Does not include request or response headers in logs + * - Measures and displays request duration in milliseconds + * + * Important: the default logger uses both `console.log` and `console.error` so it should not be used with + * `stdio` transports and applications. + * + * @param options - Logging configuration options + * @returns A fetch middleware function + */ +export declare const withLogging: (options?: LoggingOptions) => Middleware; +/** + * Composes multiple fetch middleware functions into a single middleware pipeline. + * Middleware are applied in the order they appear, creating a chain of handlers. + * + * @example + * ```typescript + * // Create a middleware pipeline that handles both OAuth and logging + * const enhancedFetch = applyMiddlewares( + * withOAuth(oauthProvider, 'https://api.example.com'), + * withLogging({ statusLevel: 400 }) + * )(fetch); + * + * // Use the enhanced fetch - it will handle auth and log errors + * const response = await enhancedFetch('https://api.example.com/data'); + * ``` + * + * @param middleware - Array of fetch middleware to compose into a pipeline + * @returns A single composed middleware function + */ +export declare const applyMiddlewares: (...middleware: Middleware[]) => Middleware; +/** + * Helper function to create custom fetch middleware with cleaner syntax. + * Provides the next handler and request details as separate parameters for easier access. + * + * @example + * ```typescript + * // Create custom authentication middleware + * const customAuthMiddleware = createMiddleware(async (next, input, init) => { + * const headers = new Headers(init?.headers); + * headers.set('X-Custom-Auth', 'my-token'); + * + * const response = await next(input, { ...init, headers }); + * + * if (response.status === 401) { + * console.log('Authentication failed'); + * } + * + * return response; + * }); + * + * // Create conditional middleware + * const conditionalMiddleware = createMiddleware(async (next, input, init) => { + * const url = typeof input === 'string' ? input : input.toString(); + * + * // Only add headers for API routes + * if (url.includes('/api/')) { + * const headers = new Headers(init?.headers); + * headers.set('X-API-Version', 'v2'); + * return next(input, { ...init, headers }); + * } + * + * // Pass through for non-API routes + * return next(input, init); + * }); + * + * // Create caching middleware + * const cacheMiddleware = createMiddleware(async (next, input, init) => { + * const cacheKey = typeof input === 'string' ? input : input.toString(); + * + * // Check cache first + * const cached = await getFromCache(cacheKey); + * if (cached) { + * return new Response(cached, { status: 200 }); + * } + * + * // Make request and cache result + * const response = await next(input, init); + * if (response.ok) { + * await saveToCache(cacheKey, await response.clone().text()); + * } + * + * return response; + * }); + * ``` + * + * @param handler - Function that receives the next handler and request parameters + * @returns A fetch middleware function + */ +export declare const createMiddleware: (handler: (next: FetchLike, input: string | URL, init?: RequestInit) => Promise) => Middleware; +//# sourceMappingURL=middleware.d.ts.map \ No newline at end of file diff --git a/dist/esm/client/middleware.d.ts.map b/dist/esm/client/middleware.d.ts.map new file mode 100644 index 0000000000..88ac77806d --- /dev/null +++ b/dist/esm/client/middleware.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../../src/client/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsC,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AACvG,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,CAAC,IAAI,EAAE,SAAS,KAAK,SAAS,CAAC;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,SAAS,aACP,mBAAmB,YAAY,MAAM,GAAG,GAAG,KAAG,UA0DxD,CAAC;AAEN;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,KAAK,CAAC,EAAE,KAAK,CAAC;CACjB,KAAK,IAAI,CAAC;AAEX;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IACzB;;OAEG;IACH,MAAM,CAAC,EAAE,aAAa,CAAC;IAEvB;;;OAGG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAEhC;;;OAGG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;IAEjC;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,WAAW,aAAa,cAAc,KAAQ,UA6E1D,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,gBAAgB,kBAAmB,UAAU,EAAE,KAAG,UAI9D,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AACH,eAAO,MAAM,gBAAgB,YAAa,CAAC,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,KAAG,UAE3H,CAAC"} \ No newline at end of file diff --git a/dist/esm/client/middleware.js b/dist/esm/client/middleware.js new file mode 100644 index 0000000000..9e24de68f8 --- /dev/null +++ b/dist/esm/client/middleware.js @@ -0,0 +1,245 @@ +import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js'; +/** + * Creates a fetch wrapper that handles OAuth authentication automatically. + * + * This wrapper will: + * - Add Authorization headers with access tokens + * - Handle 401 responses by attempting re-authentication + * - Retry the original request after successful auth + * - Handle OAuth errors appropriately (InvalidClientError, etc.) + * + * The baseUrl parameter is optional and defaults to using the domain from the request URL. + * However, you should explicitly provide baseUrl when: + * - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com) + * - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /) + * - The OAuth server is on a different domain than your API requests + * - You want to ensure consistent OAuth behavior regardless of request URLs + * + * For MCP transports, set baseUrl to the same URL you pass to the transport constructor. + * + * Note: This wrapper is designed for general-purpose fetch operations. + * MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling + * and should not need this wrapper. + * + * @param provider - OAuth client provider for authentication + * @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain) + * @returns A fetch middleware function + */ +export const withOAuth = (provider, baseUrl) => next => { + return async (input, init) => { + const makeRequest = async () => { + const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers); + // Add authorization header if tokens are available + const tokens = await provider.tokens(); + if (tokens) { + headers.set('Authorization', `Bearer ${tokens.access_token}`); + } + return await next(input, { ...init, headers }); + }; + let response = await makeRequest(); + // Handle 401 responses by attempting re-authentication + if (response.status === 401) { + try { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + // Use provided baseUrl or extract from request URL + const serverUrl = baseUrl || (typeof input === 'string' ? new URL(input).origin : input.origin); + const result = await auth(provider, { + serverUrl, + resourceMetadataUrl, + scope, + fetchFn: next + }); + if (result === 'REDIRECT') { + throw new UnauthorizedError('Authentication requires user authorization - redirect initiated'); + } + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(`Authentication failed with result: ${result}`); + } + // Retry the request with fresh tokens + response = await makeRequest(); + } + catch (error) { + if (error instanceof UnauthorizedError) { + throw error; + } + throw new UnauthorizedError(`Failed to re-authenticate: ${error instanceof Error ? error.message : String(error)}`); + } + } + // If we still have a 401 after re-auth attempt, throw an error + if (response.status === 401) { + const url = typeof input === 'string' ? input : input.toString(); + throw new UnauthorizedError(`Authentication failed for ${url}`); + } + return response; + }; +}; +/** + * Creates a fetch middleware that logs HTTP requests and responses. + * + * When called without arguments `withLogging()`, it uses the default logger that: + * - Logs successful requests (2xx) to `console.log` + * - Logs error responses (4xx/5xx) and network errors to `console.error` + * - Logs all requests regardless of status (statusLevel: 0) + * - Does not include request or response headers in logs + * - Measures and displays request duration in milliseconds + * + * Important: the default logger uses both `console.log` and `console.error` so it should not be used with + * `stdio` transports and applications. + * + * @param options - Logging configuration options + * @returns A fetch middleware function + */ +export const withLogging = (options = {}) => { + const { logger, includeRequestHeaders = false, includeResponseHeaders = false, statusLevel = 0 } = options; + const defaultLogger = input => { + const { method, url, status, statusText, duration, requestHeaders, responseHeaders, error } = input; + let message = error + ? `HTTP ${method} ${url} failed: ${error.message} (${duration}ms)` + : `HTTP ${method} ${url} ${status} ${statusText} (${duration}ms)`; + // Add headers to message if requested + if (includeRequestHeaders && requestHeaders) { + const reqHeaders = Array.from(requestHeaders.entries()) + .map(([key, value]) => `${key}: ${value}`) + .join(', '); + message += `\n Request Headers: {${reqHeaders}}`; + } + if (includeResponseHeaders && responseHeaders) { + const resHeaders = Array.from(responseHeaders.entries()) + .map(([key, value]) => `${key}: ${value}`) + .join(', '); + message += `\n Response Headers: {${resHeaders}}`; + } + if (error || status >= 400) { + // eslint-disable-next-line no-console + console.error(message); + } + else { + // eslint-disable-next-line no-console + console.log(message); + } + }; + const logFn = logger || defaultLogger; + return next => async (input, init) => { + const startTime = performance.now(); + const method = (init === null || init === void 0 ? void 0 : init.method) || 'GET'; + const url = typeof input === 'string' ? input : input.toString(); + const requestHeaders = includeRequestHeaders ? new Headers(init === null || init === void 0 ? void 0 : init.headers) : undefined; + try { + const response = await next(input, init); + const duration = performance.now() - startTime; + // Only log if status meets the log level threshold + if (response.status >= statusLevel) { + logFn({ + method, + url, + status: response.status, + statusText: response.statusText, + duration, + requestHeaders, + responseHeaders: includeResponseHeaders ? response.headers : undefined + }); + } + return response; + } + catch (error) { + const duration = performance.now() - startTime; + // Always log errors regardless of log level + logFn({ + method, + url, + status: 0, + statusText: 'Network Error', + duration, + requestHeaders, + error: error + }); + throw error; + } + }; +}; +/** + * Composes multiple fetch middleware functions into a single middleware pipeline. + * Middleware are applied in the order they appear, creating a chain of handlers. + * + * @example + * ```typescript + * // Create a middleware pipeline that handles both OAuth and logging + * const enhancedFetch = applyMiddlewares( + * withOAuth(oauthProvider, 'https://api.example.com'), + * withLogging({ statusLevel: 400 }) + * )(fetch); + * + * // Use the enhanced fetch - it will handle auth and log errors + * const response = await enhancedFetch('https://api.example.com/data'); + * ``` + * + * @param middleware - Array of fetch middleware to compose into a pipeline + * @returns A single composed middleware function + */ +export const applyMiddlewares = (...middleware) => { + return next => { + return middleware.reduce((handler, mw) => mw(handler), next); + }; +}; +/** + * Helper function to create custom fetch middleware with cleaner syntax. + * Provides the next handler and request details as separate parameters for easier access. + * + * @example + * ```typescript + * // Create custom authentication middleware + * const customAuthMiddleware = createMiddleware(async (next, input, init) => { + * const headers = new Headers(init?.headers); + * headers.set('X-Custom-Auth', 'my-token'); + * + * const response = await next(input, { ...init, headers }); + * + * if (response.status === 401) { + * console.log('Authentication failed'); + * } + * + * return response; + * }); + * + * // Create conditional middleware + * const conditionalMiddleware = createMiddleware(async (next, input, init) => { + * const url = typeof input === 'string' ? input : input.toString(); + * + * // Only add headers for API routes + * if (url.includes('/api/')) { + * const headers = new Headers(init?.headers); + * headers.set('X-API-Version', 'v2'); + * return next(input, { ...init, headers }); + * } + * + * // Pass through for non-API routes + * return next(input, init); + * }); + * + * // Create caching middleware + * const cacheMiddleware = createMiddleware(async (next, input, init) => { + * const cacheKey = typeof input === 'string' ? input : input.toString(); + * + * // Check cache first + * const cached = await getFromCache(cacheKey); + * if (cached) { + * return new Response(cached, { status: 200 }); + * } + * + * // Make request and cache result + * const response = await next(input, init); + * if (response.ok) { + * await saveToCache(cacheKey, await response.clone().text()); + * } + * + * return response; + * }); + * ``` + * + * @param handler - Function that receives the next handler and request parameters + * @returns A fetch middleware function + */ +export const createMiddleware = (handler) => { + return next => (input, init) => handler(next, input, init); +}; +//# sourceMappingURL=middleware.js.map \ No newline at end of file diff --git a/dist/esm/client/middleware.js.map b/dist/esm/client/middleware.js.map new file mode 100644 index 0000000000..eabfcc54d7 --- /dev/null +++ b/dist/esm/client/middleware.js.map @@ -0,0 +1 @@ +{"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../../src/client/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,4BAA4B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,EAAE,CAAC;gBACT,UAAU,EAAE,eAAe;gBAC3B,QAAQ;gBACR,cAAc;gBACd,KAAK,EAAE,KAAc;aACxB,CAAC,CAAC;YAEH,MAAM,KAAK,CAAC;QAChB,CAAC;IACL,CAAC,CAAC;AACN,CAAC,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,GAAG,UAAwB,EAAc,EAAE;IACxE,OAAO,IAAI,CAAC,EAAE;QACV,OAAO,UAAU,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,CAAC;IACjE,CAAC,CAAC;AACN,CAAC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,OAAwF,EAAc,EAAE;IACrI,OAAO,IAAI,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,KAAqB,EAAE,IAAI,CAAC,CAAC;AAC/E,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/client/sse.d.ts b/dist/esm/client/sse.d.ts new file mode 100644 index 0000000000..acf99f1ea6 --- /dev/null +++ b/dist/esm/client/sse.d.ts @@ -0,0 +1,81 @@ +import { type ErrorEvent, type EventSourceInit } from 'eventsource'; +import { Transport, FetchLike } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +import { OAuthClientProvider } from './auth.js'; +export declare class SseError extends Error { + readonly code: number | undefined; + readonly event: ErrorEvent; + constructor(code: number | undefined, message: string | undefined, event: ErrorEvent); +} +/** + * Configuration options for the `SSEClientTransport`. + */ +export type SSEClientTransportOptions = { + /** + * An OAuth client provider to use for authentication. + * + * When an `authProvider` is specified and the SSE connection is started: + * 1. The connection is attempted with any existing access token from the `authProvider`. + * 2. If the access token has expired, the `authProvider` is used to refresh the token. + * 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`. + * + * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `SSEClientTransport.finishAuth` with the authorization code before retrying the connection. + * + * If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown. + * + * `UnauthorizedError` might also be thrown when sending any message over the SSE transport, indicating that the session has expired, and needs to be re-authed and reconnected. + */ + authProvider?: OAuthClientProvider; + /** + * Customizes the initial SSE request to the server (the request that begins the stream). + * + * NOTE: Setting this property will prevent an `Authorization` header from + * being automatically attached to the SSE request, if an `authProvider` is + * also given. This can be worked around by setting the `Authorization` header + * manually. + */ + eventSourceInit?: EventSourceInit; + /** + * Customizes recurring POST requests to the server. + */ + requestInit?: RequestInit; + /** + * Custom fetch implementation used for all network requests. + */ + fetch?: FetchLike; +}; +/** + * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving + * messages and make separate POST requests for sending messages. + * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period. + */ +export declare class SSEClientTransport implements Transport { + private _eventSource?; + private _endpoint?; + private _abortController?; + private _url; + private _resourceMetadataUrl?; + private _scope?; + private _eventSourceInit?; + private _requestInit?; + private _authProvider?; + private _fetch?; + private _fetchWithInit; + private _protocolVersion?; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(url: URL, opts?: SSEClientTransportOptions); + private _authThenStart; + private _commonHeaders; + private _startOrAuth; + start(): Promise; + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + finishAuth(authorizationCode: string): Promise; + close(): Promise; + send(message: JSONRPCMessage): Promise; + setProtocolVersion(version: string): void; +} +//# sourceMappingURL=sse.d.ts.map \ No newline at end of file diff --git a/dist/esm/client/sse.d.ts.map b/dist/esm/client/sse.d.ts.map new file mode 100644 index 0000000000..3a0053cfc6 --- /dev/null +++ b/dist/esm/client/sse.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../../src/client/sse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,KAAK,UAAU,EAAE,KAAK,eAAe,EAAE,MAAM,aAAa,CAAC;AACjF,OAAO,EAAE,SAAS,EAAE,SAAS,EAAuB,MAAM,wBAAwB,CAAC;AACnF,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AACnE,OAAO,EAAkD,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AAEnH,qBAAa,QAAS,SAAQ,KAAK;aAEX,IAAI,EAAE,MAAM,GAAG,SAAS;aAExB,KAAK,EAAE,UAAU;gBAFjB,IAAI,EAAE,MAAM,GAAG,SAAS,EACxC,OAAO,EAAE,MAAM,GAAG,SAAS,EACX,KAAK,EAAE,UAAU;CAIxC;AAED;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACpC;;;;;;;;;;;;;OAaG;IACH,YAAY,CAAC,EAAE,mBAAmB,CAAC;IAEnC;;;;;;;OAOG;IACH,eAAe,CAAC,EAAE,eAAe,CAAC;IAElC;;OAEG;IACH,WAAW,CAAC,EAAE,WAAW,CAAC;IAE1B;;OAEG;IACH,KAAK,CAAC,EAAE,SAAS,CAAC;CACrB,CAAC;AAEF;;;;GAIG;AACH,qBAAa,kBAAmB,YAAW,SAAS;IAChD,OAAO,CAAC,YAAY,CAAC,CAAc;IACnC,OAAO,CAAC,SAAS,CAAC,CAAM;IACxB,OAAO,CAAC,gBAAgB,CAAC,CAAkB;IAC3C,OAAO,CAAC,IAAI,CAAM;IAClB,OAAO,CAAC,oBAAoB,CAAC,CAAM;IACnC,OAAO,CAAC,MAAM,CAAC,CAAS;IACxB,OAAO,CAAC,gBAAgB,CAAC,CAAkB;IAC3C,OAAO,CAAC,YAAY,CAAC,CAAc;IACnC,OAAO,CAAC,aAAa,CAAC,CAAsB;IAC5C,OAAO,CAAC,MAAM,CAAC,CAAY;IAC3B,OAAO,CAAC,cAAc,CAAY;IAClC,OAAO,CAAC,gBAAgB,CAAC,CAAS;IAElC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,yBAAyB;YAWxC,cAAc;YAyBd,cAAc;IAe5B,OAAO,CAAC,YAAY;IAyEd,KAAK;IAQX;;OAEG;IACG,UAAU,CAAC,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiBpD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAMtB,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IA8ClD,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;CAG5C"} \ No newline at end of file diff --git a/dist/esm/client/sse.js b/dist/esm/client/sse.js new file mode 100644 index 0000000000..6045cb6ba3 --- /dev/null +++ b/dist/esm/client/sse.js @@ -0,0 +1,208 @@ +import { EventSource } from 'eventsource'; +import { createFetchWithInit } from '../shared/transport.js'; +import { JSONRPCMessageSchema } from '../types.js'; +import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js'; +export class SseError extends Error { + constructor(code, message, event) { + super(`SSE error: ${message}`); + this.code = code; + this.event = event; + } +} +/** + * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving + * messages and make separate POST requests for sending messages. + * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period. + */ +export class SSEClientTransport { + constructor(url, opts) { + this._url = url; + this._resourceMetadataUrl = undefined; + this._scope = undefined; + this._eventSourceInit = opts === null || opts === void 0 ? void 0 : opts.eventSourceInit; + this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit; + this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider; + this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch; + this._fetchWithInit = createFetchWithInit(opts === null || opts === void 0 ? void 0 : opts.fetch, opts === null || opts === void 0 ? void 0 : opts.requestInit); + } + async _authThenStart() { + var _a; + if (!this._authProvider) { + throw new UnauthorizedError('No auth provider'); + } + let result; + try { + result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + } + catch (error) { + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + throw error; + } + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(); + } + return await this._startOrAuth(); + } + async _commonHeaders() { + var _a; + const headers = {}; + if (this._authProvider) { + const tokens = await this._authProvider.tokens(); + if (tokens) { + headers['Authorization'] = `Bearer ${tokens.access_token}`; + } + } + if (this._protocolVersion) { + headers['mcp-protocol-version'] = this._protocolVersion; + } + return new Headers({ ...headers, ...(_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers }); + } + _startOrAuth() { + var _a, _b, _c; + const fetchImpl = ((_c = (_b = (_a = this === null || this === void 0 ? void 0 : this._eventSourceInit) === null || _a === void 0 ? void 0 : _a.fetch) !== null && _b !== void 0 ? _b : this._fetch) !== null && _c !== void 0 ? _c : fetch); + return new Promise((resolve, reject) => { + this._eventSource = new EventSource(this._url.href, { + ...this._eventSourceInit, + fetch: async (url, init) => { + const headers = await this._commonHeaders(); + headers.set('Accept', 'text/event-stream'); + const response = await fetchImpl(url, { + ...init, + headers + }); + if (response.status === 401 && response.headers.has('www-authenticate')) { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + } + return response; + } + }); + this._abortController = new AbortController(); + this._eventSource.onerror = event => { + var _a; + if (event.code === 401 && this._authProvider) { + this._authThenStart().then(resolve, reject); + return; + } + const error = new SseError(event.code, event.message, event); + reject(error); + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }; + this._eventSource.onopen = () => { + // The connection is open, but we need to wait for the endpoint to be received. + }; + this._eventSource.addEventListener('endpoint', (event) => { + var _a; + const messageEvent = event; + try { + this._endpoint = new URL(messageEvent.data, this._url); + if (this._endpoint.origin !== this._url.origin) { + throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`); + } + } + catch (error) { + reject(error); + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + void this.close(); + return; + } + resolve(); + }); + this._eventSource.onmessage = (event) => { + var _a, _b; + const messageEvent = event; + let message; + try { + message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data)); + } + catch (error) { + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + return; + } + (_b = this.onmessage) === null || _b === void 0 ? void 0 : _b.call(this, message); + }; + }); + } + async start() { + if (this._eventSource) { + throw new Error('SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + return await this._startOrAuth(); + } + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + async finishAuth(authorizationCode) { + if (!this._authProvider) { + throw new UnauthorizedError('No auth provider'); + } + const result = await auth(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError('Failed to authorize'); + } + } + async close() { + var _a, _b, _c; + (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + (_b = this._eventSource) === null || _b === void 0 ? void 0 : _b.close(); + (_c = this.onclose) === null || _c === void 0 ? void 0 : _c.call(this); + } + async send(message) { + var _a, _b, _c; + if (!this._endpoint) { + throw new Error('Not connected'); + } + try { + const headers = await this._commonHeaders(); + headers.set('content-type', 'application/json'); + const init = { + ...this._requestInit, + method: 'POST', + headers, + body: JSON.stringify(message), + signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal + }; + const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._endpoint, init); + if (!response.ok) { + if (response.status === 401 && this._authProvider) { + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + const result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(); + } + // Purposely _not_ awaited, so we don't call onerror twice + return this.send(message); + } + const text = await response.text().catch(() => null); + throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); + } + } + catch (error) { + (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error); + throw error; + } + } + setProtocolVersion(version) { + this._protocolVersion = version; + } +} +//# sourceMappingURL=sse.js.map \ No newline at end of file diff --git a/dist/esm/client/sse.js.map b/dist/esm/client/sse.js.map new file mode 100644 index 0000000000..aafaf36635 --- /dev/null +++ b/dist/esm/client/sse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sse.js","sourceRoot":"","sources":["../../../src/client/sse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAyC,MAAM,aAAa,CAAC;AACjF,OAAO,EAAwB,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AACnF,OAAO,EAAkB,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,IAAI,EAAc,4BAA4B,EAAuB,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAEnH,MAAM,OAAO,QAAS,SAAQ,KAAK;IAC/B,YACoB,IAAwB,E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AC,CAAC;YACpF,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,MAAA,IAAI,CAAC,OAAO,qDAAG,KAAc,CAAC,CAAC;YAC/B,MAAM,KAAK,CAAC;QAChB,CAAC;IACL,CAAC;IAED,kBAAkB,CAAC,OAAe;QAC9B,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;IACpC,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/client/stdio.d.ts b/dist/esm/client/stdio.d.ts new file mode 100644 index 0000000000..58d0b6ccba --- /dev/null +++ b/dist/esm/client/stdio.d.ts @@ -0,0 +1,78 @@ +import { IOType } from 'node:child_process'; +import { Stream } from 'node:stream'; +import { Transport } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +export type StdioServerParameters = { + /** + * The executable to run to start the server. + */ + command: string; + /** + * Command line arguments to pass to the executable. + */ + args?: string[]; + /** + * The environment to use when spawning the process. + * + * If not specified, the result of getDefaultEnvironment() will be used. + */ + env?: Record; + /** + * How to handle stderr of the child process. This matches the semantics of Node's `child_process.spawn`. + * + * The default is "inherit", meaning messages to stderr will be printed to the parent process's stderr. + */ + stderr?: IOType | Stream | number; + /** + * The working directory to use when spawning the process. + * + * If not specified, the current working directory will be inherited. + */ + cwd?: string; +}; +/** + * Environment variables to inherit by default, if an environment is not explicitly given. + */ +export declare const DEFAULT_INHERITED_ENV_VARS: string[]; +/** + * Returns a default environment object including only environment variables deemed safe to inherit. + */ +export declare function getDefaultEnvironment(): Record; +/** + * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout. + * + * This transport is only available in Node.js environments. + */ +export declare class StdioClientTransport implements Transport { + private _process?; + private _abortController; + private _readBuffer; + private _serverParams; + private _stderrStream; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(server: StdioServerParameters); + /** + * Starts the server process and prepares to communicate with it. + */ + start(): Promise; + /** + * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". + * + * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to + * attach listeners before the start method is invoked. This prevents loss of any early + * error output emitted by the child process. + */ + get stderr(): Stream | null; + /** + * The child process pid spawned by this transport. + * + * This is only available after the transport has been started. + */ + get pid(): number | null; + private processReadBuffer; + close(): Promise; + send(message: JSONRPCMessage): Promise; +} +//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/dist/esm/client/stdio.d.ts.map b/dist/esm/client/stdio.d.ts.map new file mode 100644 index 0000000000..44f6de451b --- /dev/null +++ b/dist/esm/client/stdio.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/client/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAG1D,OAAO,EAAE,MAAM,EAAe,MAAM,aAAa,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE7C,MAAM,MAAM,qBAAqB,GAAG;IAChC;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAEhB;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAE7B;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IAElC;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,0BAA0B,UAiBuB,CAAC;AAE/D;;GAEG;AACH,wBAAgB,qBAAqB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAkB9D;AAED;;;;GAIG;AACH,qBAAa,oBAAqB,YAAW,SAAS;IAClD,OAAO,CAAC,QAAQ,CAAC,CAAe;IAChC,OAAO,CAAC,gBAAgB,CAA0C;IAClE,OAAO,CAAC,WAAW,CAAgC;IACnD,OAAO,CAAC,aAAa,CAAwB;IAC7C,OAAO,CAAC,aAAa,CAA4B;IAEjD,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,MAAM,EAAE,qBAAqB;IAOzC;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IA4D5B;;;;;;OAMG;IACH,IAAI,MAAM,IAAI,MAAM,GAAG,IAAI,CAM1B;IAED;;;;OAIG;IACH,IAAI,GAAG,IAAI,MAAM,GAAG,IAAI,CAEvB;IAED,OAAO,CAAC,iBAAiB;IAenB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAM5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAc/C"} \ No newline at end of file diff --git a/dist/esm/client/stdio.js b/dist/esm/client/stdio.js new file mode 100644 index 0000000000..d77c64d15b --- /dev/null +++ b/dist/esm/client/stdio.js @@ -0,0 +1,176 @@ +import spawn from 'cross-spawn'; +import process from 'node:process'; +import { PassThrough } from 'node:stream'; +import { ReadBuffer, serializeMessage } from '../shared/stdio.js'; +/** + * Environment variables to inherit by default, if an environment is not explicitly given. + */ +export const DEFAULT_INHERITED_ENV_VARS = process.platform === 'win32' + ? [ + 'APPDATA', + 'HOMEDRIVE', + 'HOMEPATH', + 'LOCALAPPDATA', + 'PATH', + 'PROCESSOR_ARCHITECTURE', + 'SYSTEMDRIVE', + 'SYSTEMROOT', + 'TEMP', + 'USERNAME', + 'USERPROFILE', + 'PROGRAMFILES' + ] + : /* list inspired by the default env inheritance of sudo */ + ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER']; +/** + * Returns a default environment object including only environment variables deemed safe to inherit. + */ +export function getDefaultEnvironment() { + const env = {}; + for (const key of DEFAULT_INHERITED_ENV_VARS) { + const value = process.env[key]; + if (value === undefined) { + continue; + } + if (value.startsWith('()')) { + // Skip functions, which are a security risk. + continue; + } + env[key] = value; + } + return env; +} +/** + * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout. + * + * This transport is only available in Node.js environments. + */ +export class StdioClientTransport { + constructor(server) { + this._abortController = new AbortController(); + this._readBuffer = new ReadBuffer(); + this._stderrStream = null; + this._serverParams = server; + if (server.stderr === 'pipe' || server.stderr === 'overlapped') { + this._stderrStream = new PassThrough(); + } + } + /** + * Starts the server process and prepares to communicate with it. + */ + async start() { + if (this._process) { + throw new Error('StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + return new Promise((resolve, reject) => { + var _a, _b, _c, _d, _e; + this._process = spawn(this._serverParams.command, (_a = this._serverParams.args) !== null && _a !== void 0 ? _a : [], { + // merge default env with server env because mcp server needs some env vars + env: { + ...getDefaultEnvironment(), + ...this._serverParams.env + }, + stdio: ['pipe', 'pipe', (_b = this._serverParams.stderr) !== null && _b !== void 0 ? _b : 'inherit'], + shell: false, + signal: this._abortController.signal, + windowsHide: process.platform === 'win32' && isElectron(), + cwd: this._serverParams.cwd + }); + this._process.on('error', error => { + var _a, _b; + if (error.name === 'AbortError') { + // Expected when close() is called. + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + return; + } + reject(error); + (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); + }); + this._process.on('spawn', () => { + resolve(); + }); + this._process.on('close', _code => { + var _a; + this._process = undefined; + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + }); + (_c = this._process.stdin) === null || _c === void 0 ? void 0 : _c.on('error', error => { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }); + (_d = this._process.stdout) === null || _d === void 0 ? void 0 : _d.on('data', chunk => { + this._readBuffer.append(chunk); + this.processReadBuffer(); + }); + (_e = this._process.stdout) === null || _e === void 0 ? void 0 : _e.on('error', error => { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }); + if (this._stderrStream && this._process.stderr) { + this._process.stderr.pipe(this._stderrStream); + } + }); + } + /** + * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". + * + * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to + * attach listeners before the start method is invoked. This prevents loss of any early + * error output emitted by the child process. + */ + get stderr() { + var _a, _b; + if (this._stderrStream) { + return this._stderrStream; + } + return (_b = (_a = this._process) === null || _a === void 0 ? void 0 : _a.stderr) !== null && _b !== void 0 ? _b : null; + } + /** + * The child process pid spawned by this transport. + * + * This is only available after the transport has been started. + */ + get pid() { + var _a, _b; + return (_b = (_a = this._process) === null || _a === void 0 ? void 0 : _a.pid) !== null && _b !== void 0 ? _b : null; + } + processReadBuffer() { + var _a, _b; + while (true) { + try { + const message = this._readBuffer.readMessage(); + if (message === null) { + break; + } + (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message); + } + catch (error) { + (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); + } + } + } + async close() { + this._abortController.abort(); + this._process = undefined; + this._readBuffer.clear(); + } + send(message) { + return new Promise(resolve => { + var _a; + if (!((_a = this._process) === null || _a === void 0 ? void 0 : _a.stdin)) { + throw new Error('Not connected'); + } + const json = serializeMessage(message); + if (this._process.stdin.write(json)) { + resolve(); + } + else { + this._process.stdin.once('drain', resolve); + } + }); + } +} +function isElectron() { + return 'type' in process; +} +//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/dist/esm/client/stdio.js.map b/dist/esm/client/stdio.js.map new file mode 100644 index 0000000000..ad681edebb --- /dev/null +++ b/dist/esm/client/stdio.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/client/stdio.ts"],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AAQ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC/C,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAED,SAAS,UAAU;IACf,OAAO,MAAM,IAAI,OAAO,CAAC;AAC7B,CAAC"} \ No newline at end of file diff --git a/dist/esm/client/streamableHttp.d.ts b/dist/esm/client/streamableHttp.d.ts new file mode 100644 index 0000000000..6c6a32f473 --- /dev/null +++ b/dist/esm/client/streamableHttp.d.ts @@ -0,0 +1,159 @@ +import { Transport, FetchLike } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +import { OAuthClientProvider } from './auth.js'; +export declare class StreamableHTTPError extends Error { + readonly code: number | undefined; + constructor(code: number | undefined, message: string | undefined); +} +/** + * Options for starting or authenticating an SSE connection + */ +export interface StartSSEOptions { + /** + * The resumption token used to continue long-running requests that were interrupted. + * + * This allows clients to reconnect and continue from where they left off. + */ + resumptionToken?: string; + /** + * A callback that is invoked when the resumption token changes. + * + * This allows clients to persist the latest token for potential reconnection. + */ + onresumptiontoken?: (token: string) => void; + /** + * Override Message ID to associate with the replay message + * so that response can be associate with the new resumed request. + */ + replayMessageId?: string | number; +} +/** + * Configuration options for reconnection behavior of the StreamableHTTPClientTransport. + */ +export interface StreamableHTTPReconnectionOptions { + /** + * Maximum backoff time between reconnection attempts in milliseconds. + * Default is 30000 (30 seconds). + */ + maxReconnectionDelay: number; + /** + * Initial backoff time between reconnection attempts in milliseconds. + * Default is 1000 (1 second). + */ + initialReconnectionDelay: number; + /** + * The factor by which the reconnection delay increases after each attempt. + * Default is 1.5. + */ + reconnectionDelayGrowFactor: number; + /** + * Maximum number of reconnection attempts before giving up. + * Default is 2. + */ + maxRetries: number; +} +/** + * Configuration options for the `StreamableHTTPClientTransport`. + */ +export type StreamableHTTPClientTransportOptions = { + /** + * An OAuth client provider to use for authentication. + * + * When an `authProvider` is specified and the connection is started: + * 1. The connection is attempted with any existing access token from the `authProvider`. + * 2. If the access token has expired, the `authProvider` is used to refresh the token. + * 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`. + * + * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `StreamableHTTPClientTransport.finishAuth` with the authorization code before retrying the connection. + * + * If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown. + * + * `UnauthorizedError` might also be thrown when sending any message over the transport, indicating that the session has expired, and needs to be re-authed and reconnected. + */ + authProvider?: OAuthClientProvider; + /** + * Customizes HTTP requests to the server. + */ + requestInit?: RequestInit; + /** + * Custom fetch implementation used for all network requests. + */ + fetch?: FetchLike; + /** + * Options to configure the reconnection behavior. + */ + reconnectionOptions?: StreamableHTTPReconnectionOptions; + /** + * Session ID for the connection. This is used to identify the session on the server. + * When not provided and connecting to a server that supports session IDs, the server will generate a new session ID. + */ + sessionId?: string; +}; +/** + * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events + * for receiving messages. + */ +export declare class StreamableHTTPClientTransport implements Transport { + private _abortController?; + private _url; + private _resourceMetadataUrl?; + private _scope?; + private _requestInit?; + private _authProvider?; + private _fetch?; + private _fetchWithInit; + private _sessionId?; + private _reconnectionOptions; + private _protocolVersion?; + private _hasCompletedAuthFlow; + private _lastUpscopingHeader?; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(url: URL, opts?: StreamableHTTPClientTransportOptions); + private _authThenStart; + private _commonHeaders; + private _startOrAuthSse; + /** + * Calculates the next reconnection delay using backoff algorithm + * + * @param attempt Current reconnection attempt count for the specific stream + * @returns Time to wait in milliseconds before next reconnection attempt + */ + private _getNextReconnectionDelay; + /** + * Schedule a reconnection attempt with exponential backoff + * + * @param lastEventId The ID of the last received event for resumability + * @param attemptCount Current reconnection attempt count for this specific stream + */ + private _scheduleReconnection; + private _handleSseStream; + start(): Promise; + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + finishAuth(authorizationCode: string): Promise; + close(): Promise; + send(message: JSONRPCMessage | JSONRPCMessage[], options?: { + resumptionToken?: string; + onresumptiontoken?: (token: string) => void; + }): Promise; + get sessionId(): string | undefined; + /** + * Terminates the current session by sending a DELETE request to the server. + * + * Clients that no longer need a particular session + * (e.g., because the user is leaving the client application) SHOULD send an + * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly + * terminate the session. + * + * The server MAY respond with HTTP 405 Method Not Allowed, indicating that + * the server does not allow clients to terminate sessions. + */ + terminateSession(): Promise; + setProtocolVersion(version: string): void; + get protocolVersion(): string | undefined; +} +//# sourceMappingURL=streamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/esm/client/streamableHttp.d.ts.map b/dist/esm/client/streamableHttp.d.ts.map new file mode 100644 index 0000000000..cbca11957b --- /dev/null +++ b/dist/esm/client/streamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.d.ts","sourceRoot":"","sources":["../../../src/client/streamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAyC,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAkE,cAAc,EAAwB,MAAM,aAAa,CAAC;AACnI,OAAO,EAAkD,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AAWnH,qBAAa,mBAAoB,SAAQ,KAAK;aAEtB,IAAI,EAAE,MAAM,GAAG,SAAS;gBAAxB,IAAI,EAAE,MAAM,GAAG,SAAS,EACxC,OAAO,EAAE,MAAM,GAAG,SAAS;CAIlC;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC5B;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAA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AK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,oCAAoC;YAYnD,cAAc;YAyBd,cAAc;YAwBd,eAAe;IAyC7B;;;;;OAKG;IACH,OAAO,CAAC,yBAAyB;IAUjC;;;;;OAKG;IACH,OAAO,CAAC,qBAAqB;IAwB7B,OAAO,CAAC,gBAAgB;IAkElB,KAAK;IAUX;;OAEG;IACG,UAAU,CAAC,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiBpD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAOtB,IAAI,CACN,OAAO,EAAE,cAAc,GAAG,cAAc,EAAE,EAC1C,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,MAAM,CAAC;QAAC,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;KAAE,GACpF,OAAO,CAAC,IAAI,CAAC;IAoJhB,IAAI,SAAS,IAAI,MAAM,GAAG,SAAS,CAElC;IAED;;;;;;;;;;OAUG;IACG,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;IA8BvC,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAGzC,IAAI,eAAe,IAAI,MAAM,GAAG,SAAS,CAExC;CACJ"} \ No newline at end of file diff --git a/dist/esm/client/streamableHttp.js b/dist/esm/client/streamableHttp.js new file mode 100644 index 0000000000..808dc097d0 --- /dev/null +++ b/dist/esm/client/streamableHttp.js @@ -0,0 +1,421 @@ +import { createFetchWithInit, normalizeHeaders } from '../shared/transport.js'; +import { isInitializedNotification, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessageSchema } from '../types.js'; +import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js'; +import { EventSourceParserStream } from 'eventsource-parser/stream'; +// Default reconnection options for StreamableHTTP connections +const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = { + initialReconnectionDelay: 1000, + maxReconnectionDelay: 30000, + reconnectionDelayGrowFactor: 1.5, + maxRetries: 2 +}; +export class StreamableHTTPError extends Error { + constructor(code, message) { + super(`Streamable HTTP error: ${message}`); + this.code = code; + } +} +/** + * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events + * for receiving messages. + */ +export class StreamableHTTPClientTransport { + constructor(url, opts) { + var _a; + this._hasCompletedAuthFlow = false; // Circuit breaker: detect auth success followed by immediate 401 + this._url = url; + this._resourceMetadataUrl = undefined; + this._scope = undefined; + this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit; + this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider; + this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch; + this._fetchWithInit = createFetchWithInit(opts === null || opts === void 0 ? void 0 : opts.fetch, opts === null || opts === void 0 ? void 0 : opts.requestInit); + this._sessionId = opts === null || opts === void 0 ? void 0 : opts.sessionId; + this._reconnectionOptions = (_a = opts === null || opts === void 0 ? void 0 : opts.reconnectionOptions) !== null && _a !== void 0 ? _a : DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS; + } + async _authThenStart() { + var _a; + if (!this._authProvider) { + throw new UnauthorizedError('No auth provider'); + } + let result; + try { + result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + } + catch (error) { + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + throw error; + } + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(); + } + return await this._startOrAuthSse({ resumptionToken: undefined }); + } + async _commonHeaders() { + var _a; + const headers = {}; + if (this._authProvider) { + const tokens = await this._authProvider.tokens(); + if (tokens) { + headers['Authorization'] = `Bearer ${tokens.access_token}`; + } + } + if (this._sessionId) { + headers['mcp-session-id'] = this._sessionId; + } + if (this._protocolVersion) { + headers['mcp-protocol-version'] = this._protocolVersion; + } + const extraHeaders = normalizeHeaders((_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers); + return new Headers({ + ...headers, + ...extraHeaders + }); + } + async _startOrAuthSse(options) { + var _a, _b, _c; + const { resumptionToken } = options; + try { + // Try to open an initial SSE stream with GET to listen for server messages + // This is optional according to the spec - server may not support it + const headers = await this._commonHeaders(); + headers.set('Accept', 'text/event-stream'); + // Include Last-Event-ID header for resumable streams if provided + if (resumptionToken) { + headers.set('last-event-id', resumptionToken); + } + const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(this._url, { + method: 'GET', + headers, + signal: (_b = this._abortController) === null || _b === void 0 ? void 0 : _b.signal + }); + if (!response.ok) { + if (response.status === 401 && this._authProvider) { + // Need to authenticate + return await this._authThenStart(); + } + // 405 indicates that the server does not offer an SSE stream at GET endpoint + // This is an expected case that should not trigger an error + if (response.status === 405) { + return; + } + throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`); + } + this._handleSseStream(response.body, options, true); + } + catch (error) { + (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error); + throw error; + } + } + /** + * Calculates the next reconnection delay using backoff algorithm + * + * @param attempt Current reconnection attempt count for the specific stream + * @returns Time to wait in milliseconds before next reconnection attempt + */ + _getNextReconnectionDelay(attempt) { + // Access default values directly, ensuring they're never undefined + const initialDelay = this._reconnectionOptions.initialReconnectionDelay; + const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor; + const maxDelay = this._reconnectionOptions.maxReconnectionDelay; + // Cap at maximum delay + return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay); + } + /** + * Schedule a reconnection attempt with exponential backoff + * + * @param lastEventId The ID of the last received event for resumability + * @param attemptCount Current reconnection attempt count for this specific stream + */ + _scheduleReconnection(options, attemptCount = 0) { + var _a; + // Use provided options or default options + const maxRetries = this._reconnectionOptions.maxRetries; + // Check if we've exceeded maximum retry attempts + if (maxRetries > 0 && attemptCount >= maxRetries) { + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`)); + return; + } + // Calculate next delay based on current attempt count + const delay = this._getNextReconnectionDelay(attemptCount); + // Schedule the reconnection + setTimeout(() => { + // Use the last event ID to resume where we left off + this._startOrAuthSse(options).catch(error => { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`)); + // Schedule another attempt if this one failed, incrementing the attempt counter + this._scheduleReconnection(options, attemptCount + 1); + }); + }, delay); + } + _handleSseStream(stream, options, isReconnectable) { + if (!stream) { + return; + } + const { onresumptiontoken, replayMessageId } = options; + let lastEventId; + const processStream = async () => { + var _a, _b, _c, _d; + // this is the closest we can get to trying to catch network errors + // if something happens reader will throw + try { + // Create a pipeline: binary stream -> text decoder -> SSE parser + const reader = stream + .pipeThrough(new TextDecoderStream()) + .pipeThrough(new EventSourceParserStream()) + .getReader(); + while (true) { + const { value: event, done } = await reader.read(); + if (done) { + break; + } + // Update last event ID if provided + if (event.id) { + lastEventId = event.id; + onresumptiontoken === null || onresumptiontoken === void 0 ? void 0 : onresumptiontoken(event.id); + } + if (!event.event || event.event === 'message') { + try { + const message = JSONRPCMessageSchema.parse(JSON.parse(event.data)); + if (replayMessageId !== undefined && isJSONRPCResponse(message)) { + message.id = replayMessageId; + } + (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message); + } + catch (error) { + (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); + } + } + } + } + catch (error) { + // Handle stream errors - likely a network disconnect + (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, new Error(`SSE stream disconnected: ${error}`)); + // Attempt to reconnect if the stream disconnects unexpectedly and we aren't closing + if (isReconnectable && this._abortController && !this._abortController.signal.aborted) { + // Use the exponential backoff reconnection strategy + try { + this._scheduleReconnection({ + resumptionToken: lastEventId, + onresumptiontoken, + replayMessageId + }, 0); + } + catch (error) { + (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`)); + } + } + } + }; + processStream(); + } + async start() { + if (this._abortController) { + throw new Error('StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + this._abortController = new AbortController(); + } + /** + * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. + */ + async finishAuth(authorizationCode) { + if (!this._authProvider) { + throw new UnauthorizedError('No auth provider'); + } + const result = await auth(this._authProvider, { + serverUrl: this._url, + authorizationCode, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError('Failed to authorize'); + } + } + async close() { + var _a, _b; + // Abort any pending requests + (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.abort(); + (_b = this.onclose) === null || _b === void 0 ? void 0 : _b.call(this); + } + async send(message, options) { + var _a, _b, _c, _d; + try { + const { resumptionToken, onresumptiontoken } = options || {}; + if (resumptionToken) { + // If we have at last event ID, we need to reconnect the SSE stream + this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : undefined }).catch(err => { var _a; return (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, err); }); + return; + } + const headers = await this._commonHeaders(); + headers.set('content-type', 'application/json'); + headers.set('accept', 'application/json, text/event-stream'); + const init = { + ...this._requestInit, + method: 'POST', + headers, + body: JSON.stringify(message), + signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal + }; + const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._url, init); + // Handle session ID received during initialization + const sessionId = response.headers.get('mcp-session-id'); + if (sessionId) { + this._sessionId = sessionId; + } + if (!response.ok) { + if (response.status === 401 && this._authProvider) { + // Prevent infinite recursion when server returns 401 after successful auth + if (this._hasCompletedAuthFlow) { + throw new StreamableHTTPError(401, 'Server returned 401 after successful authentication'); + } + const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); + this._resourceMetadataUrl = resourceMetadataUrl; + this._scope = scope; + const result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetchWithInit + }); + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(); + } + // Mark that we completed auth flow + this._hasCompletedAuthFlow = true; + // Purposely _not_ awaited, so we don't call onerror twice + return this.send(message); + } + if (response.status === 403 && this._authProvider) { + const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response); + if (error === 'insufficient_scope') { + const wwwAuthHeader = response.headers.get('WWW-Authenticate'); + // Check if we've already tried upscoping with this header to prevent infinite loops. + if (this._lastUpscopingHeader === wwwAuthHeader) { + throw new StreamableHTTPError(403, 'Server returned 403 after trying upscoping'); + } + if (scope) { + this._scope = scope; + } + if (resourceMetadataUrl) { + this._resourceMetadataUrl = resourceMetadataUrl; + } + // Mark that upscoping was tried. + this._lastUpscopingHeader = wwwAuthHeader !== null && wwwAuthHeader !== void 0 ? wwwAuthHeader : undefined; + const result = await auth(this._authProvider, { + serverUrl: this._url, + resourceMetadataUrl: this._resourceMetadataUrl, + scope: this._scope, + fetchFn: this._fetch + }); + if (result !== 'AUTHORIZED') { + throw new UnauthorizedError(); + } + return this.send(message); + } + } + const text = await response.text().catch(() => null); + throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); + } + // Reset auth loop flag on successful response + this._hasCompletedAuthFlow = false; + this._lastUpscopingHeader = undefined; + // If the response is 202 Accepted, there's no body to process + if (response.status === 202) { + // if the accepted notification is initialized, we start the SSE stream + // if it's supported by the server + if (isInitializedNotification(message)) { + // Start without a lastEventId since this is a fresh connection + this._startOrAuthSse({ resumptionToken: undefined }).catch(err => { var _a; return (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, err); }); + } + return; + } + // Get original message(s) for detecting request IDs + const messages = Array.isArray(message) ? message : [message]; + const hasRequests = messages.filter(msg => 'method' in msg && 'id' in msg && msg.id !== undefined).length > 0; + // Check the response type + const contentType = response.headers.get('content-type'); + if (hasRequests) { + if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('text/event-stream')) { + // Handle SSE stream responses for requests + // We use the same handler as standalone streams, which now supports + // reconnection with the last event ID + this._handleSseStream(response.body, { onresumptiontoken }, false); + } + else if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) { + // For non-streaming servers, we might get direct JSON responses + const data = await response.json(); + const responseMessages = Array.isArray(data) + ? data.map(msg => JSONRPCMessageSchema.parse(msg)) + : [JSONRPCMessageSchema.parse(data)]; + for (const msg of responseMessages) { + (_c = this.onmessage) === null || _c === void 0 ? void 0 : _c.call(this, msg); + } + } + else { + throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`); + } + } + } + catch (error) { + (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error); + throw error; + } + } + get sessionId() { + return this._sessionId; + } + /** + * Terminates the current session by sending a DELETE request to the server. + * + * Clients that no longer need a particular session + * (e.g., because the user is leaving the client application) SHOULD send an + * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly + * terminate the session. + * + * The server MAY respond with HTTP 405 Method Not Allowed, indicating that + * the server does not allow clients to terminate sessions. + */ + async terminateSession() { + var _a, _b, _c; + if (!this._sessionId) { + return; // No session to terminate + } + try { + const headers = await this._commonHeaders(); + const init = { + ...this._requestInit, + method: 'DELETE', + headers, + signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal + }; + const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._url, init); + // We specifically handle 405 as a valid response according to the spec, + // meaning the server does not support explicit session termination + if (!response.ok && response.status !== 405) { + throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`); + } + this._sessionId = undefined; + } + catch (error) { + (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error); + throw error; + } + } + setProtocolVersion(version) { + this._protocolVersion = version; + } + get protocolVersion() { + return this._protocolVersion; + } +} +//# sourceMappingURL=streamableHttp.js.map \ No newline at end of file diff --git a/dist/esm/client/streamableHttp.js.map b/dist/esm/client/streamableHttp.js.map new file mode 100644 index 0000000000..e86b4545bc --- /dev/null +++ b/dist/esm/client/streamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.js","sourceRoot":"","sources":["../../../src/client/streamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwB,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAE,yBAAyB,EAAE,gBAAgB,EAAE,iBAAiB,EAAkB,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnI,OAAO,EAAE,IAAI,EAAc,4BAA4B,EAAuB,iBAAiB,EAAE,MAAM,WAAW,CAAC;AACnH,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AAEpE,8DAA8D;AAC9D,MAAM,4CAA4C,GAAsC;IACpF,wBAAwB,EAAE,IAAI;IAC9B,oBAAoB,EAAE,KAAK;IAC3B,2BAA2B,EAAE,GAAG;IAChC,UAAU,EAAE,CAAC;CAChB,CAAC;AAEF,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAC1C,YACoB,IAAwB,EACxC,OAA2B;QAE3B,KAAK,CAAC,0BAA0B,OAAO,EAAE,CAAC,CAAC;QAH3B,SAAI,GAAJ,IAAI,CAAoB;IAI5C,CAAC;CACJ;AAkGD;;;;GAIG;AACH,MAAM,OAAO,6BAA6B;IAmBtC,YAAY,GAAQ,EAAE,IAA2C;;QAPzD,0BAAqB,GAAG,KAAK,CAAC,CAAC,iEAAiE;QAQpG,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;QAChB,IAAI,CAAC,oBAA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GAAG;gBACT,GAAG,IAAI,CAAC,YAAY;gBACpB,MAAM,EAAE,QAAQ;gBAChB,OAAO;gBACP,MAAM,EAAE,MAAA,IAAI,CAAC,gBAAgB,0CAAE,MAAM;aACxC,CAAC;YAEF,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAA,IAAI,CAAC,MAAM,mCAAI,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;YAE/D,wEAAwE;YACxE,mEAAmE;YACnE,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;gBAC1C,MAAM,IAAI,mBAAmB,CAAC,QAAQ,CAAC,MAAM,EAAE,gCAAgC,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAC;YAC1G,CAAC;YAED,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAChC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,MAAA,IAAI,CAAC,OAAO,qDAAG,KAAc,CAAC,CAAC;YAC/B,MAAM,KAAK,CAAC;QAChB,CAAC;IACL,CAAC;IAED,kBAAkB,CAAC,OAAe;QAC9B,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;IACpC,CAAC;IACD,IAAI,eAAe;QACf,OAAO,IAAI,CAAC,gBAAgB,CAAC;IACjC,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/client/websocket.d.ts b/dist/esm/client/websocket.d.ts new file mode 100644 index 0000000000..78f95de3b9 --- /dev/null +++ b/dist/esm/client/websocket.d.ts @@ -0,0 +1,17 @@ +import { Transport } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; +/** + * Client transport for WebSocket: this will connect to a server over the WebSocket protocol. + */ +export declare class WebSocketClientTransport implements Transport { + private _socket?; + private _url; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + constructor(url: URL); + start(): Promise; + close(): Promise; + send(message: JSONRPCMessage): Promise; +} +//# sourceMappingURL=websocket.d.ts.map \ No newline at end of file diff --git a/dist/esm/client/websocket.d.ts.map b/dist/esm/client/websocket.d.ts.map new file mode 100644 index 0000000000..2882d98226 --- /dev/null +++ b/dist/esm/client/websocket.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../../../src/client/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AAInE;;GAEG;AACH,qBAAa,wBAAyB,YAAW,SAAS;IACtD,OAAO,CAAC,OAAO,CAAC,CAAY;IAC5B,OAAO,CAAC,IAAI,CAAM;IAElB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,GAAG,EAAE,GAAG;IAIpB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAsChB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAW/C"} \ No newline at end of file diff --git a/dist/esm/client/websocket.js b/dist/esm/client/websocket.js new file mode 100644 index 0000000000..d55feabeb7 --- /dev/null +++ b/dist/esm/client/websocket.js @@ -0,0 +1,59 @@ +import { JSONRPCMessageSchema } from '../types.js'; +const SUBPROTOCOL = 'mcp'; +/** + * Client transport for WebSocket: this will connect to a server over the WebSocket protocol. + */ +export class WebSocketClientTransport { + constructor(url) { + this._url = url; + } + start() { + if (this._socket) { + throw new Error('WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.'); + } + return new Promise((resolve, reject) => { + this._socket = new WebSocket(this._url, SUBPROTOCOL); + this._socket.onerror = event => { + var _a; + const error = 'error' in event ? event.error : new Error(`WebSocket error: ${JSON.stringify(event)}`); + reject(error); + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }; + this._socket.onopen = () => { + resolve(); + }; + this._socket.onclose = () => { + var _a; + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + }; + this._socket.onmessage = (event) => { + var _a, _b; + let message; + try { + message = JSONRPCMessageSchema.parse(JSON.parse(event.data)); + } + catch (error) { + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + return; + } + (_b = this.onmessage) === null || _b === void 0 ? void 0 : _b.call(this, message); + }; + }); + } + async close() { + var _a; + (_a = this._socket) === null || _a === void 0 ? void 0 : _a.close(); + } + send(message) { + return new Promise((resolve, reject) => { + var _a; + if (!this._socket) { + reject(new Error('Not connected')); + return; + } + (_a = this._socket) === null || _a === void 0 ? void 0 : _a.send(JSON.stringify(message)); + resolve(); + }); + } +} +//# sourceMappingURL=websocket.js.map \ No newline at end of file diff --git a/dist/esm/client/websocket.js.map b/dist/esm/client/websocket.js.map new file mode 100644 index 0000000000..616164b1d9 --- /dev/null +++ b/dist/esm/client/websocket.js.map @@ -0,0 +1 @@ +{"version":3,"file":"websocket.js","sourceRoot":"","sources":["../../../src/client/websocket.ts"],"names":[],"mappings":"AACA,OAAO,EAAkB,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnE,MAAM,WAAW,GAAG,KAAK,CAAC;AAE1B;;GAEG;AACH,MAAM,OAAO,wBAAwB;IAQjC,YAAY,GAAQ;QAChB,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;IACpB,CAAC;IAED,KAAK;QACD,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACf,MAAM,IAAI,KAAK,CACX,mHAAmH,CACtH,CAAC;QACN,CAAC;QAED,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACnC,IAAI,CAAC,OAAO,GAAG,IAAI,SAAS,CAAC,IAAI,CA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EAAE;;YACnC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;gBAChB,MAAM,CAAC,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC,CAAC;gBACnC,OAAO;YACX,CAAC;YAED,MAAA,IAAI,CAAC,OAAO,0CAAE,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;YAC5C,OAAO,EAAE,CAAC;QACd,CAAC,CAAC,CAAC;IACP,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/examples/client/elicitationUrlExample.d.ts b/dist/esm/examples/client/elicitationUrlExample.d.ts new file mode 100644 index 0000000000..611f6eba22 --- /dev/null +++ b/dist/esm/examples/client/elicitationUrlExample.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=elicitationUrlExample.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/client/elicitationUrlExample.d.ts.map b/dist/esm/examples/client/elicitationUrlExample.d.ts.map new file mode 100644 index 0000000000..e749adfb95 --- /dev/null +++ b/dist/esm/examples/client/elicitationUrlExample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/elicitationUrlExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/client/elicitationUrlExample.js b/dist/esm/examples/client/elicitationUrlExample.js new file mode 100644 index 0000000000..741e83d3ed --- /dev/null +++ b/dist/esm/examples/client/elicitationUrlExample.js @@ -0,0 +1,691 @@ +// Run with: npx tsx src/examples/client/elicitationUrlExample.ts +// +// This example demonstrates how to use URL elicitation to securely +// collect user input in a remote (HTTP) server. +// URL elicitation allows servers to prompt the end-user to open a URL in their browser +// to collect sensitive information. +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { createInterface } from 'node:readline'; +import { ListToolsResultSchema, CallToolResultSchema, ElicitRequestSchema, McpError, ErrorCode, UrlElicitationRequiredError, ElicitationCompleteNotificationSchema } from '../../types.js'; +import { getDisplayName } from '../../shared/metadataUtils.js'; +import { exec } from 'node:child_process'; +import { InMemoryOAuthClientProvider } from './simpleOAuthClientProvider.js'; +import { UnauthorizedError } from '../../client/auth.js'; +import { createServer } from 'node:http'; +// Set up OAuth (required for this example) +const OAUTH_CALLBACK_PORT = 8090; // Use different port than auth server (3001) +const OAUTH_CALLBACK_URL = `http://localhost:${OAUTH_CALLBACK_PORT}/callback`; +let oauthProvider = undefined; +console.log('Getting OAuth token...'); +const clientMetadata = { + client_name: 'Elicitation MCP Client', + redirect_uris: [OAUTH_CALLBACK_URL], + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + token_endpoint_auth_method: 'client_secret_post', + scope: 'mcp:tools' +}; +oauthProvider = new InMemoryOAuthClientProvider(OAUTH_CALLBACK_URL, clientMetadata, (redirectUrl) => { + console.log(`🌐 Opening browser for OAuth redirect: ${redirectUrl.toString()}`); + openBrowser(redirectUrl.toString()); +}); +// Create readline interface for user input +const readline = createInterface({ + input: process.stdin, + output: process.stdout +}); +let abortCommand = new AbortController(); +// Global client and transport for interactive commands +let client = null; +let transport = null; +let serverUrl = 'http://localhost:3000/mcp'; +let sessionId = undefined; +let isProcessingCommand = false; +let isProcessingElicitations = false; +const elicitationQueue = []; +let elicitationQueueSignal = null; +let elicitationsCompleteSignal = null; +// Map to track pending URL elicitations waiting for completion notifications +const pendingURLElicitations = new Map(); +async function main() { + console.log('MCP Interactive Client'); + console.log('====================='); + // Connect to server immediately with default settings + await connect(); + // Start the elicitation loop in the background + elicitationLoop().catch(error => { + console.error('Unexpected error in elicitation loop:', error); + process.exit(1); + }); + // Short delay allowing the server to send any SSE elicitations on connection + await new Promise(resolve => setTimeout(resolve, 200)); + // Wait until we are done processing any initial elicitations + await waitForElicitationsToComplete(); + // Print help and start the command loop + printHelp(); + await commandLoop(); +} +async function waitForElicitationsToComplete() { + // Wait until the queue is empty and nothing is being processed + while (elicitationQueue.length > 0 || isProcessingElicitations) { + await new Promise(resolve => setTimeout(resolve, 100)); + } +} +function printHelp() { + console.log('\nAvailable commands:'); + console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)'); + console.log(' disconnect - Disconnect from server'); + console.log(' terminate-session - Terminate the current session'); + console.log(' reconnect - Reconnect to the server'); + console.log(' list-tools - List available tools'); + console.log(' call-tool [args] - Call a tool with optional JSON arguments'); + console.log(' payment-confirm - Test URL elicitation via error response with payment-confirm tool'); + console.log(' third-party-auth - Test tool that requires third-party OAuth credentials'); + console.log(' help - Show this help'); + console.log(' quit - Exit the program'); +} +async function commandLoop() { + await new Promise(resolve => { + if (!isProcessingElicitations) { + resolve(); + } + else { + elicitationsCompleteSignal = resolve; + } + }); + readline.question('\n> ', { signal: abortCommand.signal }, async (input) => { + var _a; + isProcessingCommand = true; + const args = input.trim().split(/\s+/); + const command = (_a = args[0]) === null || _a === void 0 ? void 0 : _a.toLowerCase(); + try { + switch (command) { + case 'connect': + await connect(args[1]); + break; + case 'disconnect': + await disconnect(); + break; + case 'terminate-session': + await terminateSession(); + break; + case 'reconnect': + await reconnect(); + break; + case 'list-tools': + await listTools(); + break; + case 'call-tool': + if (args.length < 2) { + console.log('Usage: call-tool [args]'); + } + else { + const toolName = args[1]; + let toolArgs = {}; + if (args.length > 2) { + try { + toolArgs = JSON.parse(args.slice(2).join(' ')); + } + catch (_b) { + console.log('Invalid JSON arguments. Using empty args.'); + } + } + await callTool(toolName, toolArgs); + } + break; + case 'payment-confirm': + await callPaymentConfirmTool(); + break; + case 'third-party-auth': + await callThirdPartyAuthTool(); + break; + case 'help': + printHelp(); + break; + case 'quit': + case 'exit': + await cleanup(); + return; + default: + if (command) { + console.log(`Unknown command: ${command}`); + } + break; + } + } + catch (error) { + console.error(`Error executing command: ${error}`); + } + finally { + isProcessingCommand = false; + } + // Process another command after we've processed the this one + await commandLoop(); + }); +} +async function elicitationLoop() { + while (true) { + // Wait until we have elicitations to process + await new Promise(resolve => { + if (elicitationQueue.length > 0) { + resolve(); + } + else { + elicitationQueueSignal = resolve; + } + }); + isProcessingElicitations = true; + abortCommand.abort(); // Abort the command loop if it's running + // Process all queued elicitations + while (elicitationQueue.length > 0) { + const queued = elicitationQueue.shift(); + console.log(`📤 Processing queued elicitation (${elicitationQueue.length} remaining)`); + try { + const result = await handleElicitationRequest(queued.request); + queued.resolve(result); + } + catch (error) { + queued.reject(error instanceof Error ? error : new Error(String(error))); + } + } + console.log('✅ All queued elicitations processed. Resuming command loop...\n'); + isProcessingElicitations = false; + // Reset the abort controller for the next command loop + abortCommand = new AbortController(); + // Resume the command loop + if (elicitationsCompleteSignal) { + elicitationsCompleteSignal(); + elicitationsCompleteSignal = null; + } + } +} +async function openBrowser(url) { + const command = `open "${url}"`; + exec(command, error => { + if (error) { + console.error(`Failed to open browser: ${error.message}`); + console.log(`Please manually open: ${url}`); + } + }); +} +/** + * Enqueues an elicitation request and returns the result. + * + * This function is used so that our CLI (which can only handle one input request at a time) + * can handle elicitation requests and the command loop. + * + * @param request - The elicitation request to be handled + * @returns The elicitation result + */ +async function elicitationRequestHandler(request) { + // If we are processing a command, handle this elicitation immediately + if (isProcessingCommand) { + console.log('📋 Processing elicitation immediately (during command execution)'); + return await handleElicitationRequest(request); + } + // Otherwise, queue the request to be handled by the elicitation loop + console.log(`📥 Queueing elicitation request (queue size will be: ${elicitationQueue.length + 1})`); + return new Promise((resolve, reject) => { + elicitationQueue.push({ + request, + resolve, + reject + }); + // Signal the elicitation loop that there's work to do + if (elicitationQueueSignal) { + elicitationQueueSignal(); + elicitationQueueSignal = null; + } + }); +} +/** + * Handles an elicitation request. + * + * This function is used to handle the elicitation request and return the result. + * + * @param request - The elicitation request to be handled + * @returns The elicitation result + */ +async function handleElicitationRequest(request) { + const mode = request.params.mode; + console.log('\n🔔 Elicitation Request Received:'); + console.log(`Mode: ${mode}`); + if (mode === 'url') { + return { + action: await handleURLElicitation(request.params) + }; + } + else { + // Should not happen because the client declares its capabilities to the server, + // but being defensive is a good practice: + throw new McpError(ErrorCode.InvalidParams, `Unsupported elicitation mode: ${mode}`); + } +} +/** + * Handles a URL elicitation by opening the URL in the browser. + * + * Note: This is a shared code for both request handlers and error handlers. + * As a result of sharing schema, there is no big forking of logic for the client. + * + * @param params - The URL elicitation request parameters + * @returns The action to take (accept, cancel, or decline) + */ +async function handleURLElicitation(params) { + const url = params.url; + const elicitationId = params.elicitationId; + const message = params.message; + console.log(`🆔 Elicitation ID: ${elicitationId}`); // Print for illustration + // Parse URL to show domain for security + let domain = 'unknown domain'; + try { + const parsedUrl = new URL(url); + domain = parsedUrl.hostname; + } + catch (_a) { + console.error('Invalid URL provided by server'); + return 'decline'; + } + // Example security warning to help prevent phishing attacks + console.log('\n⚠️ \x1b[33mSECURITY WARNING\x1b[0m ⚠️'); + console.log('\x1b[33mThe server is requesting you to open an external URL.\x1b[0m'); + console.log('\x1b[33mOnly proceed if you trust this server and understand why it needs this.\x1b[0m\n'); + console.log(`🌐 Target domain: \x1b[36m${domain}\x1b[0m`); + console.log(`🔗 Full URL: \x1b[36m${url}\x1b[0m`); + console.log(`\nℹ️ Server's reason:\n\n\x1b[36m${message}\x1b[0m\n`); + // 1. Ask for user consent to open the URL + const consent = await new Promise(resolve => { + readline.question('\nDo you want to open this URL in your browser? (y/n): ', input => { + resolve(input.trim().toLowerCase()); + }); + }); + // 2. If user did not consent, return appropriate result + if (consent === 'no' || consent === 'n') { + console.log('❌ URL navigation declined.'); + return 'decline'; + } + else if (consent !== 'yes' && consent !== 'y') { + console.log('🚫 Invalid response. Cancelling elicitation.'); + return 'cancel'; + } + // 3. Wait for completion notification in the background + const completionPromise = new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + pendingURLElicitations.delete(elicitationId); + console.log(`\x1b[31m❌ Elicitation ${elicitationId} timed out waiting for completion.\x1b[0m`); + reject(new Error('Elicitation completion timeout')); + }, 5 * 60 * 1000); // 5 minute timeout + pendingURLElicitations.set(elicitationId, { + resolve: () => { + clearTimeout(timeout); + resolve(); + }, + reject, + timeout + }); + }); + completionPromise.catch(error => { + console.error('Background completion wait failed:', error); + }); + // 4. Open the URL in the browser + console.log(`\n🚀 Opening browser to: ${url}`); + await openBrowser(url); + console.log('\n⏳ Waiting for you to complete the interaction in your browser...'); + console.log(' The server will send a notification once you complete the action.'); + // 5. Acknowledge the user accepted the elicitation + return 'accept'; +} +/** + * Example OAuth callback handler - in production, use a more robust approach + * for handling callbacks and storing tokens + */ +/** + * Starts a temporary HTTP server to receive the OAuth callback + */ +async function waitForOAuthCallback() { + return new Promise((resolve, reject) => { + const server = createServer((req, res) => { + // Ignore favicon requests + if (req.url === '/favicon.ico') { + res.writeHead(404); + res.end(); + return; + } + console.log(`📥 Received callback: ${req.url}`); + const parsedUrl = new URL(req.url || '', 'http://localhost'); + const code = parsedUrl.searchParams.get('code'); + const error = parsedUrl.searchParams.get('error'); + if (code) { + console.log(`✅ Authorization code received: ${code === null || code === void 0 ? void 0 : code.substring(0, 10)}...`); + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Successful!

+

This simulates successful authorization of the MCP client, which now has an access token for the MCP server.

+

This window will close automatically in 10 seconds.

+ + + + `); + resolve(code); + setTimeout(() => server.close(), 15000); + } + else if (error) { + console.log(`❌ Authorization error: ${error}`); + res.writeHead(400, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Failed

+

Error: ${error}

+ + + `); + reject(new Error(`OAuth authorization failed: ${error}`)); + } + else { + console.log(`❌ No authorization code or error in callback`); + res.writeHead(400); + res.end('Bad request'); + reject(new Error('No authorization code provided')); + } + }); + server.listen(OAUTH_CALLBACK_PORT, () => { + console.log(`OAuth callback server started on http://localhost:${OAUTH_CALLBACK_PORT}`); + }); + }); +} +/** + * Attempts to connect to the MCP server with OAuth authentication. + * Handles OAuth flow recursively if authorization is required. + */ +async function attemptConnection(oauthProvider) { + console.log('🚢 Creating transport with OAuth provider...'); + const baseUrl = new URL(serverUrl); + transport = new StreamableHTTPClientTransport(baseUrl, { + sessionId: sessionId, + authProvider: oauthProvider + }); + console.log('🚢 Transport created'); + try { + console.log('🔌 Attempting connection (this will trigger OAuth redirect if needed)...'); + await client.connect(transport); + sessionId = transport.sessionId; + console.log('Transport created with session ID:', sessionId); + console.log('✅ Connected successfully'); + } + catch (error) { + if (error instanceof UnauthorizedError) { + console.log('🔐 OAuth required - waiting for authorization...'); + const callbackPromise = waitForOAuthCallback(); + const authCode = await callbackPromise; + await transport.finishAuth(authCode); + console.log('🔐 Authorization code received:', authCode); + console.log('🔌 Reconnecting with authenticated transport...'); + // Recursively retry connection after OAuth completion + await attemptConnection(oauthProvider); + } + else { + console.error('❌ Connection failed with non-auth error:', error); + throw error; + } + } +} +async function connect(url) { + if (client) { + console.log('Already connected. Disconnect first.'); + return; + } + if (url) { + serverUrl = url; + } + console.log(`🔗 Attempting to connect to ${serverUrl}...`); + // Create a new client with elicitation capability + console.log('👤 Creating MCP client...'); + client = new Client({ + name: 'example-client', + version: '1.0.0' + }, { + capabilities: { + elicitation: { + // Only URL elicitation is supported in this demo + // (see server/elicitationExample.ts for a demo of form mode elicitation) + url: {} + } + } + }); + console.log('👤 Client created'); + // Set up elicitation request handler with proper validation + client.setRequestHandler(ElicitRequestSchema, elicitationRequestHandler); + // Set up notification handler for elicitation completion + client.setNotificationHandler(ElicitationCompleteNotificationSchema, notification => { + const { elicitationId } = notification.params; + const pending = pendingURLElicitations.get(elicitationId); + if (pending) { + clearTimeout(pending.timeout); + pendingURLElicitations.delete(elicitationId); + console.log(`\x1b[32m✅ Elicitation ${elicitationId} completed!\x1b[0m`); + pending.resolve(); + } + else { + // Shouldn't happen - discard it! + console.warn(`Received completion notification for unknown elicitation: ${elicitationId}`); + } + }); + try { + console.log('🔐 Starting OAuth flow...'); + await attemptConnection(oauthProvider); + console.log('Connected to MCP server'); + // Set up error handler after connection is established so we don't double log errors + client.onerror = error => { + console.error('\x1b[31mClient error:', error, '\x1b[0m'); + }; + } + catch (error) { + console.error('Failed to connect:', error); + client = null; + transport = null; + return; + } +} +async function disconnect() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + await transport.close(); + console.log('Disconnected from MCP server'); + client = null; + transport = null; + } + catch (error) { + console.error('Error disconnecting:', error); + } +} +async function terminateSession() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + console.log('Terminating session with ID:', transport.sessionId); + await transport.terminateSession(); + console.log('Session terminated successfully'); + // Check if sessionId was cleared after termination + if (!transport.sessionId) { + console.log('Session ID has been cleared'); + sessionId = undefined; + // Also close the transport and clear client objects + await transport.close(); + console.log('Transport closed after session termination'); + client = null; + transport = null; + } + else { + console.log('Server responded with 405 Method Not Allowed (session termination not supported)'); + console.log('Session ID is still active:', transport.sessionId); + } + } + catch (error) { + console.error('Error terminating session:', error); + } +} +async function reconnect() { + if (client) { + await disconnect(); + } + await connect(); +} +async function listTools() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - id: ${tool.name}, name: ${getDisplayName(tool)}, description: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server (${error})`); + } +} +async function callTool(name, args) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const request = { + method: 'tools/call', + params: { + name, + arguments: args + } + }; + console.log(`Calling tool '${name}' with args:`, args); + const result = await client.request(request, CallToolResultSchema); + console.log('Tool result:'); + const resourceLinks = []; + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else if (item.type === 'resource_link') { + const resourceLink = item; + resourceLinks.push(resourceLink); + console.log(` 📁 Resource Link: ${resourceLink.name}`); + console.log(` URI: ${resourceLink.uri}`); + if (resourceLink.mimeType) { + console.log(` Type: ${resourceLink.mimeType}`); + } + if (resourceLink.description) { + console.log(` Description: ${resourceLink.description}`); + } + } + else if (item.type === 'resource') { + console.log(` [Embedded Resource: ${item.resource.uri}]`); + } + else if (item.type === 'image') { + console.log(` [Image: ${item.mimeType}]`); + } + else if (item.type === 'audio') { + console.log(` [Audio: ${item.mimeType}]`); + } + else { + console.log(` [Unknown content type]:`, item); + } + }); + // Offer to read resource links + if (resourceLinks.length > 0) { + console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource ' to read their content.`); + } + } + catch (error) { + if (error instanceof UrlElicitationRequiredError) { + console.log('\n🔔 Elicitation Required Error Received:'); + console.log(`Message: ${error.message}`); + for (const e of error.elicitations) { + await handleURLElicitation(e); // For the error handler, we discard the action result because we don't respond to an error response + } + return; + } + console.log(`Error calling tool ${name}: ${error}`); + } +} +async function cleanup() { + if (client && transport) { + try { + // First try to terminate the session gracefully + if (transport.sessionId) { + try { + console.log('Terminating session before exit...'); + await transport.terminateSession(); + console.log('Session terminated successfully'); + } + catch (error) { + console.error('Error terminating session:', error); + } + } + // Then close the transport + await transport.close(); + } + catch (error) { + console.error('Error closing transport:', error); + } + } + process.stdin.setRawMode(false); + readline.close(); + console.log('\nGoodbye!'); + process.exit(0); +} +async function callPaymentConfirmTool() { + console.log('Calling payment-confirm tool...'); + await callTool('payment-confirm', { cartId: 'cart_123' }); +} +async function callThirdPartyAuthTool() { + console.log('Calling third-party-auth tool...'); + await callTool('third-party-auth', { param1: 'test' }); +} +// Set up raw mode for keyboard input to capture Escape key +process.stdin.setRawMode(true); +process.stdin.on('data', async (data) => { + // Check for Escape key (27) + if (data.length === 1 && data[0] === 27) { + console.log('\nESC key pressed. Disconnecting from server...'); + // Abort current operation and disconnect from server + if (client && transport) { + await disconnect(); + console.log('Disconnected. Press Enter to continue.'); + } + else { + console.log('Not connected to server.'); + } + // Re-display the prompt + process.stdout.write('> '); + } +}); +// Handle Ctrl+C +process.on('SIGINT', async () => { + console.log('\nReceived SIGINT. Cleaning up...'); + await cleanup(); +}); +// Start the interactive client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=elicitationUrlExample.js.map \ No newline at end of file diff --git a/dist/esm/examples/client/elicitationUrlExample.js.map b/dist/esm/examples/client/elicitationUrlExample.js.map new file mode 100644 index 0000000000..4b59163929 --- /dev/null +++ b/dist/esm/examples/client/elicitationUrlExample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.js","sourceRoot":"","sources":["../../../../src/examples/client/elicitationUrlExample.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,EAAE;AACF,mEAAmE;AACnE,gDAAgD;AAChD,uFAAuF;AACvF,oCAAoC;AAEpC,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAEH,qBAAqB,EAErB,oBAAoB,EACpB,mBAAmB,EAKnB,QAAQ,EACR,SAAS,EACT,2BAA2B,EAC3B,qCAAqC,EACxC,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAE/D,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,2BAA2B,EAAE,MAAM,gCAAgC,CAAC;AAC7E,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,2CAA2C;AAC3C,MAAM,mBAAmB,GAAG,IAAI,CAAC,CAAC,6CAA6C;AAC/E,MAAM,kBAAkB,GAAG,oBAAoB,mBAAmB,WAAW,CAAC;AAC9E,IAAI,aAAa,GAA4C,SAAS,CAAC;AAEvE,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;AACtC,MAAM,cAAc,GAAwB;IACxC,WAAW,EAAE,wBAAwB;IACrC,aAAa,EAAE,CAAC,kBAAkB,CAA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C;AAED,2DAA2D;AAC3D,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAC/B,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,EAAC,IAAI,EAAC,EAAE;IAClC,4BAA4B;IAC5B,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;QACtC,OAAO,CAAC,GAAG,CAAC,iDAAiD,CAAC,CAAC;QAE/D,qDAAqD;QACrD,IAAI,MAAM,IAAI,SAAS,EAAE,CAAC;YACtB,MAAM,UAAU,EAAE,CAAC;YACnB,OAAO,CAAC,GAAG,CAAC,wCAAwC,CAAC,CAAC;QAC1D,CAAC;aAAM,CAAC;YACJ,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;QAC5C,CAAC;QAED,wBAAwB;QACxB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,gBAAgB;AAChB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;IACjD,MAAM,OAAO,EAAE,CAAC;AACpB,CAAC,CAAC,CAAC;AAEH,+BAA+B;AAC/B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/client/multipleClientsParallel.d.ts b/dist/esm/examples/client/multipleClientsParallel.d.ts new file mode 100644 index 0000000000..0ac5af8e56 --- /dev/null +++ b/dist/esm/examples/client/multipleClientsParallel.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=multipleClientsParallel.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/client/multipleClientsParallel.d.ts.map b/dist/esm/examples/client/multipleClientsParallel.d.ts.map new file mode 100644 index 0000000000..91051dc946 --- /dev/null +++ b/dist/esm/examples/client/multipleClientsParallel.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"multipleClientsParallel.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/multipleClientsParallel.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/client/multipleClientsParallel.js b/dist/esm/examples/client/multipleClientsParallel.js new file mode 100644 index 0000000000..4264856735 --- /dev/null +++ b/dist/esm/examples/client/multipleClientsParallel.js @@ -0,0 +1,132 @@ +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { CallToolResultSchema, LoggingMessageNotificationSchema } from '../../types.js'; +/** + * Multiple Clients MCP Example + * + * This client demonstrates how to: + * 1. Create multiple MCP clients in parallel + * 2. Each client calls a single tool + * 3. Track notifications from each client independently + */ +// Command line args processing +const args = process.argv.slice(2); +const serverUrl = args[0] || 'http://localhost:3000/mcp'; +async function createAndRunClient(config) { + console.log(`[${config.id}] Creating client: ${config.name}`); + const client = new Client({ + name: config.name, + version: '1.0.0' + }); + const transport = new StreamableHTTPClientTransport(new URL(serverUrl)); + // Set up client-specific error handler + client.onerror = error => { + console.error(`[${config.id}] Client error:`, error); + }; + // Set up client-specific notification handler + client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { + console.log(`[${config.id}] Notification: ${notification.params.data}`); + }); + try { + // Connect to the server + await client.connect(transport); + console.log(`[${config.id}] Connected to MCP server`); + // Call the specified tool + console.log(`[${config.id}] Calling tool: ${config.toolName}`); + const toolRequest = { + method: 'tools/call', + params: { + name: config.toolName, + arguments: { + ...config.toolArguments, + // Add client ID to arguments for identification in notifications + caller: config.id + } + } + }; + const result = await client.request(toolRequest, CallToolResultSchema); + console.log(`[${config.id}] Tool call completed`); + // Keep the connection open for a bit to receive notifications + await new Promise(resolve => setTimeout(resolve, 5000)); + // Disconnect + await transport.close(); + console.log(`[${config.id}] Disconnected from MCP server`); + return { id: config.id, result }; + } + catch (error) { + console.error(`[${config.id}] Error:`, error); + throw error; + } +} +async function main() { + console.log('MCP Multiple Clients Example'); + console.log('============================'); + console.log(`Server URL: ${serverUrl}`); + console.log(''); + try { + // Define client configurations + const clientConfigs = [ + { + id: 'client1', + name: 'basic-client-1', + toolName: 'start-notification-stream', + toolArguments: { + interval: 3, // 1 second between notifications + count: 5 // Send 5 notifications + } + }, + { + id: 'client2', + name: 'basic-client-2', + toolName: 'start-notification-stream', + toolArguments: { + interval: 2, // 2 seconds between notifications + count: 3 // Send 3 notifications + } + }, + { + id: 'client3', + name: 'basic-client-3', + toolName: 'start-notification-stream', + toolArguments: { + interval: 1, // 0.5 second between notifications + count: 8 // Send 8 notifications + } + } + ]; + // Start all clients in parallel + console.log(`Starting ${clientConfigs.length} clients in parallel...`); + console.log(''); + const clientPromises = clientConfigs.map(config => createAndRunClient(config)); + const results = await Promise.all(clientPromises); + // Display results from all clients + console.log('\n=== Final Results ==='); + results.forEach(({ id, result }) => { + console.log(`\n[${id}] Tool result:`); + if (Array.isArray(result.content)) { + result.content.forEach((item) => { + if (item.type === 'text' && item.text) { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + else { + console.log(` Unexpected result format:`, result); + } + }); + console.log('\n=== All clients completed successfully ==='); + } + catch (error) { + console.error('Error running multiple clients:', error); + process.exit(1); + } +} +// Start the example +main().catch((error) => { + console.error('Error running MCP multiple clients example:', error); + process.exit(1); +}); +//# sourceMappingURL=multipleClientsParallel.js.map \ No newline at end of file diff --git a/dist/esm/examples/client/multipleClientsParallel.js.map b/dist/esm/examples/client/multipleClientsParallel.js.map new file mode 100644 index 0000000000..d02ce22805 --- /dev/null +++ b/dist/esm/examples/client/multipleClientsParallel.js.map @@ -0,0 +1 @@ +{"version":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;YAC/B,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;YACtC,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC;gBAChC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,IAAqC,EAAE,EAAE;oBAC7D,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;wBACpC,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;oBAClC,CAAC;yBAAM,CAAC;wBACJ,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,WAAW,EAAE,IAAI,CAAC,CAAC;oBACjD,CAAC;gBACL,CAAC,CAAC,CAAC;YACP,CAAC;iBAAM,CAAC;gBACJ,OAAO,CAAC,GAAG,CAAC,6BAA6B,EAAE,MAAM,CAAC,CAAC;YACvD,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,GAAG,CAAC,8CAA8C,CAAC,CAAC;IAChE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;QACxD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;AACL,CAAC;AAED,oBAAoB;AACpB,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,6CAA6C,EAAE,KAAK,CAAC,CAAC;IACpE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/client/parallelToolCallsClient.d.ts b/dist/esm/examples/client/parallelToolCallsClient.d.ts new file mode 100644 index 0000000000..e93d4d69d2 --- /dev/null +++ b/dist/esm/examples/client/parallelToolCallsClient.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=parallelToolCallsClient.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/client/parallelToolCallsClient.d.ts.map b/dist/esm/examples/client/parallelToolCallsClient.d.ts.map new file mode 100644 index 0000000000..25a3b820cf --- /dev/null +++ b/dist/esm/examples/client/parallelToolCallsClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"parallelToolCallsClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/parallelToolCallsClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/client/parallelToolCallsClient.js b/dist/esm/examples/client/parallelToolCallsClient.js new file mode 100644 index 0000000000..9d2a2e9153 --- /dev/null +++ b/dist/esm/examples/client/parallelToolCallsClient.js @@ -0,0 +1,174 @@ +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { ListToolsResultSchema, CallToolResultSchema, LoggingMessageNotificationSchema } from '../../types.js'; +/** + * Parallel Tool Calls MCP Client + * + * This client demonstrates how to: + * 1. Start multiple tool calls in parallel + * 2. Track notifications from each tool call using a caller parameter + */ +// Command line args processing +const args = process.argv.slice(2); +const serverUrl = args[0] || 'http://localhost:3000/mcp'; +async function main() { + console.log('MCP Parallel Tool Calls Client'); + console.log('=============================='); + console.log(`Connecting to server at: ${serverUrl}`); + let client; + let transport; + try { + // Create client with streamable HTTP transport + client = new Client({ + name: 'parallel-tool-calls-client', + version: '1.0.0' + }); + client.onerror = error => { + console.error('Client error:', error); + }; + // Connect to the server + transport = new StreamableHTTPClientTransport(new URL(serverUrl)); + await client.connect(transport); + console.log('Successfully connected to MCP server'); + // Set up notification handler with caller identification + client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { + console.log(`Notification: ${notification.params.data}`); + }); + console.log('List tools'); + const toolsRequest = await listTools(client); + console.log('Tools: ', toolsRequest); + // 2. Start multiple notification tools in parallel + console.log('\n=== Starting Multiple Notification Streams in Parallel ==='); + const toolResults = await startParallelNotificationTools(client); + // Log the results from each tool call + for (const [caller, result] of Object.entries(toolResults)) { + console.log(`\n=== Tool result for ${caller} ===`); + result.content.forEach((item) => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + // 3. Wait for all notifications (10 seconds) + console.log('\n=== Waiting for all notifications ==='); + await new Promise(resolve => setTimeout(resolve, 10000)); + // 4. Disconnect + console.log('\n=== Disconnecting ==='); + await transport.close(); + console.log('Disconnected from MCP server'); + } + catch (error) { + console.error('Error running client:', error); + process.exit(1); + } +} +/** + * List available tools on the server + */ +async function listTools(client) { + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - ${tool.name}: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server: ${error}`); + } +} +/** + * Start multiple notification tools in parallel with different configurations + * Each tool call includes a caller parameter to identify its notifications + */ +async function startParallelNotificationTools(client) { + try { + // Define multiple tool calls with different configurations + const toolCalls = [ + { + caller: 'fast-notifier', + request: { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 2, // 0.5 second between notifications + count: 10, // Send 10 notifications + caller: 'fast-notifier' // Identify this tool call + } + } + } + }, + { + caller: 'slow-notifier', + request: { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 5, // 2 seconds between notifications + count: 5, // Send 5 notifications + caller: 'slow-notifier' // Identify this tool call + } + } + } + }, + { + caller: 'burst-notifier', + request: { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 1, // 0.1 second between notifications + count: 3, // Send just 3 notifications + caller: 'burst-notifier' // Identify this tool call + } + } + } + } + ]; + console.log(`Starting ${toolCalls.length} notification tools in parallel...`); + // Start all tool calls in parallel + const toolPromises = toolCalls.map(({ caller, request }) => { + console.log(`Starting tool call for ${caller}...`); + return client + .request(request, CallToolResultSchema) + .then(result => ({ caller, result })) + .catch(error => { + console.error(`Error in tool call for ${caller}:`, error); + throw error; + }); + }); + // Wait for all tool calls to complete + const results = await Promise.all(toolPromises); + // Organize results by caller + const resultsByTool = {}; + results.forEach(({ caller, result }) => { + resultsByTool[caller] = result; + }); + return resultsByTool; + } + catch (error) { + console.error(`Error starting parallel notification tools:`, error); + throw error; + } +} +// Start the client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=parallelToolCallsClient.js.map \ No newline at end of file diff --git a/dist/esm/examples/client/parallelToolCallsClient.js.map b/dist/esm/examples/client/parallelToolCallsClient.js.map new file mode 100644 index 0000000000..0a044818ef --- /dev/null +++ b/dist/esm/examples/client/parallelToolCallsClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parallelToolCallsClient.js","sourceRoot":"","sources":["../../../../src/examples/client/parallelToolCallsClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAEH,qBAAqB,EACrB,oBAAoB,EACpB,gCAAgC,EAEnC,MAAM,gBAAgB,CAAC;AAExB;;;;;;GAMG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AAEzD,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,4BAA4B,SAAS,EAAE,CAAC,CAAC;IAErD,IAAI,MAAc,CAAC;IACnB,IAAI,SAAwC,CAAC;IAE7C,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,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClient.d.ts b/dist/esm/examples/client/simpleOAuthClient.d.ts new file mode 100644 index 0000000000..e4b43dbc01 --- /dev/null +++ b/dist/esm/examples/client/simpleOAuthClient.d.ts @@ -0,0 +1,3 @@ +#!/usr/bin/env node +export {}; +//# sourceMappingURL=simpleOAuthClient.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClient.d.ts.map b/dist/esm/examples/client/simpleOAuthClient.d.ts.map new file mode 100644 index 0000000000..c09eef86ea --- /dev/null +++ b/dist/esm/examples/client/simpleOAuthClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClient.js b/dist/esm/examples/client/simpleOAuthClient.js new file mode 100644 index 0000000000..4ad45fda2d --- /dev/null +++ b/dist/esm/examples/client/simpleOAuthClient.js @@ -0,0 +1,335 @@ +#!/usr/bin/env node +import { createServer } from 'node:http'; +import { createInterface } from 'node:readline'; +import { URL } from 'node:url'; +import { exec } from 'node:child_process'; +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { CallToolResultSchema, ListToolsResultSchema } from '../../types.js'; +import { UnauthorizedError } from '../../client/auth.js'; +import { InMemoryOAuthClientProvider } from './simpleOAuthClientProvider.js'; +// Configuration +const DEFAULT_SERVER_URL = 'http://localhost:3000/mcp'; +const CALLBACK_PORT = 8090; // Use different port than auth server (3001) +const CALLBACK_URL = `http://localhost:${CALLBACK_PORT}/callback`; +/** + * Interactive MCP client with OAuth authentication + * Demonstrates the complete OAuth flow with browser-based authorization + */ +class InteractiveOAuthClient { + constructor(serverUrl, clientMetadataUrl) { + this.serverUrl = serverUrl; + this.clientMetadataUrl = clientMetadataUrl; + this.client = null; + this.rl = createInterface({ + input: process.stdin, + output: process.stdout + }); + } + /** + * Prompts user for input via readline + */ + async question(query) { + return new Promise(resolve => { + this.rl.question(query, resolve); + }); + } + /** + * Opens the authorization URL in the user's default browser + */ + async openBrowser(url) { + console.log(`🌐 Opening browser for authorization: ${url}`); + const command = `open "${url}"`; + exec(command, error => { + if (error) { + console.error(`Failed to open browser: ${error.message}`); + console.log(`Please manually open: ${url}`); + } + }); + } + /** + * Example OAuth callback handler - in production, use a more robust approach + * for handling callbacks and storing tokens + */ + /** + * Starts a temporary HTTP server to receive the OAuth callback + */ + async waitForOAuthCallback() { + return new Promise((resolve, reject) => { + const server = createServer((req, res) => { + // Ignore favicon requests + if (req.url === '/favicon.ico') { + res.writeHead(404); + res.end(); + return; + } + console.log(`📥 Received callback: ${req.url}`); + const parsedUrl = new URL(req.url || '', 'http://localhost'); + const code = parsedUrl.searchParams.get('code'); + const error = parsedUrl.searchParams.get('error'); + if (code) { + console.log(`✅ Authorization code received: ${code === null || code === void 0 ? void 0 : code.substring(0, 10)}...`); + res.writeHead(200, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Successful!

+

You can close this window and return to the terminal.

+ + + + `); + resolve(code); + setTimeout(() => server.close(), 3000); + } + else if (error) { + console.log(`❌ Authorization error: ${error}`); + res.writeHead(400, { 'Content-Type': 'text/html' }); + res.end(` + + +

Authorization Failed

+

Error: ${error}

+ + + `); + reject(new Error(`OAuth authorization failed: ${error}`)); + } + else { + console.log(`❌ No authorization code or error in callback`); + res.writeHead(400); + res.end('Bad request'); + reject(new Error('No authorization code provided')); + } + }); + server.listen(CALLBACK_PORT, () => { + console.log(`OAuth callback server started on http://localhost:${CALLBACK_PORT}`); + }); + }); + } + async attemptConnection(oauthProvider) { + console.log('🚢 Creating transport with OAuth provider...'); + const baseUrl = new URL(this.serverUrl); + const transport = new StreamableHTTPClientTransport(baseUrl, { + authProvider: oauthProvider + }); + console.log('🚢 Transport created'); + try { + console.log('🔌 Attempting connection (this will trigger OAuth redirect)...'); + await this.client.connect(transport); + console.log('✅ Connected successfully'); + } + catch (error) { + if (error instanceof UnauthorizedError) { + console.log('🔐 OAuth required - waiting for authorization...'); + const callbackPromise = this.waitForOAuthCallback(); + const authCode = await callbackPromise; + await transport.finishAuth(authCode); + console.log('🔐 Authorization code received:', authCode); + console.log('🔌 Reconnecting with authenticated transport...'); + await this.attemptConnection(oauthProvider); + } + else { + console.error('❌ Connection failed with non-auth error:', error); + throw error; + } + } + } + /** + * Establishes connection to the MCP server with OAuth authentication + */ + async connect() { + console.log(`🔗 Attempting to connect to ${this.serverUrl}...`); + const clientMetadata = { + client_name: 'Simple OAuth MCP Client', + redirect_uris: [CALLBACK_URL], + grant_types: ['authorization_code', 'refresh_token'], + response_types: ['code'], + token_endpoint_auth_method: 'client_secret_post' + }; + console.log('🔐 Creating OAuth provider...'); + const oauthProvider = new InMemoryOAuthClientProvider(CALLBACK_URL, clientMetadata, (redirectUrl) => { + console.log(`📌 OAuth redirect handler called - opening browser`); + console.log(`Opening browser to: ${redirectUrl.toString()}`); + this.openBrowser(redirectUrl.toString()); + }, this.clientMetadataUrl); + console.log('🔐 OAuth provider created'); + console.log('👤 Creating MCP client...'); + this.client = new Client({ + name: 'simple-oauth-client', + version: '1.0.0' + }, { capabilities: {} }); + console.log('👤 Client created'); + console.log('🔐 Starting OAuth flow...'); + await this.attemptConnection(oauthProvider); + // Start interactive loop + await this.interactiveLoop(); + } + /** + * Main interactive loop for user commands + */ + async interactiveLoop() { + console.log('\n🎯 Interactive MCP Client with OAuth'); + console.log('Commands:'); + console.log(' list - List available tools'); + console.log(' call [args] - Call a tool'); + console.log(' quit - Exit the client'); + console.log(); + while (true) { + try { + const command = await this.question('mcp> '); + if (!command.trim()) { + continue; + } + if (command === 'quit') { + console.log('\n👋 Goodbye!'); + this.close(); + process.exit(0); + } + else if (command === 'list') { + await this.listTools(); + } + else if (command.startsWith('call ')) { + await this.handleCallTool(command); + } + else { + console.log("❌ Unknown command. Try 'list', 'call ', or 'quit'"); + } + } + catch (error) { + if (error instanceof Error && error.message === 'SIGINT') { + console.log('\n\n👋 Goodbye!'); + break; + } + console.error('❌ Error:', error); + } + } + } + async listTools() { + if (!this.client) { + console.log('❌ Not connected to server'); + return; + } + try { + const request = { + method: 'tools/list', + params: {} + }; + const result = await this.client.request(request, ListToolsResultSchema); + if (result.tools && result.tools.length > 0) { + console.log('\n📋 Available tools:'); + result.tools.forEach((tool, index) => { + console.log(`${index + 1}. ${tool.name}`); + if (tool.description) { + console.log(` Description: ${tool.description}`); + } + console.log(); + }); + } + else { + console.log('No tools available'); + } + } + catch (error) { + console.error('❌ Failed to list tools:', error); + } + } + async handleCallTool(command) { + const parts = command.split(/\s+/); + const toolName = parts[1]; + if (!toolName) { + console.log('❌ Please specify a tool name'); + return; + } + // Parse arguments (simple JSON-like format) + let toolArgs = {}; + if (parts.length > 2) { + const argsString = parts.slice(2).join(' '); + try { + toolArgs = JSON.parse(argsString); + } + catch (_a) { + console.log('❌ Invalid arguments format (expected JSON)'); + return; + } + } + await this.callTool(toolName, toolArgs); + } + async callTool(toolName, toolArgs) { + if (!this.client) { + console.log('❌ Not connected to server'); + return; + } + try { + const request = { + method: 'tools/call', + params: { + name: toolName, + arguments: toolArgs + } + }; + const result = await this.client.request(request, CallToolResultSchema); + console.log(`\n🔧 Tool '${toolName}' result:`); + if (result.content) { + result.content.forEach(content => { + if (content.type === 'text') { + console.log(content.text); + } + else { + console.log(content); + } + }); + } + else { + console.log(result); + } + } + catch (error) { + console.error(`❌ Failed to call tool '${toolName}':`, error); + } + } + close() { + this.rl.close(); + if (this.client) { + // Note: Client doesn't have a close method in the current implementation + // This would typically close the transport connection + } + } +} +/** + * Main entry point + */ +async function main() { + const args = process.argv.slice(2); + const serverUrl = args[0] || DEFAULT_SERVER_URL; + const clientMetadataUrl = args[1]; + console.log('🚀 Simple MCP OAuth Client'); + console.log(`Connecting to: ${serverUrl}`); + if (clientMetadataUrl) { + console.log(`Client Metadata URL: ${clientMetadataUrl}`); + } + console.log(); + const client = new InteractiveOAuthClient(serverUrl, clientMetadataUrl); + // Handle graceful shutdown + process.on('SIGINT', () => { + console.log('\n\n👋 Goodbye!'); + client.close(); + process.exit(0); + }); + try { + await client.connect(); + } + catch (error) { + console.error('Failed to start client:', error); + process.exit(1); + } + finally { + client.close(); + } +} +// Run if this file is executed directly +main().catch(error => { + console.error('Unhandled error:', error); + process.exit(1); +}); +//# sourceMappingURL=simpleOAuthClient.js.map \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClient.js.map b/dist/esm/examples/client/simpleOAuthClient.js.map new file mode 100644 index 0000000000..9cfa58aacf --- /dev/null +++ b/dist/esm/examples/client/simpleOAuthClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClient.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClient.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAC;AAC/B,OAAO,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAC1C,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAE/E,OAAO,EAAqC,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAChH,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,2BAA2B,EAAE,MAAM,gCAAgC,CAAC;AAE7E,gBAAgB;AAChB,MAAM,kBAAkB,GAAG,2BAA2B,CAAC;AACvD,MAAM,aAAa,GAAG,IAAI,CAAC,CAAC,6CAA6C;AACzE,MAAM,YAAY,GAAG,oBAAoB,aAAa,WAAW,CAAC;AAElE;;;GAGG;AACH,MAAM,sBAAsB;IAOxB,Y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;IAC3C,IAAI,iBAAiB,EAAE,CAAC;QACpB,OAAO,CAAC,GAAG,CAAC,wBAAwB,iBAAiB,EAAE,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,CAAC,GAAG,EAAE,CAAC;IAEd,MAAM,MAAM,GAAG,IAAI,sBAAsB,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC;IAExE,2BAA2B;IAC3B,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;QACtB,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC;QACD,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;YAAS,CAAC;QACP,MAAM,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;AACL,CAAC;AAED,wCAAwC;AACxC,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;IACzC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClientProvider.d.ts b/dist/esm/examples/client/simpleOAuthClientProvider.d.ts new file mode 100644 index 0000000000..092616cf5c --- /dev/null +++ b/dist/esm/examples/client/simpleOAuthClientProvider.d.ts @@ -0,0 +1,26 @@ +import { OAuthClientProvider } from '../../client/auth.js'; +import { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from '../../shared/auth.js'; +/** + * In-memory OAuth client provider for demonstration purposes + * In production, you should persist tokens securely + */ +export declare class InMemoryOAuthClientProvider implements OAuthClientProvider { + private readonly _redirectUrl; + private readonly _clientMetadata; + readonly clientMetadataUrl?: string | undefined; + private _clientInformation?; + private _tokens?; + private _codeVerifier?; + constructor(_redirectUrl: string | URL, _clientMetadata: OAuthClientMetadata, onRedirect?: (url: URL) => void, clientMetadataUrl?: string | undefined); + private _onRedirect; + get redirectUrl(): string | URL; + get clientMetadata(): OAuthClientMetadata; + clientInformation(): OAuthClientInformationMixed | undefined; + saveClientInformation(clientInformation: OAuthClientInformationMixed): void; + tokens(): OAuthTokens | undefined; + saveTokens(tokens: OAuthTokens): void; + redirectToAuthorization(authorizationUrl: URL): void; + saveCodeVerifier(codeVerifier: string): void; + codeVerifier(): string; +} +//# sourceMappingURL=simpleOAuthClientProvider.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClientProvider.d.ts.map b/dist/esm/examples/client/simpleOAuthClientProvider.d.ts.map new file mode 100644 index 0000000000..21efe9444a --- /dev/null +++ b/dist/esm/examples/client/simpleOAuthClientProvider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClientProvider.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClientProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,2BAA2B,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAErG;;;GAGG;AACH,qBAAa,2BAA4B,YAAW,mBAAmB;IAM/D,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,eAAe;aAEhB,iBAAiB,CAAC,EAAE,MAAM;IAR9C,OAAO,CAAC,kBAAkB,CAAC,CAA8B;IACzD,OAAO,CAAC,OAAO,CAAC,CAAc;IAC9B,OAAO,CAAC,aAAa,CAAC,CAAS;gBAGV,YAAY,EAAE,MAAM,GAAG,GAAG,EAC1B,eAAe,EAAE,mBAAmB,EACrD,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,EACf,iBAAiB,CAAC,EAAE,MAAM,YAAA;IAS9C,OAAO,CAAC,WAAW,CAAqB;IAExC,IAAI,WAAW,IAAI,MAAM,GAAG,GAAG,CAE9B;IAED,IAAI,cAAc,IAAI,mBAAmB,CAExC;IAED,iBAAiB,IAAI,2BAA2B,GAAG,SAAS;IAI5D,qBAAqB,CAAC,iBAAiB,EAAE,2BAA2B,GAAG,IAAI;IAI3E,MAAM,IAAI,WAAW,GAAG,SAAS;IAIjC,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI;IAIrC,uBAAuB,CAAC,gBAAgB,EAAE,GAAG,GAAG,IAAI;IAIpD,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI;IAI5C,YAAY,IAAI,MAAM;CAMzB"} \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClientProvider.js b/dist/esm/examples/client/simpleOAuthClientProvider.js new file mode 100644 index 0000000000..7c350d1313 --- /dev/null +++ b/dist/esm/examples/client/simpleOAuthClientProvider.js @@ -0,0 +1,47 @@ +/** + * In-memory OAuth client provider for demonstration purposes + * In production, you should persist tokens securely + */ +export class InMemoryOAuthClientProvider { + constructor(_redirectUrl, _clientMetadata, onRedirect, clientMetadataUrl) { + this._redirectUrl = _redirectUrl; + this._clientMetadata = _clientMetadata; + this.clientMetadataUrl = clientMetadataUrl; + this._onRedirect = + onRedirect || + (url => { + console.log(`Redirect to: ${url.toString()}`); + }); + } + get redirectUrl() { + return this._redirectUrl; + } + get clientMetadata() { + return this._clientMetadata; + } + clientInformation() { + return this._clientInformation; + } + saveClientInformation(clientInformation) { + this._clientInformation = clientInformation; + } + tokens() { + return this._tokens; + } + saveTokens(tokens) { + this._tokens = tokens; + } + redirectToAuthorization(authorizationUrl) { + this._onRedirect(authorizationUrl); + } + saveCodeVerifier(codeVerifier) { + this._codeVerifier = codeVerifier; + } + codeVerifier() { + if (!this._codeVerifier) { + throw new Error('No code verifier saved'); + } + return this._codeVerifier; + } +} +//# sourceMappingURL=simpleOAuthClientProvider.js.map \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClientProvider.js.map b/dist/esm/examples/client/simpleOAuthClientProvider.js.map new file mode 100644 index 0000000000..88f15cde57 --- /dev/null +++ b/dist/esm/examples/client/simpleOAuthClientProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleOAuthClientProvider.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClientProvider.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,MAAM,OAAO,2BAA2B;IAKpC,YACqB,YAA0B,EAC1B,eAAoC,EACrD,UAA+B,EACf,iBAA0B;QAHzB,iBAAY,GAAZ,YAAY,CAAc;QAC1B,oBAAe,GAAf,eAAe,CAAqB;QAErC,sBAAiB,GAAjB,iBAAiB,CAAS;QAE1C,IAAI,CAAC,WAAW;YACZ,UAAU;gBACV,CAAC,GAAG,CAAC,EAAE;oBACH,OAAO,CAAC,GAAG,CAAC,gBAAgB,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;gBAClD,CAAC,CAAC,CAAC;IACX,CAAC;IAID,IAAI,WAAW;QACX,OAAO,IAAI,CAAC,YAAY,CAAC;IAC7B,CAAC;IAED,IAAI,cAAc;QACd,OAAO,IAAI,CAAC,eAAe,CAAC;IAChC,CAAC;IAED,iBAAiB;QACb,OAAO,IAAI,CAAC,kBAAkB,CAAC;IACnC,CAAC;IAED,qBAAqB,CAAC,iBAA8C;QAChE,IAAI,CAAC,kBAAkB,GAAG,iBAAiB,CAAC;IAChD,CAAC;IAED,MAAM;QACF,OAAO,IAAI,CAAC,OAAO,CAAC;IACxB,CAAC;IAED,UAAU,CAAC,MAAmB;QAC1B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IAC1B,CAAC;IAED,uBAAuB,CAAC,gBAAqB;QACzC,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC;IACvC,CAAC;IAED,gBAAgB,CAAC,YAAoB;QACjC,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;IACtC,CAAC;IAED,YAAY;QACR,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACtB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC9C,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC;IAC9B,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/examples/client/simpleStreamableHttp.d.ts b/dist/esm/examples/client/simpleStreamableHttp.d.ts new file mode 100644 index 0000000000..a20be42ca4 --- /dev/null +++ b/dist/esm/examples/client/simpleStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/client/simpleStreamableHttp.d.ts.map b/dist/esm/examples/client/simpleStreamableHttp.d.ts.map new file mode 100644 index 0000000000..28406b0c1e --- /dev/null +++ b/dist/esm/examples/client/simpleStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/client/simpleStreamableHttp.js b/dist/esm/examples/client/simpleStreamableHttp.js new file mode 100644 index 0000000000..6a2effd251 --- /dev/null +++ b/dist/esm/examples/client/simpleStreamableHttp.js @@ -0,0 +1,747 @@ +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { createInterface } from 'node:readline'; +import { ListToolsResultSchema, CallToolResultSchema, ListPromptsResultSchema, GetPromptResultSchema, ListResourcesResultSchema, LoggingMessageNotificationSchema, ResourceListChangedNotificationSchema, ElicitRequestSchema, ReadResourceResultSchema, ErrorCode, McpError } from '../../types.js'; +import { getDisplayName } from '../../shared/metadataUtils.js'; +import { Ajv } from 'ajv'; +// Create readline interface for user input +const readline = createInterface({ + input: process.stdin, + output: process.stdout +}); +// Track received notifications for debugging resumability +let notificationCount = 0; +// Global client and transport for interactive commands +let client = null; +let transport = null; +let serverUrl = 'http://localhost:3000/mcp'; +let notificationsToolLastEventId = undefined; +let sessionId = undefined; +async function main() { + console.log('MCP Interactive Client'); + console.log('====================='); + // Connect to server immediately with default settings + await connect(); + // Print help and start the command loop + printHelp(); + commandLoop(); +} +function printHelp() { + console.log('\nAvailable commands:'); + console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)'); + console.log(' disconnect - Disconnect from server'); + console.log(' terminate-session - Terminate the current session'); + console.log(' reconnect - Reconnect to the server'); + console.log(' list-tools - List available tools'); + console.log(' call-tool [args] - Call a tool with optional JSON arguments'); + console.log(' greet [name] - Call the greet tool'); + console.log(' multi-greet [name] - Call the multi-greet tool with notifications'); + console.log(' collect-info [type] - Test form elicitation with collect-user-info tool (contact/preferences/feedback)'); + console.log(' start-notifications [interval] [count] - Start periodic notifications'); + console.log(' run-notifications-tool-with-resumability [interval] [count] - Run notification tool with resumability'); + console.log(' list-prompts - List available prompts'); + console.log(' get-prompt [name] [args] - Get a prompt with optional JSON arguments'); + console.log(' list-resources - List available resources'); + console.log(' read-resource - Read a specific resource by URI'); + console.log(' help - Show this help'); + console.log(' quit - Exit the program'); +} +function commandLoop() { + readline.question('\n> ', async (input) => { + var _a; + const args = input.trim().split(/\s+/); + const command = (_a = args[0]) === null || _a === void 0 ? void 0 : _a.toLowerCase(); + try { + switch (command) { + case 'connect': + await connect(args[1]); + break; + case 'disconnect': + await disconnect(); + break; + case 'terminate-session': + await terminateSession(); + break; + case 'reconnect': + await reconnect(); + break; + case 'list-tools': + await listTools(); + break; + case 'call-tool': + if (args.length < 2) { + console.log('Usage: call-tool [args]'); + } + else { + const toolName = args[1]; + let toolArgs = {}; + if (args.length > 2) { + try { + toolArgs = JSON.parse(args.slice(2).join(' ')); + } + catch (_b) { + console.log('Invalid JSON arguments. Using empty args.'); + } + } + await callTool(toolName, toolArgs); + } + break; + case 'greet': + await callGreetTool(args[1] || 'MCP User'); + break; + case 'multi-greet': + await callMultiGreetTool(args[1] || 'MCP User'); + break; + case 'collect-info': + await callCollectInfoTool(args[1] || 'contact'); + break; + case 'start-notifications': { + const interval = args[1] ? parseInt(args[1], 10) : 2000; + const count = args[2] ? parseInt(args[2], 10) : 10; + await startNotifications(interval, count); + break; + } + case 'run-notifications-tool-with-resumability': { + const interval = args[1] ? parseInt(args[1], 10) : 2000; + const count = args[2] ? parseInt(args[2], 10) : 10; + await runNotificationsToolWithResumability(interval, count); + break; + } + case 'list-prompts': + await listPrompts(); + break; + case 'get-prompt': + if (args.length < 2) { + console.log('Usage: get-prompt [args]'); + } + else { + const promptName = args[1]; + let promptArgs = {}; + if (args.length > 2) { + try { + promptArgs = JSON.parse(args.slice(2).join(' ')); + } + catch (_c) { + console.log('Invalid JSON arguments. Using empty args.'); + } + } + await getPrompt(promptName, promptArgs); + } + break; + case 'list-resources': + await listResources(); + break; + case 'read-resource': + if (args.length < 2) { + console.log('Usage: read-resource '); + } + else { + await readResource(args[1]); + } + break; + case 'help': + printHelp(); + break; + case 'quit': + case 'exit': + await cleanup(); + return; + default: + if (command) { + console.log(`Unknown command: ${command}`); + } + break; + } + } + catch (error) { + console.error(`Error executing command: ${error}`); + } + // Continue the command loop + commandLoop(); + }); +} +async function connect(url) { + if (client) { + console.log('Already connected. Disconnect first.'); + return; + } + if (url) { + serverUrl = url; + } + console.log(`Connecting to ${serverUrl}...`); + try { + // Create a new client with form elicitation capability + client = new Client({ + name: 'example-client', + version: '1.0.0' + }, { + capabilities: { + elicitation: { + form: {} + } + } + }); + client.onerror = error => { + console.error('\x1b[31mClient error:', error, '\x1b[0m'); + }; + // Set up elicitation request handler with proper validation + client.setRequestHandler(ElicitRequestSchema, async (request) => { + var _a; + if (request.params.mode !== 'form') { + throw new McpError(ErrorCode.InvalidParams, `Unsupported elicitation mode: ${request.params.mode}`); + } + console.log('\n🔔 Elicitation (form) Request Received:'); + console.log(`Message: ${request.params.message}`); + console.log('Requested Schema:'); + console.log(JSON.stringify(request.params.requestedSchema, null, 2)); + const schema = request.params.requestedSchema; + const properties = schema.properties; + const required = schema.required || []; + // Set up AJV validator for the requested schema + const ajv = new Ajv(); + const validate = ajv.compile(schema); + let attempts = 0; + const maxAttempts = 3; + while (attempts < maxAttempts) { + attempts++; + console.log(`\nPlease provide the following information (attempt ${attempts}/${maxAttempts}):`); + const content = {}; + let inputCancelled = false; + // Collect input for each field + for (const [fieldName, fieldSchema] of Object.entries(properties)) { + const field = fieldSchema; + const isRequired = required.includes(fieldName); + let prompt = `${field.title || fieldName}`; + // Add helpful information to the prompt + if (field.description) { + prompt += ` (${field.description})`; + } + if (field.enum) { + prompt += ` [options: ${field.enum.join(', ')}]`; + } + if (field.type === 'number' || field.type === 'integer') { + if (field.minimum !== undefined && field.maximum !== undefined) { + prompt += ` [${field.minimum}-${field.maximum}]`; + } + else if (field.minimum !== undefined) { + prompt += ` [min: ${field.minimum}]`; + } + else if (field.maximum !== undefined) { + prompt += ` [max: ${field.maximum}]`; + } + } + if (field.type === 'string' && field.format) { + prompt += ` [format: ${field.format}]`; + } + if (isRequired) { + prompt += ' *required*'; + } + if (field.default !== undefined) { + prompt += ` [default: ${field.default}]`; + } + prompt += ': '; + const answer = await new Promise(resolve => { + readline.question(prompt, input => { + resolve(input.trim()); + }); + }); + // Check for cancellation + if (answer.toLowerCase() === 'cancel' || answer.toLowerCase() === 'c') { + inputCancelled = true; + break; + } + // Parse and validate the input + try { + if (answer === '' && field.default !== undefined) { + content[fieldName] = field.default; + } + else if (answer === '' && !isRequired) { + // Skip optional empty fields + continue; + } + else if (answer === '') { + throw new Error(`${fieldName} is required`); + } + else { + // Parse the value based on type + let parsedValue; + if (field.type === 'boolean') { + parsedValue = answer.toLowerCase() === 'true' || answer.toLowerCase() === 'yes' || answer === '1'; + } + else if (field.type === 'number') { + parsedValue = parseFloat(answer); + if (isNaN(parsedValue)) { + throw new Error(`${fieldName} must be a valid number`); + } + } + else if (field.type === 'integer') { + parsedValue = parseInt(answer, 10); + if (isNaN(parsedValue)) { + throw new Error(`${fieldName} must be a valid integer`); + } + } + else if (field.enum) { + if (!field.enum.includes(answer)) { + throw new Error(`${fieldName} must be one of: ${field.enum.join(', ')}`); + } + parsedValue = answer; + } + else { + parsedValue = answer; + } + content[fieldName] = parsedValue; + } + } + catch (error) { + console.log(`❌ Error: ${error}`); + // Continue to next attempt + break; + } + } + if (inputCancelled) { + return { action: 'cancel' }; + } + // If we didn't complete all fields due to an error, try again + if (Object.keys(content).length !== + Object.keys(properties).filter(name => required.includes(name) || content[name] !== undefined).length) { + if (attempts < maxAttempts) { + console.log('Please try again...'); + continue; + } + else { + console.log('Maximum attempts reached. Declining request.'); + return { action: 'decline' }; + } + } + // Validate the complete object against the schema + const isValid = validate(content); + if (!isValid) { + console.log('❌ Validation errors:'); + (_a = validate.errors) === null || _a === void 0 ? void 0 : _a.forEach(error => { + console.log(` - ${error.instancePath || 'root'}: ${error.message}`); + }); + if (attempts < maxAttempts) { + console.log('Please correct the errors and try again...'); + continue; + } + else { + console.log('Maximum attempts reached. Declining request.'); + return { action: 'decline' }; + } + } + // Show the collected data and ask for confirmation + console.log('\n✅ Collected data:'); + console.log(JSON.stringify(content, null, 2)); + const confirmAnswer = await new Promise(resolve => { + readline.question('\nSubmit this information? (yes/no/cancel): ', input => { + resolve(input.trim().toLowerCase()); + }); + }); + if (confirmAnswer === 'yes' || confirmAnswer === 'y') { + return { + action: 'accept', + content + }; + } + else if (confirmAnswer === 'cancel' || confirmAnswer === 'c') { + return { action: 'cancel' }; + } + else if (confirmAnswer === 'no' || confirmAnswer === 'n') { + if (attempts < maxAttempts) { + console.log('Please re-enter the information...'); + continue; + } + else { + return { action: 'decline' }; + } + } + } + console.log('Maximum attempts reached. Declining request.'); + return { action: 'decline' }; + }); + transport = new StreamableHTTPClientTransport(new URL(serverUrl), { + sessionId: sessionId + }); + // Set up notification handlers + client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { + notificationCount++; + console.log(`\nNotification #${notificationCount}: ${notification.params.level} - ${notification.params.data}`); + // Re-display the prompt + process.stdout.write('> '); + }); + client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_) => { + console.log(`\nResource list changed notification received!`); + try { + if (!client) { + console.log('Client disconnected, cannot fetch resources'); + return; + } + const resourcesResult = await client.request({ + method: 'resources/list', + params: {} + }, ListResourcesResultSchema); + console.log('Available resources count:', resourcesResult.resources.length); + } + catch (_a) { + console.log('Failed to list resources after change notification'); + } + // Re-display the prompt + process.stdout.write('> '); + }); + // Connect the client + await client.connect(transport); + sessionId = transport.sessionId; + console.log('Transport created with session ID:', sessionId); + console.log('Connected to MCP server'); + } + catch (error) { + console.error('Failed to connect:', error); + client = null; + transport = null; + } +} +async function disconnect() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + await transport.close(); + console.log('Disconnected from MCP server'); + client = null; + transport = null; + } + catch (error) { + console.error('Error disconnecting:', error); + } +} +async function terminateSession() { + if (!client || !transport) { + console.log('Not connected.'); + return; + } + try { + console.log('Terminating session with ID:', transport.sessionId); + await transport.terminateSession(); + console.log('Session terminated successfully'); + // Check if sessionId was cleared after termination + if (!transport.sessionId) { + console.log('Session ID has been cleared'); + sessionId = undefined; + // Also close the transport and clear client objects + await transport.close(); + console.log('Transport closed after session termination'); + client = null; + transport = null; + } + else { + console.log('Server responded with 405 Method Not Allowed (session termination not supported)'); + console.log('Session ID is still active:', transport.sessionId); + } + } + catch (error) { + console.error('Error terminating session:', error); + } +} +async function reconnect() { + if (client) { + await disconnect(); + } + await connect(); +} +async function listTools() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - id: ${tool.name}, name: ${getDisplayName(tool)}, description: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server (${error})`); + } +} +async function callTool(name, args) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const request = { + method: 'tools/call', + params: { + name, + arguments: args + } + }; + console.log(`Calling tool '${name}' with args:`, args); + const result = await client.request(request, CallToolResultSchema); + console.log('Tool result:'); + const resourceLinks = []; + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else if (item.type === 'resource_link') { + const resourceLink = item; + resourceLinks.push(resourceLink); + console.log(` 📁 Resource Link: ${resourceLink.name}`); + console.log(` URI: ${resourceLink.uri}`); + if (resourceLink.mimeType) { + console.log(` Type: ${resourceLink.mimeType}`); + } + if (resourceLink.description) { + console.log(` Description: ${resourceLink.description}`); + } + } + else if (item.type === 'resource') { + console.log(` [Embedded Resource: ${item.resource.uri}]`); + } + else if (item.type === 'image') { + console.log(` [Image: ${item.mimeType}]`); + } + else if (item.type === 'audio') { + console.log(` [Audio: ${item.mimeType}]`); + } + else { + console.log(` [Unknown content type]:`, item); + } + }); + // Offer to read resource links + if (resourceLinks.length > 0) { + console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource ' to read their content.`); + } + } + catch (error) { + console.log(`Error calling tool ${name}: ${error}`); + } +} +async function callGreetTool(name) { + await callTool('greet', { name }); +} +async function callMultiGreetTool(name) { + console.log('Calling multi-greet tool with notifications...'); + await callTool('multi-greet', { name }); +} +async function callCollectInfoTool(infoType) { + console.log(`Testing form elicitation with collect-user-info tool (${infoType})...`); + await callTool('collect-user-info', { infoType }); +} +async function startNotifications(interval, count) { + console.log(`Starting notification stream: interval=${interval}ms, count=${count || 'unlimited'}`); + await callTool('start-notification-stream', { interval, count }); +} +async function runNotificationsToolWithResumability(interval, count) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + console.log(`Starting notification stream with resumability: interval=${interval}ms, count=${count || 'unlimited'}`); + console.log(`Using resumption token: ${notificationsToolLastEventId || 'none'}`); + const request = { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { interval, count } + } + }; + const onLastEventIdUpdate = (event) => { + notificationsToolLastEventId = event; + console.log(`Updated resumption token: ${event}`); + }; + const result = await client.request(request, CallToolResultSchema, { + resumptionToken: notificationsToolLastEventId, + onresumptiontoken: onLastEventIdUpdate + }); + console.log('Tool result:'); + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + catch (error) { + console.log(`Error starting notification stream: ${error}`); + } +} +async function listPrompts() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const promptsRequest = { + method: 'prompts/list', + params: {} + }; + const promptsResult = await client.request(promptsRequest, ListPromptsResultSchema); + console.log('Available prompts:'); + if (promptsResult.prompts.length === 0) { + console.log(' No prompts available'); + } + else { + for (const prompt of promptsResult.prompts) { + console.log(` - id: ${prompt.name}, name: ${getDisplayName(prompt)}, description: ${prompt.description}`); + } + } + } + catch (error) { + console.log(`Prompts not supported by this server (${error})`); + } +} +async function getPrompt(name, args) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const promptRequest = { + method: 'prompts/get', + params: { + name, + arguments: args + } + }; + const promptResult = await client.request(promptRequest, GetPromptResultSchema); + console.log('Prompt template:'); + promptResult.messages.forEach((msg, index) => { + console.log(` [${index + 1}] ${msg.role}: ${msg.content.type === 'text' ? msg.content.text : JSON.stringify(msg.content)}`); + }); + } + catch (error) { + console.log(`Error getting prompt ${name}: ${error}`); + } +} +async function listResources() { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const resourcesRequest = { + method: 'resources/list', + params: {} + }; + const resourcesResult = await client.request(resourcesRequest, ListResourcesResultSchema); + console.log('Available resources:'); + if (resourcesResult.resources.length === 0) { + console.log(' No resources available'); + } + else { + for (const resource of resourcesResult.resources) { + console.log(` - id: ${resource.name}, name: ${getDisplayName(resource)}, description: ${resource.uri}`); + } + } + } + catch (error) { + console.log(`Resources not supported by this server (${error})`); + } +} +async function readResource(uri) { + if (!client) { + console.log('Not connected to server.'); + return; + } + try { + const request = { + method: 'resources/read', + params: { uri } + }; + console.log(`Reading resource: ${uri}`); + const result = await client.request(request, ReadResourceResultSchema); + console.log('Resource contents:'); + for (const content of result.contents) { + console.log(` URI: ${content.uri}`); + if (content.mimeType) { + console.log(` Type: ${content.mimeType}`); + } + if ('text' in content && typeof content.text === 'string') { + console.log(' Content:'); + console.log(' ---'); + console.log(content.text + .split('\n') + .map((line) => ' ' + line) + .join('\n')); + console.log(' ---'); + } + else if ('blob' in content && typeof content.blob === 'string') { + console.log(` [Binary data: ${content.blob.length} bytes]`); + } + } + } + catch (error) { + console.log(`Error reading resource ${uri}: ${error}`); + } +} +async function cleanup() { + if (client && transport) { + try { + // First try to terminate the session gracefully + if (transport.sessionId) { + try { + console.log('Terminating session before exit...'); + await transport.terminateSession(); + console.log('Session terminated successfully'); + } + catch (error) { + console.error('Error terminating session:', error); + } + } + // Then close the transport + await transport.close(); + } + catch (error) { + console.error('Error closing transport:', error); + } + } + process.stdin.setRawMode(false); + readline.close(); + console.log('\nGoodbye!'); + process.exit(0); +} +// Set up raw mode for keyboard input to capture Escape key +process.stdin.setRawMode(true); +process.stdin.on('data', async (data) => { + // Check for Escape key (27) + if (data.length === 1 && data[0] === 27) { + console.log('\nESC key pressed. Disconnecting from server...'); + // Abort current operation and disconnect from server + if (client && transport) { + await disconnect(); + console.log('Disconnected. Press Enter to continue.'); + } + else { + console.log('Not connected to server.'); + } + // Re-display the prompt + process.stdout.write('> '); + } +}); +// Handle Ctrl+C +process.on('SIGINT', async () => { + console.log('\nReceived SIGINT. Cleaning up...'); + await cleanup(); +}); +// Start the interactive client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=simpleStreamableHttp.js.map \ No newline at end of file diff --git a/dist/esm/examples/client/simpleStreamableHttp.js.map b/dist/esm/examples/client/simpleStreamableHttp.js.map new file mode 100644 index 0000000000..b5495eb5ba --- /dev/null +++ b/dist/esm/examples/client/simpleStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleStreamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAEH,qBAAqB,EAErB,oBAAoB,EAEpB,uBAAuB,EAEvB,qBAAqB,EAErB,yBAAyB,EACzB,gCAAgC,EAChC,qCAAqC,EACrC,mBAAmB,EAGnB,wBAAwB,EACxB,SAAS,EACT,QAAQ,EACX,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAC/D,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAE1B,2CAA2C;AAC3C,MAAM,QAAQ,GAAG,eAAe,CAAC;IAC7B,KAAK,EAAE,OAAO,CAAC,KAAK;IACpB,MAAM,EAAE,OAAO,CAAC,MAAM;CACzB,CAAC,CAAC;AAEH,0DAA0D;AAC1D,IAAI,iBAAiB,GAAG,CAAC,CAAC;AAE1B,uDAAuD;AACvD,IAAI,MAAM,GAAkB,IAAI,CAAC;AACjC,IAAI,SAAS,GAAyC,IAAI,CAAC;AAC3D,IAAI,SAAS,GAAG,2BAA2B,CAAC;AAC5C,IAAI,4BAA4B,GAAuB,SAAS,CAAC;AACjE,IAAI,SAAS,GAAuB,SAAS,CAAC;AAE9C,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;IACtC,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;IAErC,sDAAsD;IACtD,MAAM,OAAO,EAAE,CAAC;IAE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CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC;AAED,2DAA2D;AAC3D,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAC/B,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,EAAC,IAAI,EAAC,EAAE;IAClC,4BAA4B;IAC5B,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;QACtC,OAAO,CAAC,GAAG,CAAC,iDAAiD,CAAC,CAAC;QAE/D,qDAAqD;QACrD,IAAI,MAAM,IAAI,SAAS,EAAE,CAAC;YACtB,MAAM,UAAU,EAAE,CAAC;YACnB,OAAO,CAAC,GAAG,CAAC,wCAAwC,CAAC,CAAC;QAC1D,CAAC;aAAM,CAAC;YACJ,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;QAC5C,CAAC;QAED,wBAAwB;QACxB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,gBAAgB;AAChB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;IACjD,MAAM,OAAO,EAAE,CAAC;AACpB,CAAC,CAAC,CAAC;AAEH,+BAA+B;AAC/B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts b/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts new file mode 100644 index 0000000000..c2679e6694 --- /dev/null +++ b/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=streamableHttpWithSseFallbackClient.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts.map b/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts.map new file mode 100644 index 0000000000..b79ae2a72c --- /dev/null +++ b/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttpWithSseFallbackClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/streamableHttpWithSseFallbackClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js b/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js new file mode 100644 index 0000000000..1bea76828d --- /dev/null +++ b/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js @@ -0,0 +1,166 @@ +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { SSEClientTransport } from '../../client/sse.js'; +import { ListToolsResultSchema, CallToolResultSchema, LoggingMessageNotificationSchema } from '../../types.js'; +/** + * Simplified Backwards Compatible MCP Client + * + * This client demonstrates backward compatibility with both: + * 1. Modern servers using Streamable HTTP transport (protocol version 2025-03-26) + * 2. Older servers using HTTP+SSE transport (protocol version 2024-11-05) + * + * Following the MCP specification for backwards compatibility: + * - Attempts to POST an initialize request to the server URL first (modern transport) + * - If that fails with 4xx status, falls back to GET request for SSE stream (older transport) + */ +// Command line args processing +const args = process.argv.slice(2); +const serverUrl = args[0] || 'http://localhost:3000/mcp'; +async function main() { + console.log('MCP Backwards Compatible Client'); + console.log('==============================='); + console.log(`Connecting to server at: ${serverUrl}`); + let client; + let transport; + try { + // Try connecting with automatic transport detection + const connection = await connectWithBackwardsCompatibility(serverUrl); + client = connection.client; + transport = connection.transport; + // Set up notification handler + client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { + console.log(`Notification: ${notification.params.level} - ${notification.params.data}`); + }); + // DEMO WORKFLOW: + // 1. List available tools + console.log('\n=== Listing Available Tools ==='); + await listTools(client); + // 2. Call the notification tool + console.log('\n=== Starting Notification Stream ==='); + await startNotificationTool(client); + // 3. Wait for all notifications (5 seconds) + console.log('\n=== Waiting for all notifications ==='); + await new Promise(resolve => setTimeout(resolve, 5000)); + // 4. Disconnect + console.log('\n=== Disconnecting ==='); + await transport.close(); + console.log('Disconnected from MCP server'); + } + catch (error) { + console.error('Error running client:', error); + process.exit(1); + } +} +/** + * Connect to an MCP server with backwards compatibility + * Following the spec for client backward compatibility + */ +async function connectWithBackwardsCompatibility(url) { + console.log('1. Trying Streamable HTTP transport first...'); + // Step 1: Try Streamable HTTP transport first + const client = new Client({ + name: 'backwards-compatible-client', + version: '1.0.0' + }); + client.onerror = error => { + console.error('Client error:', error); + }; + const baseUrl = new URL(url); + try { + // Create modern transport + const streamableTransport = new StreamableHTTPClientTransport(baseUrl); + await client.connect(streamableTransport); + console.log('Successfully connected using modern Streamable HTTP transport.'); + return { + client, + transport: streamableTransport, + transportType: 'streamable-http' + }; + } + catch (error) { + // Step 2: If transport fails, try the older SSE transport + console.log(`StreamableHttp transport connection failed: ${error}`); + console.log('2. Falling back to deprecated HTTP+SSE transport...'); + try { + // Create SSE transport pointing to /sse endpoint + const sseTransport = new SSEClientTransport(baseUrl); + const sseClient = new Client({ + name: 'backwards-compatible-client', + version: '1.0.0' + }); + await sseClient.connect(sseTransport); + console.log('Successfully connected using deprecated HTTP+SSE transport.'); + return { + client: sseClient, + transport: sseTransport, + transportType: 'sse' + }; + } + catch (sseError) { + console.error(`Failed to connect with either transport method:\n1. Streamable HTTP error: ${error}\n2. SSE error: ${sseError}`); + throw new Error('Could not connect to server with any available transport'); + } + } +} +/** + * List available tools on the server + */ +async function listTools(client) { + try { + const toolsRequest = { + method: 'tools/list', + params: {} + }; + const toolsResult = await client.request(toolsRequest, ListToolsResultSchema); + console.log('Available tools:'); + if (toolsResult.tools.length === 0) { + console.log(' No tools available'); + } + else { + for (const tool of toolsResult.tools) { + console.log(` - ${tool.name}: ${tool.description}`); + } + } + } + catch (error) { + console.log(`Tools not supported by this server: ${error}`); + } +} +/** + * Start a notification stream by calling the notification tool + */ +async function startNotificationTool(client) { + try { + // Call the notification tool using reasonable defaults + const request = { + method: 'tools/call', + params: { + name: 'start-notification-stream', + arguments: { + interval: 1000, // 1 second between notifications + count: 5 // Send 5 notifications + } + } + }; + console.log('Calling notification tool...'); + const result = await client.request(request, CallToolResultSchema); + console.log('Tool result:'); + result.content.forEach(item => { + if (item.type === 'text') { + console.log(` ${item.text}`); + } + else { + console.log(` ${item.type} content:`, item); + } + }); + } + catch (error) { + console.log(`Error calling notification tool: ${error}`); + } +} +// Start the client +main().catch((error) => { + console.error('Error running MCP client:', error); + process.exit(1); +}); +//# sourceMappingURL=streamableHttpWithSseFallbackClient.js.map \ No newline at end of file diff --git a/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js.map b/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js.map new file mode 100644 index 0000000000..0d9399dc90 --- /dev/null +++ b/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttpWithSseFallbackClient.js","sourceRoot":"","sources":["../../../../src/examples/client/streamableHttpWithSseFallbackClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAEH,qBAAqB,EAErB,oBAAoB,EACpB,gCAAgC,EACnC,MAAM,gBAAgB,CAAC;AAExB;;;;;;;;;;GAUG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,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oInMemoryOAuthProvider.d.ts new file mode 100644 index 0000000000..218aeac8b2 --- /dev/null +++ b/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts @@ -0,0 +1,78 @@ +import { AuthorizationParams, OAuthServerProvider } from '../../server/auth/provider.js'; +import { OAuthRegisteredClientsStore } from '../../server/auth/clients.js'; +import { OAuthClientInformationFull, OAuthMetadata, OAuthTokens } from '../../shared/auth.js'; +import { Response } from 'express'; +import { AuthInfo } from '../../server/auth/types.js'; +export declare class DemoInMemoryClientsStore implements OAuthRegisteredClientsStore { + private clients; + getClient(clientId: string): Promise<{ + redirect_uris: string[]; + client_id: string; + token_endpoint_auth_method?: string | undefined; + grant_types?: string[] | undefined; + response_types?: string[] | undefined; + client_name?: string | undefined; + client_uri?: string | undefined; + logo_uri?: string | undefined; + scope?: string | undefined; + contacts?: string[] | undefined; + tos_uri?: string | undefined; + policy_uri?: string | undefined; + jwks_uri?: string | undefined; + jwks?: any; + software_id?: string | undefined; + software_version?: string | undefined; + software_statement?: string | undefined; + client_secret?: string | undefined; + client_id_issued_at?: number | undefined; + client_secret_expires_at?: number | undefined; + } | undefined>; + registerClient(clientMetadata: OAuthClientInformationFull): Promise<{ + redirect_uris: string[]; + client_id: string; + token_endpoint_auth_method?: string | undefined; + grant_types?: string[] | undefined; + response_types?: string[] | undefined; + client_name?: string | undefined; + client_uri?: string | undefined; + logo_uri?: string | undefined; + scope?: string | undefined; + contacts?: string[] | undefined; + tos_uri?: string | undefined; + policy_uri?: string | undefined; + jwks_uri?: string | undefined; + jwks?: any; + software_id?: string | undefined; + software_version?: string | undefined; + software_statement?: string | undefined; + client_secret?: string | undefined; + client_id_issued_at?: number | undefined; + client_secret_expires_at?: number | undefined; + }>; +} +/** + * 🚨 DEMO ONLY - NOT FOR PRODUCTION + * + * This example demonstrates MCP OAuth flow but lacks some of the features required for production use, + * for example: + * - Persistent token storage + * - Rate limiting + */ +export declare class DemoInMemoryAuthProvider implements OAuthServerProvider { + private validateResource?; + clientsStore: DemoInMemoryClientsStore; + private codes; + private tokens; + constructor(validateResource?: ((resource?: URL) => boolean) | undefined); + authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; + challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise; + exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, _codeVerifier?: string): Promise; + exchangeRefreshToken(_client: OAuthClientInformationFull, _refreshToken: string, _scopes?: string[], _resource?: URL): Promise; + verifyAccessToken(token: string): Promise; +} +export declare const setupAuthServer: ({ authServerUrl, mcpServerUrl, strictResource }: { + authServerUrl: URL; + mcpServerUrl: URL; + strictResource: boolean; +}) => OAuthMetadata; +//# sourceMappingURL=demoInMemoryOAuthProvider.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts.map b/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts.map new file mode 100644 index 0000000000..8a4a43fe8d --- /dev/null +++ b/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"demoInMemoryOAuthProvider.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/demoInMemoryOAuthProvider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACzF,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAgB,EAAW,QAAQ,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAKtD,qBAAa,wBAAyB,YAAW,2BAA2B;IACxE,OAAO,CAAC,OAAO,CAAiD;IAE1D,SAAS,CAAC,QAAQ,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;IAI1B,cAAc,CAAC,cAAc,EAAE,0BAA0B;;;;;;;;;;;;;;;;;;;;;;CAIlE;AAED;;;;;;;GAOG;AACH,qBAAa,wBAAyB,YAAW,mBAAmB;IAWpD,OAAO,CAAC,gBAAgB,CAAC;IAVrC,YAAY,2BAAkC;IAC9C,OAAO,CAAC,KAAK,CAMT;IACJ,OAAO,CAAC,MAAM,CAA+B;gBAEzB,gBAAgB,CAAC,GAAE,CAAC,QAAQ,CAAC,EAAE,GAAG,KAAK,OAAO,aAAA;IAE5D,SAAS,CAAC,MAAM,EAAE,0BAA0B,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAwCxG,6BAA6B,CAAC,MAAM,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAU7G,yBAAyB,CAC3B,MAAM,EAAE,0BAA0B,EAClC,iBAAiB,EAAE,MAAM,EAGzB,aAAa,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,WAAW,CAAC;IAoCjB,oBAAoB,CACtB,OAAO,EAAE,0BAA0B,EACnC,aAAa,EAAE,MAAM,EACrB,OAAO,CAAC,EAAE,MAAM,EAAE,EAClB,SAAS,CAAC,EAAE,GAAG,GAChB,OAAO,CAAC,WAAW,CAAC;IAIjB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;CAc5D;AAED,eAAO,MAAM,eAAe,oDAIzB;IACC,aAAa,EAAE,GAAG,CAAC;IACnB,YAAY,EAAE,GAAG,CAAC;IAClB,cAAc,EAAE,OAAO,CAAC;CAC3B,KAAG,aA+EH,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/demoInMemoryOAuthProvider.js b/dist/esm/examples/server/demoInMemoryOAuthProvider.js new file mode 100644 index 0000000000..45bde7043d --- /dev/null +++ b/dist/esm/examples/server/demoInMemoryOAuthProvider.js @@ -0,0 +1,196 @@ +import { randomUUID } from 'node:crypto'; +import express from 'express'; +import { createOAuthMetadata, mcpAuthRouter } from '../../server/auth/router.js'; +import { resourceUrlFromServerUrl } from '../../shared/auth-utils.js'; +import { InvalidRequestError } from '../../server/auth/errors.js'; +export class DemoInMemoryClientsStore { + constructor() { + this.clients = new Map(); + } + async getClient(clientId) { + return this.clients.get(clientId); + } + async registerClient(clientMetadata) { + this.clients.set(clientMetadata.client_id, clientMetadata); + return clientMetadata; + } +} +/** + * 🚨 DEMO ONLY - NOT FOR PRODUCTION + * + * This example demonstrates MCP OAuth flow but lacks some of the features required for production use, + * for example: + * - Persistent token storage + * - Rate limiting + */ +export class DemoInMemoryAuthProvider { + constructor(validateResource) { + this.validateResource = validateResource; + this.clientsStore = new DemoInMemoryClientsStore(); + this.codes = new Map(); + this.tokens = new Map(); + } + async authorize(client, params, res) { + const code = randomUUID(); + const searchParams = new URLSearchParams({ + code + }); + if (params.state !== undefined) { + searchParams.set('state', params.state); + } + this.codes.set(code, { + client, + params + }); + // Simulate a user login + // Set a secure HTTP-only session cookie with authorization info + if (res.cookie) { + const authCookieData = { + userId: 'demo_user', + name: 'Demo User', + timestamp: Date.now() + }; + res.cookie('demo_session', JSON.stringify(authCookieData), { + httpOnly: true, + secure: false, // In production, this should be true + sameSite: 'lax', + maxAge: 24 * 60 * 60 * 1000, // 24 hours - for demo purposes + path: '/' // Available to all routes + }); + } + if (!client.redirect_uris.includes(params.redirectUri)) { + throw new InvalidRequestError('Unregistered redirect_uri'); + } + const targetUrl = new URL(params.redirectUri); + targetUrl.search = searchParams.toString(); + res.redirect(targetUrl.toString()); + } + async challengeForAuthorizationCode(client, authorizationCode) { + // Store the challenge with the code data + const codeData = this.codes.get(authorizationCode); + if (!codeData) { + throw new Error('Invalid authorization code'); + } + return codeData.params.codeChallenge; + } + async exchangeAuthorizationCode(client, authorizationCode, + // Note: code verifier is checked in token.ts by default + // it's unused here for that reason. + _codeVerifier) { + const codeData = this.codes.get(authorizationCode); + if (!codeData) { + throw new Error('Invalid authorization code'); + } + if (codeData.client.client_id !== client.client_id) { + throw new Error(`Authorization code was not issued to this client, ${codeData.client.client_id} != ${client.client_id}`); + } + if (this.validateResource && !this.validateResource(codeData.params.resource)) { + throw new Error(`Invalid resource: ${codeData.params.resource}`); + } + this.codes.delete(authorizationCode); + const token = randomUUID(); + const tokenData = { + token, + clientId: client.client_id, + scopes: codeData.params.scopes || [], + expiresAt: Date.now() + 3600000, // 1 hour + resource: codeData.params.resource, + type: 'access' + }; + this.tokens.set(token, tokenData); + return { + access_token: token, + token_type: 'bearer', + expires_in: 3600, + scope: (codeData.params.scopes || []).join(' ') + }; + } + async exchangeRefreshToken(_client, _refreshToken, _scopes, _resource) { + throw new Error('Not implemented for example demo'); + } + async verifyAccessToken(token) { + const tokenData = this.tokens.get(token); + if (!tokenData || !tokenData.expiresAt || tokenData.expiresAt < Date.now()) { + throw new Error('Invalid or expired token'); + } + return { + token, + clientId: tokenData.clientId, + scopes: tokenData.scopes, + expiresAt: Math.floor(tokenData.expiresAt / 1000), + resource: tokenData.resource + }; + } +} +export const setupAuthServer = ({ authServerUrl, mcpServerUrl, strictResource }) => { + // Create separate auth server app + // NOTE: This is a separate app on a separate port to illustrate + // how to separate an OAuth Authorization Server from a Resource + // server in the SDK. The SDK is not intended to be provide a standalone + // authorization server. + const validateResource = strictResource + ? (resource) => { + if (!resource) + return false; + const expectedResource = resourceUrlFromServerUrl(mcpServerUrl); + return resource.toString() === expectedResource.toString(); + } + : undefined; + const provider = new DemoInMemoryAuthProvider(validateResource); + const authApp = express(); + authApp.use(express.json()); + // For introspection requests + authApp.use(express.urlencoded()); + // Add OAuth routes to the auth server + // NOTE: this will also add a protected resource metadata route, + // but it won't be used, so leave it. + authApp.use(mcpAuthRouter({ + provider, + issuerUrl: authServerUrl, + scopesSupported: ['mcp:tools'] + })); + authApp.post('/introspect', async (req, res) => { + try { + const { token } = req.body; + if (!token) { + res.status(400).json({ error: 'Token is required' }); + return; + } + const tokenInfo = await provider.verifyAccessToken(token); + res.json({ + active: true, + client_id: tokenInfo.clientId, + scope: tokenInfo.scopes.join(' '), + exp: tokenInfo.expiresAt, + aud: tokenInfo.resource + }); + return; + } + catch (error) { + res.status(401).json({ + active: false, + error: 'Unauthorized', + error_description: `Invalid token: ${error}` + }); + } + }); + const auth_port = authServerUrl.port; + // Start the auth server + authApp.listen(auth_port, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`OAuth Authorization Server listening on port ${auth_port}`); + }); + // Note: we could fetch this from the server, but then we end up + // with some top level async which gets annoying. + const oauthMetadata = createOAuthMetadata({ + provider, + issuerUrl: authServerUrl, + scopesSupported: ['mcp:tools'] + }); + oauthMetadata.introspection_endpoint = new URL('/introspect', authServerUrl).href; + return oauthMetadata; +}; +//# sourceMappingURL=demoInMemoryOAuthProvider.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/demoInMemoryOAuthProvider.js.map b/dist/esm/examples/server/demoInMemoryOAuthProvider.js.map new file mode 100644 index 0000000000..80fcc5502d --- /dev/null +++ b/dist/esm/examples/server/demoInMemoryOAuthProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"demoInMemoryOAuthProvider.js","sourceRoot":"","sources":["../../../../src/examples/server/demoInMemoryOAuthProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAIzC,OAAO,OAA8B,MAAM,SAAS,CAAC;AAErD,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AACjF,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,MAAM,OAAO,wBAAwB;IAArC;QACY,YAAO,GAAG,IAAI,GAAG,EAAsC,CAAC;IAUpE,CAAC;IARG,KAAK,CAAC,SAAS,CAAC,QAAgB;QAC5B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACtC,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AAI,CAAC,CAAC,CAAC,CAAC;QACpB,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,gDAAgD,SAAS,EAAE,CAAC,CAAC;IAC7E,CAAC,CAAC,CAAC;IAEH,gEAAgE;IAChE,iDAAiD;IACjD,MAAM,aAAa,GAAkB,mBAAmB,CAAC;QACrD,QAAQ;QACR,SAAS,EAAE,aAAa;QACxB,eAAe,EAAE,CAAC,WAAW,CAAC;KACjC,CAAC,CAAC;IAEH,aAAa,CAAC,sBAAsB,GAAG,IAAI,GAAG,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC,IAAI,CAAC;IAElF,OAAO,aAAa,CAAC;AACzB,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationFormExample.d.ts b/dist/esm/examples/server/elicitationFormExample.d.ts new file mode 100644 index 0000000000..e4b736e0f2 --- /dev/null +++ b/dist/esm/examples/server/elicitationFormExample.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=elicitationFormExample.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationFormExample.d.ts.map b/dist/esm/examples/server/elicitationFormExample.d.ts.map new file mode 100644 index 0000000000..c569df428d --- /dev/null +++ b/dist/esm/examples/server/elicitationFormExample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationFormExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/elicitationFormExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationFormExample.js b/dist/esm/examples/server/elicitationFormExample.js new file mode 100644 index 0000000000..1a651166dc --- /dev/null +++ b/dist/esm/examples/server/elicitationFormExample.js @@ -0,0 +1,436 @@ +// Run with: npx tsx src/examples/server/elicitationFormExample.ts +// +// This example demonstrates how to use form elicitation to collect structured user input +// with JSON Schema validation via a local HTTP server with SSE streaming. +// Form elicitation allows servers to request *non-sensitive* user input through the client +// with schema-based validation. +// Note: See also elicitationUrlExample.ts for an example of using URL elicitation +// to collect *sensitive* user input via a browser. +import { randomUUID } from 'node:crypto'; +import cors from 'cors'; +import express from 'express'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { isInitializeRequest } from '../../types.js'; +// Create MCP server - it will automatically use AjvJsonSchemaValidator with sensible defaults +// The validator supports format validation (email, date, etc.) if ajv-formats is installed +const mcpServer = new McpServer({ + name: 'form-elicitation-example-server', + version: '1.0.0' +}, { + capabilities: {} +}); +/** + * Example 1: Simple user registration tool + * Collects username, email, and password from the user + */ +mcpServer.registerTool('register_user', { + description: 'Register a new user account by collecting their information', + inputSchema: {} +}, async () => { + try { + // Request user information through form elicitation + const result = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Please provide your registration information:', + requestedSchema: { + type: 'object', + properties: { + username: { + type: 'string', + title: 'Username', + description: 'Your desired username (3-20 characters)', + minLength: 3, + maxLength: 20 + }, + email: { + type: 'string', + title: 'Email', + description: 'Your email address', + format: 'email' + }, + password: { + type: 'string', + title: 'Password', + description: 'Your password (min 8 characters)', + minLength: 8 + }, + newsletter: { + type: 'boolean', + title: 'Newsletter', + description: 'Subscribe to newsletter?', + default: false + } + }, + required: ['username', 'email', 'password'] + } + }); + // Handle the different possible actions + if (result.action === 'accept' && result.content) { + const { username, email, newsletter } = result.content; + return { + content: [ + { + type: 'text', + text: `Registration successful!\n\nUsername: ${username}\nEmail: ${email}\nNewsletter: ${newsletter ? 'Yes' : 'No'}` + } + ] + }; + } + else if (result.action === 'decline') { + return { + content: [ + { + type: 'text', + text: 'Registration cancelled by user.' + } + ] + }; + } + else { + return { + content: [ + { + type: 'text', + text: 'Registration was cancelled.' + } + ] + }; + } + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Registration failed: ${error instanceof Error ? error.message : String(error)}` + } + ], + isError: true + }; + } +}); +/** + * Example 2: Multi-step workflow with multiple form elicitation requests + * Demonstrates how to collect information in multiple steps + */ +mcpServer.registerTool('create_event', { + description: 'Create a calendar event by collecting event details', + inputSchema: {} +}, async () => { + try { + // Step 1: Collect basic event information + const basicInfo = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Step 1: Enter basic event information', + requestedSchema: { + type: 'object', + properties: { + title: { + type: 'string', + title: 'Event Title', + description: 'Name of the event', + minLength: 1 + }, + description: { + type: 'string', + title: 'Description', + description: 'Event description (optional)' + } + }, + required: ['title'] + } + }); + if (basicInfo.action !== 'accept' || !basicInfo.content) { + return { + content: [{ type: 'text', text: 'Event creation cancelled.' }] + }; + } + // Step 2: Collect date and time + const dateTime = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Step 2: Enter date and time', + requestedSchema: { + type: 'object', + properties: { + date: { + type: 'string', + title: 'Date', + description: 'Event date', + format: 'date' + }, + startTime: { + type: 'string', + title: 'Start Time', + description: 'Event start time (HH:MM)' + }, + duration: { + type: 'integer', + title: 'Duration', + description: 'Duration in minutes', + minimum: 15, + maximum: 480 + } + }, + required: ['date', 'startTime', 'duration'] + } + }); + if (dateTime.action !== 'accept' || !dateTime.content) { + return { + content: [{ type: 'text', text: 'Event creation cancelled.' }] + }; + } + // Combine all collected information + const event = { + ...basicInfo.content, + ...dateTime.content + }; + return { + content: [ + { + type: 'text', + text: `Event created successfully!\n\n${JSON.stringify(event, null, 2)}` + } + ] + }; + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Event creation failed: ${error instanceof Error ? error.message : String(error)}` + } + ], + isError: true + }; + } +}); +/** + * Example 3: Collecting address information + * Demonstrates validation with patterns and optional fields + */ +mcpServer.registerTool('update_shipping_address', { + description: 'Update shipping address with validation', + inputSchema: {} +}, async () => { + try { + const result = await mcpServer.server.elicitInput({ + mode: 'form', + message: 'Please provide your shipping address:', + requestedSchema: { + type: 'object', + properties: { + name: { + type: 'string', + title: 'Full Name', + description: 'Recipient name', + minLength: 1 + }, + street: { + type: 'string', + title: 'Street Address', + minLength: 1 + }, + city: { + type: 'string', + title: 'City', + minLength: 1 + }, + state: { + type: 'string', + title: 'State/Province', + minLength: 2, + maxLength: 2 + }, + zipCode: { + type: 'string', + title: 'ZIP/Postal Code', + description: '5-digit ZIP code' + }, + phone: { + type: 'string', + title: 'Phone Number (optional)', + description: 'Contact phone number' + } + }, + required: ['name', 'street', 'city', 'state', 'zipCode'] + } + }); + if (result.action === 'accept' && result.content) { + return { + content: [ + { + type: 'text', + text: `Address updated successfully!\n\n${JSON.stringify(result.content, null, 2)}` + } + ] + }; + } + else if (result.action === 'decline') { + return { + content: [{ type: 'text', text: 'Address update cancelled by user.' }] + }; + } + else { + return { + content: [{ type: 'text', text: 'Address update was cancelled.' }] + }; + } + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Address update failed: ${error instanceof Error ? error.message : String(error)}` + } + ], + isError: true + }; + } +}); +async function main() { + const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000; + const app = express(); + app.use(express.json()); + // Allow CORS for all domains, expose the Mcp-Session-Id header + app.use(cors({ + origin: '*', + exposedHeaders: ['Mcp-Session-Id'] + })); + // Map to store transports by session ID + const transports = {}; + // MCP POST endpoint + const mcpPostHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (sessionId) { + console.log(`Received MCP request for session: ${sessionId}`); + } + try { + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport for this session + transport = transports[sessionId]; + } + else if (!sessionId && isInitializeRequest(req.body)) { + // New initialization request - create new transport + transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + } + }; + // Connect the transport to the MCP server BEFORE handling the request + await mcpServer.connect(transport); + await transport.handleRequest(req, res, req.body); + return; + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } + }; + app.post('/mcp', mcpPostHandler); + // Handle GET requests for SSE streams + const mcpGetHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Establishing SSE stream for session ${sessionId}`); + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + }; + app.get('/mcp', mcpGetHandler); + // Handle DELETE requests for session termination + const mcpDeleteHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Received session termination request for session ${sessionId}`); + try { + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + } + catch (error) { + console.error('Error handling session termination:', error); + if (!res.headersSent) { + res.status(500).send('Error processing session termination'); + } + } + }; + app.delete('/mcp', mcpDeleteHandler); + // Start listening + app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Form elicitation example server is running on http://localhost:${PORT}/mcp`); + console.log('Available tools:'); + console.log(' - register_user: Collect user registration information'); + console.log(' - create_event: Multi-step event creation'); + console.log(' - update_shipping_address: Collect and validate address'); + console.log('\nConnect your MCP client to this server using the HTTP transport.'); + }); + // Handle server shutdown + process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); + }); +} +main().catch(error => { + console.error('Server error:', error); + process.exit(1); +}); +//# sourceMappingURL=elicitationFormExample.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationFormExample.js.map b/dist/esm/examples/server/elicitationFormExample.js.map new file mode 100644 index 0000000000..0a486154e0 --- /dev/null +++ b/dist/esm/examples/server/elicitationFormExample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationFormExample.js","sourceRoot":"","sources":["../../../../src/examples/server/elicitationFormExample.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,yFAAyF;AACzF,0EAA0E;AAC1E,2FAA2F;AAC3F,gCAAgC;AAChC,kFAAkF;AAClF,mDAAmD;AAEnD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,OAAwC,MAAM,SAAS,CAAC;AAC/D,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAErD,8FAA8F;AAC9F,2FAA2F;AAC3F,MAAM,SAAS,GAAG,IAAI,SAAS,CAC3B;IACI,IAAI,EAAE,iCAAiC;IACvC,OAAO,EAAE,OAAO;CACnB,EACD;IACI,YAAY,EAAE,EAAE;CACnB,CACJ,CAAC;AAEF;;;GAGG;AACH,SAAS,CAAC,YAAY,CAClB,eAAe,EACf;IACI,WAAW,EAAE,6DAA6D;IAC1E,WAAW,EAAE,EAAE;CAClB,EACD,KAAK,IAAI,EAAE;IACP,IAAI,CAAC;QACD,oDAAoD;QACpD,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,MAAM,CAAC,WAAW,CAAC;YAC9C,IAAI,EAAE,MAAM;YACZ,OAAO,EAAE,+CAA+C;YACxD,eAAe,EAAE;gBACb,IAAI,EAAE,QAAQ;gBACd,UAAU,EAAE;oBACR,QAAQ,EAAE;wBACN,IAAI,E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SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;YAC9E,CAAC;QACL,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;QACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationUrlExample.d.ts b/dist/esm/examples/server/elicitationUrlExample.d.ts new file mode 100644 index 0000000000..611f6eba22 --- /dev/null +++ b/dist/esm/examples/server/elicitationUrlExample.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=elicitationUrlExample.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationUrlExample.d.ts.map b/dist/esm/examples/server/elicitationUrlExample.d.ts.map new file mode 100644 index 0000000000..04acd6664d --- /dev/null +++ b/dist/esm/examples/server/elicitationUrlExample.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/elicitationUrlExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationUrlExample.js b/dist/esm/examples/server/elicitationUrlExample.js new file mode 100644 index 0000000000..c40b3084b0 --- /dev/null +++ b/dist/esm/examples/server/elicitationUrlExample.js @@ -0,0 +1,650 @@ +// Run with: npx tsx src/examples/server/elicitationUrlExample.ts +// +// This example demonstrates how to use URL elicitation to securely collect +// *sensitive* user input in a remote (HTTP) server. +// URL elicitation allows servers to prompt the end-user to open a URL in their browser +// to collect sensitive information. +// Note: See also elicitationFormExample.ts for an example of using form (not URL) elicitation +// to collect *non-sensitive* user input with a structured schema. +import express from 'express'; +import { randomUUID } from 'node:crypto'; +import { z } from 'zod'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { getOAuthProtectedResourceMetadataUrl, mcpAuthMetadataRouter } from '../../server/auth/router.js'; +import { requireBearerAuth } from '../../server/auth/middleware/bearerAuth.js'; +import { UrlElicitationRequiredError, isInitializeRequest } from '../../types.js'; +import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; +import { setupAuthServer } from './demoInMemoryOAuthProvider.js'; +import { checkResourceAllowed } from '../../shared/auth-utils.js'; +import cors from 'cors'; +// Create an MCP server with implementation details +const getServer = () => { + const mcpServer = new McpServer({ + name: 'url-elicitation-http-server', + version: '1.0.0' + }, { + capabilities: { logging: {} } + }); + mcpServer.registerTool('payment-confirm', { + description: 'A tool that confirms a payment directly with a user', + inputSchema: { + cartId: z.string().describe('The ID of the cart to confirm') + } + }, async ({ cartId }, extra) => { + /* + In a real world scenario, there would be some logic here to check if the user has the provided cartId. + For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to confirm payment) + */ + const sessionId = extra.sessionId; + if (!sessionId) { + throw new Error('Expected a Session ID'); + } + // Create and track the elicitation + const elicitationId = generateTrackedElicitation(sessionId, elicitationId => mcpServer.server.createElicitationCompletionNotifier(elicitationId)); + throw new UrlElicitationRequiredError([ + { + mode: 'url', + message: 'This tool requires a payment confirmation. Open the link to confirm payment!', + url: `http://localhost:${MCP_PORT}/confirm-payment?session=${sessionId}&elicitation=${elicitationId}&cartId=${encodeURIComponent(cartId)}`, + elicitationId + } + ]); + }); + mcpServer.registerTool('third-party-auth', { + description: 'A demo tool that requires third-party OAuth credentials', + inputSchema: { + param1: z.string().describe('First parameter') + } + }, async (_, extra) => { + /* + In a real world scenario, there would be some logic here to check if we already have a valid access token for the user. + Auth info (with a subject or `sub` claim) can be typically be found in `extra.authInfo`. + If we do, we can just return the result of the tool call. + If we don't, we can throw an ElicitationRequiredError to request the user to authenticate. + For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to authenticate). + */ + const sessionId = extra.sessionId; + if (!sessionId) { + throw new Error('Expected a Session ID'); + } + // Create and track the elicitation + const elicitationId = generateTrackedElicitation(sessionId, elicitationId => mcpServer.server.createElicitationCompletionNotifier(elicitationId)); + // Simulate OAuth callback and token exchange after 5 seconds + // In a real app, this would be called from your OAuth callback handler + setTimeout(() => { + console.log(`Simulating OAuth token received for elicitation ${elicitationId}`); + completeURLElicitation(elicitationId); + }, 5000); + throw new UrlElicitationRequiredError([ + { + mode: 'url', + message: 'This tool requires access to your example.com account. Open the link to authenticate!', + url: 'https://www.example.com/oauth/authorize', + elicitationId + } + ]); + }); + return mcpServer; +}; +const elicitationsMap = new Map(); +// Clean up old elicitations after 1 hour to prevent memory leaks +const ELICITATION_TTL_MS = 60 * 60 * 1000; // 1 hour +const CLEANUP_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes +function cleanupOldElicitations() { + const now = new Date(); + for (const [id, metadata] of elicitationsMap.entries()) { + if (now.getTime() - metadata.createdAt.getTime() > ELICITATION_TTL_MS) { + elicitationsMap.delete(id); + console.log(`Cleaned up expired elicitation: ${id}`); + } + } +} +setInterval(cleanupOldElicitations, CLEANUP_INTERVAL_MS); +/** + * Elicitation IDs must be unique strings within the MCP session + * UUIDs are used in this example for simplicity + */ +function generateElicitationId() { + return randomUUID(); +} +/** + * Helper function to create and track a new elicitation. + */ +function generateTrackedElicitation(sessionId, createCompletionNotifier) { + const elicitationId = generateElicitationId(); + // Create a Promise and its resolver for tracking completion + let completeResolver; + const completedPromise = new Promise(resolve => { + completeResolver = resolve; + }); + const completionNotifier = createCompletionNotifier ? createCompletionNotifier(elicitationId) : undefined; + // Store the elicitation in our map + elicitationsMap.set(elicitationId, { + status: 'pending', + completedPromise, + completeResolver: completeResolver, + createdAt: new Date(), + sessionId, + completionNotifier + }); + return elicitationId; +} +/** + * Helper function to complete an elicitation. + */ +function completeURLElicitation(elicitationId) { + const elicitation = elicitationsMap.get(elicitationId); + if (!elicitation) { + console.warn(`Attempted to complete unknown elicitation: ${elicitationId}`); + return; + } + if (elicitation.status === 'complete') { + console.warn(`Elicitation already complete: ${elicitationId}`); + return; + } + // Update metadata + elicitation.status = 'complete'; + // Send completion notification to the client + if (elicitation.completionNotifier) { + console.log(`Sending notifications/elicitation/complete notification for elicitation ${elicitationId}`); + elicitation.completionNotifier().catch(error => { + console.error(`Failed to send completion notification for elicitation ${elicitationId}:`, error); + }); + } + // Resolve the promise to unblock any waiting code + elicitation.completeResolver(); +} +const MCP_PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; +const AUTH_PORT = process.env.MCP_AUTH_PORT ? parseInt(process.env.MCP_AUTH_PORT, 10) : 3001; +const app = express(); +app.use(express.json()); +// Allow CORS all domains, expose the Mcp-Session-Id header +app.use(cors({ + origin: '*', // Allow all origins + exposedHeaders: ['Mcp-Session-Id'], + credentials: true // Allow cookies to be sent cross-origin +})); +// Set up OAuth (required for this example) +let authMiddleware = null; +// Create auth middleware for MCP endpoints +const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`); +const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); +const oauthMetadata = setupAuthServer({ authServerUrl, mcpServerUrl, strictResource: true }); +const tokenVerifier = { + verifyAccessToken: async (token) => { + const endpoint = oauthMetadata.introspection_endpoint; + if (!endpoint) { + throw new Error('No token verification endpoint available in metadata'); + } + const response = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: new URLSearchParams({ + token: token + }).toString() + }); + if (!response.ok) { + throw new Error(`Invalid or expired token: ${await response.text()}`); + } + const data = await response.json(); + if (!data.aud) { + throw new Error(`Resource Indicator (RFC8707) missing`); + } + if (!checkResourceAllowed({ requestedResource: data.aud, configuredResource: mcpServerUrl })) { + throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); + } + // Convert the response to AuthInfo format + return { + token, + clientId: data.client_id, + scopes: data.scope ? data.scope.split(' ') : [], + expiresAt: data.exp + }; + } +}; +// Add metadata routes to the main MCP server +app.use(mcpAuthMetadataRouter({ + oauthMetadata, + resourceServerUrl: mcpServerUrl, + scopesSupported: ['mcp:tools'], + resourceName: 'MCP Demo Server' +})); +authMiddleware = requireBearerAuth({ + verifier: tokenVerifier, + requiredScopes: [], + resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl) +}); +/** + * API Key Form Handling + * + * Many servers today require an API key to operate, but there's no scalable way to do this dynamically for remote servers within MCP protocol. + * URL-mode elicitation enables the server to host a simple form and get the secret data securely from the user without involving the LLM or client. + **/ +async function sendApiKeyElicitation(sessionId, sender, createCompletionNotifier) { + if (!sessionId) { + console.error('No session ID provided'); + throw new Error('Expected a Session ID to track elicitation'); + } + console.log('🔑 URL elicitation demo: Requesting API key from client...'); + const elicitationId = generateTrackedElicitation(sessionId, createCompletionNotifier); + try { + const result = await sender({ + mode: 'url', + message: 'Please provide your API key to authenticate with this server', + // Host the form on the same server. In a real app, you might coordinate passing these state variables differently. + url: `http://localhost:${MCP_PORT}/api-key-form?session=${sessionId}&elicitation=${elicitationId}`, + elicitationId + }); + switch (result.action) { + case 'accept': + console.log('🔑 URL elicitation demo: Client accepted the API key elicitation (now pending form submission)'); + // Wait for the API key to be submitted via the form + // The form submission will complete the elicitation + break; + default: + console.log('🔑 URL elicitation demo: Client declined to provide an API key'); + // In a real app, this might close the connection, but for the demo, we'll continue + break; + } + } + catch (error) { + console.error('Error during API key elicitation:', error); + } +} +// API Key Form endpoint - serves a simple HTML form +app.get('/api-key-form', (req, res) => { + const mcpSessionId = req.query.session; + const elicitationId = req.query.elicitation; + if (!mcpSessionId || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie + // In production, this is often handled by some user auth middleware to ensure the user has a valid session + // This session is different from the MCP session. + // This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in. + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + // Serve a simple HTML form + res.send(` + + + + Submit Your API Key + + + +

API Key Required

+
✓ Logged in as: ${userSession.name}
+
+ + + + +
+
This is a demo showing how a server can securely elicit sensitive data from a user using a URL.
+ + + `); +}); +// Handle API key form submission +app.post('/api-key-form', express.urlencoded(), (req, res) => { + const { session: sessionId, apiKey, elicitation: elicitationId } = req.body; + if (!sessionId || !apiKey || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie here too + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + // A real app might store this API key to be used later for the user. + console.log(`🔑 Received API key \x1b[32m${apiKey}\x1b[0m for session ${sessionId}`); + // If we have an elicitationId, complete the elicitation + completeURLElicitation(elicitationId); + // Send a success response + res.send(` + + + + Success + + + +
+

Success ✓

+

API key received.

+
+

You can close this window and return to your MCP client.

+ + + `); +}); +// Helper to get the user session from the demo_session cookie +function getUserSessionCookie(cookieHeader) { + if (!cookieHeader) + return null; + const cookies = cookieHeader.split(';'); + for (const cookie of cookies) { + const [name, value] = cookie.trim().split('='); + if (name === 'demo_session' && value) { + try { + return JSON.parse(decodeURIComponent(value)); + } + catch (error) { + console.error('Failed to parse demo_session cookie:', error); + return null; + } + } + } + return null; +} +/** + * Payment Confirmation Form Handling + * + * This demonstrates how a server can use URL-mode elicitation to get user confirmation + * for sensitive operations like payment processing. + **/ +// Payment Confirmation Form endpoint - serves a simple HTML form +app.get('/confirm-payment', (req, res) => { + const mcpSessionId = req.query.session; + const elicitationId = req.query.elicitation; + const cartId = req.query.cartId; + if (!mcpSessionId || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie + // In production, this is often handled by some user auth middleware to ensure the user has a valid session + // This session is different from the MCP session. + // This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in. + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + // Serve a simple HTML form + res.send(` + + + + Confirm Payment + + + +

Confirm Payment

+
✓ Logged in as: ${userSession.name}
+ ${cartId ? `
Cart ID: ${cartId}
` : ''} +
+ ⚠️ Please review your order before confirming. +
+
+ + + ${cartId ? `` : ''} + + +
+
This is a demo showing how a server can securely get user confirmation for sensitive operations using URL-mode elicitation.
+ + + `); +}); +// Handle Payment Confirmation form submission +app.post('/confirm-payment', express.urlencoded(), (req, res) => { + const { session: sessionId, elicitation: elicitationId, cartId, action } = req.body; + if (!sessionId || !elicitationId) { + res.status(400).send('

Error

Missing required parameters

'); + return; + } + // Check for user session cookie here too + const userSession = getUserSessionCookie(req.headers.cookie); + if (!userSession) { + res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); + return; + } + if (action === 'confirm') { + // A real app would process the payment here + console.log(`💳 Payment confirmed for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`); + // Complete the elicitation + completeURLElicitation(elicitationId); + // Send a success response + res.send(` + + + + Payment Confirmed + + + +
+

Payment Confirmed ✓

+

Your payment has been successfully processed.

+ ${cartId ? `

Cart ID: ${cartId}

` : ''} +
+

You can close this window and return to your MCP client.

+ + + `); + } + else if (action === 'cancel') { + console.log(`💳 Payment cancelled for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`); + // The client will still receive a notifications/elicitation/complete notification, + // which indicates that the out-of-band interaction is complete (but not necessarily successful) + completeURLElicitation(elicitationId); + res.send(` + + + + Payment Cancelled + + + +
+

Payment Cancelled

+

Your payment has been cancelled.

+
+

You can close this window and return to your MCP client.

+ + + `); + } + else { + res.status(400).send('

Error

Invalid action

'); + } +}); +// Map to store transports by session ID +const transports = {}; +const sessionsNeedingElicitation = {}; +// MCP POST endpoint +const mcpPostHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + console.debug(`Received MCP POST for session: ${sessionId || 'unknown'}`); + try { + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && isInitializeRequest(req.body)) { + const server = getServer(); + // New initialization request + const eventStore = new InMemoryEventStore(); + transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + eventStore, // Enable resumability + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + sessionsNeedingElicitation[sessionId] = { + elicitationSender: params => server.server.elicitInput(params), + createCompletionNotifier: elicitationId => server.server.createElicitationCompletionNotifier(elicitationId) + }; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + delete sessionsNeedingElicitation[sid]; + } + }; + // Connect the transport to the MCP server BEFORE handling the request + // so responses can flow back through the same transport + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport - no need to reconnect + // The existing transport is already connected to the server + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}; +// Set up routes with auth middleware +app.post('/mcp', authMiddleware, mcpPostHandler); +// Handle GET requests for SSE streams (using built-in support from StreamableHTTP) +const mcpGetHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + // Check for Last-Event-ID header for resumability + const lastEventId = req.headers['last-event-id']; + if (lastEventId) { + console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`); + } + else { + console.log(`Establishing new SSE stream for session ${sessionId}`); + } + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + if (sessionsNeedingElicitation[sessionId]) { + const { elicitationSender, createCompletionNotifier } = sessionsNeedingElicitation[sessionId]; + // Send an elicitation request to the client in the background + sendApiKeyElicitation(sessionId, elicitationSender, createCompletionNotifier) + .then(() => { + // Only delete on successful send for this demo + delete sessionsNeedingElicitation[sessionId]; + console.log(`🔑 URL elicitation demo: Finished sending API key elicitation request for session ${sessionId}`); + }) + .catch(error => { + console.error('Error sending API key elicitation:', error); + // Keep in map to potentially retry on next reconnect + }); + } +}; +// Set up GET route with conditional auth middleware +app.get('/mcp', authMiddleware, mcpGetHandler); +// Handle DELETE requests for session termination (according to MCP spec) +const mcpDeleteHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Received session termination request for session ${sessionId}`); + try { + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + } + catch (error) { + console.error('Error handling session termination:', error); + if (!res.headersSent) { + res.status(500).send('Error processing session termination'); + } + } +}; +// Set up DELETE route with auth middleware +app.delete('/mcp', authMiddleware, mcpDeleteHandler); +app.listen(MCP_PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Streamable HTTP Server listening on port ${MCP_PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + delete sessionsNeedingElicitation[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=elicitationUrlExample.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationUrlExample.js.map b/dist/esm/examples/server/elicitationUrlExample.js.map new file mode 100644 index 0000000000..bb8d75b8fd --- /dev/null +++ b/dist/esm/examples/server/elicitationUrlExample.js.map @@ -0,0 +1 @@ +{"version":3,"file":"elicitationUrlExample.js","sourceRoot":"","sources":["../../../../src/examples/server/elicitationUrlExample.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,EAAE;AACF,2EAA2E;AAC3E,oDAAoD;AACpD,uFAAuF;AACvF,oCAAoC;AACpC,8FAA8F;AAC9F,kEAAkE;AAElE,OAAO,OAA8B,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,oCAAoC,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAC1G,OAAO,EAAE,iBAAiB,EAAE,MAAM,4CAA4C,CAAC;AAC/E,OAAO,EAAkB,2BAA2B,EAAwC,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACxI,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAEjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAElE,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,mDAAmD;AACnD,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,SAAS,GAAG,IAAI,SAAS,CAC3B;QACI,IAAI,EAAE,6BAA6B;QACnC,OAAO,EAAE,OAAO;KACnB,EACD;QACI,YAAY,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE;KAChC,CACJ,CAAC;IAEF,SAAS,CAAC,YAAY,CAClB,iBAAiB,EACjB;QACI,WAAW,EAAE,qDAAqD;QAClE,WAAW,EAAE;YACT,MAAM,EAAE,CAAC,CAA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AAE,KAAK,CAAC,EAAE;IACzB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,gDAAgD,QAAQ,EAAE,CAAC,CAAC;AAC5E,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAEvC,6DAA6D;IAC7D,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACjC,IAAI,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,iCAAiC,SAAS,EAAE,CAAC,CAAC;YAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;YAC7B,OAAO,0BAA0B,CAAC,SAAS,CAAC,CAAC;QACjD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts b/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts new file mode 100644 index 0000000000..477fa6bae7 --- /dev/null +++ b/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=jsonResponseStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts.map b/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts.map new file mode 100644 index 0000000000..ee8117ee2e --- /dev/null +++ b/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonResponseStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/jsonResponseStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/jsonResponseStreamableHttp.js b/dist/esm/examples/server/jsonResponseStreamableHttp.js new file mode 100644 index 0000000000..f9bd04d87b --- /dev/null +++ b/dist/esm/examples/server/jsonResponseStreamableHttp.js @@ -0,0 +1,147 @@ +import express from 'express'; +import { randomUUID } from 'node:crypto'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import * as z from 'zod/v4'; +import { isInitializeRequest } from '../../types.js'; +import cors from 'cors'; +// Create an MCP server with implementation details +const getServer = () => { + const server = new McpServer({ + name: 'json-response-streamable-http-server', + version: '1.0.0' + }, { + capabilities: { + logging: {} + } + }); + // Register a simple tool that returns a greeting + server.tool('greet', 'A simple greeting tool', { + name: z.string().describe('Name to greet') + }, async ({ name }) => { + return { + content: [ + { + type: 'text', + text: `Hello, ${name}!` + } + ] + }; + }); + // Register a tool that sends multiple greetings with notifications + server.tool('multi-greet', 'A tool that sends different greetings with delays between them', { + name: z.string().describe('Name to greet') + }, async ({ name }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + await server.sendLoggingMessage({ + level: 'debug', + data: `Starting multi-greet for ${name}` + }, extra.sessionId); + await sleep(1000); // Wait 1 second before first greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending first greeting to ${name}` + }, extra.sessionId); + await sleep(1000); // Wait another second before second greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending second greeting to ${name}` + }, extra.sessionId); + return { + content: [ + { + type: 'text', + text: `Good morning, ${name}!` + } + ] + }; + }); + return server; +}; +const app = express(); +app.use(express.json()); +// Configure CORS to expose Mcp-Session-Id header for browser-based clients +app.use(cors({ + origin: '*', // Allow all origins - adjust as needed for production + exposedHeaders: ['Mcp-Session-Id'] +})); +// Map to store transports by session ID +const transports = {}; +app.post('/mcp', async (req, res) => { + console.log('Received MCP request:', req.body); + try { + // Check for existing session ID + const sessionId = req.headers['mcp-session-id']; + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && isInitializeRequest(req.body)) { + // New initialization request - use JSON response mode + transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + enableJsonResponse: true, // Enable JSON response mode + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Connect the transport to the MCP server BEFORE handling the request + const server = getServer(); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport - no need to reconnect + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +// Handle GET requests for SSE streams according to spec +app.get('/mcp', async (req, res) => { + // Since this is a very simple example, we don't support GET requests for this server + // The spec requires returning 405 Method Not Allowed in this case + res.status(405).set('Allow', 'POST').send('Method Not Allowed'); +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Streamable HTTP Server listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + process.exit(0); +}); +//# sourceMappingURL=jsonResponseStreamableHttp.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/jsonResponseStreamableHttp.js.map b/dist/esm/examples/server/jsonResponseStreamableHttp.js.map new file mode 100644 index 0000000000..67ae23baa7 --- /dev/null +++ b/dist/esm/examples/server/jsonResponseStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jsonResponseStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/jsonResponseStreamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,OAA8B,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAkB,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,mDAAmD;AACnD,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,GAAG,IAAI,SAAS,CACxB;QACI,IAAI,EAAE,sCAAsC;QAC5C,OAAO,EAAE,OAAO;KACnB,EACD;QACI,YAAY,EAAE;YACV,OAAO,EAAE,EAAE;SACd;KACJ,CACJ,CAAC;IAEF,iDAAiD;IACjD,MAAM,CAAC,IAAI,CACP,OAAO,EACP,wBAAwB,EACxB;QACI,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,eAAe,CAAC;KAC7C,EACD,KAAK,EAAE,EAAE,IAAI,EAAE,EAA2B,EAAE;QACxC,OAAO;YACH,OAAO,EAAE;gBACL;oBACI,IAAI,EAAE,MAAM;oBACZ,IAAI,EAAE,UAAU,IAAI,GAAG;iBAC1B;aACJ;SACJ,CAAC;IACN,CAAC,CACJ,CAAC;IAEF,mEAAmE;IACnE,MAAM,CAAC,IAAI,CACP,aAAa,EACb,gEAAgE,EAChE;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,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,gDAAgD,IAAI,EAAE,CAAC,CAAC;AACxE,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/mcpServerOutputSchema.d.ts b/dist/esm/examples/server/mcpServerOutputSchema.d.ts new file mode 100644 index 0000000000..a6cb497473 --- /dev/null +++ b/dist/esm/examples/server/mcpServerOutputSchema.d.ts @@ -0,0 +1,7 @@ +#!/usr/bin/env node +/** + * Example MCP server using the high-level McpServer API with outputSchema + * This demonstrates how to easily create tools with structured output + */ +export {}; +//# sourceMappingURL=mcpServerOutputSchema.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/mcpServerOutputSchema.d.ts.map b/dist/esm/examples/server/mcpServerOutputSchema.d.ts.map new file mode 100644 index 0000000000..bd3abdcc26 --- /dev/null +++ b/dist/esm/examples/server/mcpServerOutputSchema.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mcpServerOutputSchema.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/mcpServerOutputSchema.ts"],"names":[],"mappings":";AACA;;;GAGG"} \ No newline at end of file diff --git a/dist/esm/examples/server/mcpServerOutputSchema.js b/dist/esm/examples/server/mcpServerOutputSchema.js new file mode 100644 index 0000000000..17b52b73e5 --- /dev/null +++ b/dist/esm/examples/server/mcpServerOutputSchema.js @@ -0,0 +1,70 @@ +#!/usr/bin/env node +/** + * Example MCP server using the high-level McpServer API with outputSchema + * This demonstrates how to easily create tools with structured output + */ +import { McpServer } from '../../server/mcp.js'; +import { StdioServerTransport } from '../../server/stdio.js'; +import * as z from 'zod/v4'; +const server = new McpServer({ + name: 'mcp-output-schema-high-level-example', + version: '1.0.0' +}); +// Define a tool with structured output - Weather data +server.registerTool('get_weather', { + description: 'Get weather information for a city', + inputSchema: { + city: z.string().describe('City name'), + country: z.string().describe('Country code (e.g., US, UK)') + }, + outputSchema: { + temperature: z.object({ + celsius: z.number(), + fahrenheit: z.number() + }), + conditions: z.enum(['sunny', 'cloudy', 'rainy', 'stormy', 'snowy']), + humidity: z.number().min(0).max(100), + wind: z.object({ + speed_kmh: z.number(), + direction: z.string() + }) + } +}, async ({ city, country }) => { + // Parameters are available but not used in this example + void city; + void country; + // Simulate weather API call + const temp_c = Math.round((Math.random() * 35 - 5) * 10) / 10; + const conditions = ['sunny', 'cloudy', 'rainy', 'stormy', 'snowy'][Math.floor(Math.random() * 5)]; + const structuredContent = { + temperature: { + celsius: temp_c, + fahrenheit: Math.round(((temp_c * 9) / 5 + 32) * 10) / 10 + }, + conditions, + humidity: Math.round(Math.random() * 100), + wind: { + speed_kmh: Math.round(Math.random() * 50), + direction: ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'][Math.floor(Math.random() * 8)] + } + }; + return { + content: [ + { + type: 'text', + text: JSON.stringify(structuredContent, null, 2) + } + ], + structuredContent + }; +}); +async function main() { + const transport = new StdioServerTransport(); + await server.connect(transport); + console.error('High-level Output Schema Example Server running on stdio'); +} +main().catch(error => { + console.error('Server error:', error); + process.exit(1); +}); +//# sourceMappingURL=mcpServerOutputSchema.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/mcpServerOutputSchema.js.map b/dist/esm/examples/server/mcpServerOutputSchema.js.map new file mode 100644 index 0000000000..b932b856b6 --- /dev/null +++ b/dist/esm/examples/server/mcpServerOutputSchema.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mcpServerOutputSchema.js","sourceRoot":"","sources":["../../../../src/examples/server/mcpServerOutputSchema.ts"],"names":[],"mappings":";AACA;;;GAGG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM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9E,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/simpleSseServer.d.ts b/dist/esm/examples/server/simpleSseServer.d.ts new file mode 100644 index 0000000000..4269b7814f --- /dev/null +++ b/dist/esm/examples/server/simpleSseServer.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleSseServer.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/simpleSseServer.d.ts.map b/dist/esm/examples/server/simpleSseServer.d.ts.map new file mode 100644 index 0000000000..08a1b45021 --- /dev/null +++ b/dist/esm/examples/server/simpleSseServer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleSseServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleSseServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/simpleSseServer.js b/dist/esm/examples/server/simpleSseServer.js new file mode 100644 index 0000000000..21e8ef96ba --- /dev/null +++ b/dist/esm/examples/server/simpleSseServer.js @@ -0,0 +1,141 @@ +import express from 'express'; +import { McpServer } from '../../server/mcp.js'; +import { SSEServerTransport } from '../../server/sse.js'; +import * as z from 'zod/v4'; +/** + * This example server demonstrates the deprecated HTTP+SSE transport + * (protocol version 2024-11-05). It mainly used for testing backward compatible clients. + * + * The server exposes two endpoints: + * - /mcp: For establishing the SSE stream (GET) + * - /messages: For receiving client messages (POST) + * + */ +// Create an MCP server instance +const getServer = () => { + const server = new McpServer({ + name: 'simple-sse-server', + version: '1.0.0' + }, { capabilities: { logging: {} } }); + server.tool('start-notification-stream', 'Starts sending periodic notifications', { + interval: z.number().describe('Interval in milliseconds between notifications').default(1000), + count: z.number().describe('Number of notifications to send').default(10) + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + // Send the initial notification + await server.sendLoggingMessage({ + level: 'info', + data: `Starting notification stream with ${count} messages every ${interval}ms` + }, extra.sessionId); + // Send periodic notifications + while (counter < count) { + counter++; + await sleep(interval); + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + } + return { + content: [ + { + type: 'text', + text: `Completed sending ${count} notifications every ${interval}ms` + } + ] + }; + }); + return server; +}; +const app = express(); +app.use(express.json()); +// Store transports by session ID +const transports = {}; +// SSE endpoint for establishing the stream +app.get('/mcp', async (req, res) => { + console.log('Received GET request to /sse (establishing SSE stream)'); + try { + // Create a new SSE transport for the client + // The endpoint for POST messages is '/messages' + const transport = new SSEServerTransport('/messages', res); + // Store the transport by session ID + const sessionId = transport.sessionId; + transports[sessionId] = transport; + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + console.log(`SSE transport closed for session ${sessionId}`); + delete transports[sessionId]; + }; + // Connect the transport to the MCP server + const server = getServer(); + await server.connect(transport); + console.log(`Established SSE stream with session ID: ${sessionId}`); + } + catch (error) { + console.error('Error establishing SSE stream:', error); + if (!res.headersSent) { + res.status(500).send('Error establishing SSE stream'); + } + } +}); +// Messages endpoint for receiving client JSON-RPC requests +app.post('/messages', async (req, res) => { + console.log('Received POST request to /messages'); + // Extract session ID from URL query parameter + // In the SSE protocol, this is added by the client based on the endpoint event + const sessionId = req.query.sessionId; + if (!sessionId) { + console.error('No session ID provided in request URL'); + res.status(400).send('Missing sessionId parameter'); + return; + } + const transport = transports[sessionId]; + if (!transport) { + console.error(`No active transport found for session ID: ${sessionId}`); + res.status(404).send('Session not found'); + return; + } + try { + // Handle the POST message with the transport + await transport.handlePostMessage(req, res, req.body); + } + catch (error) { + console.error('Error handling request:', error); + if (!res.headersSent) { + res.status(500).send('Error handling request'); + } + } +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Simple SSE Server (deprecated protocol version 2024-11-05) listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=simpleSseServer.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/simpleSseServer.js.map b/dist/esm/examples/server/simpleSseServer.js.map new file mode 100644 index 0000000000..4ac49a2326 --- /dev/null +++ b/dist/esm/examples/server/simpleSseServer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleSseServer.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleSseServer.ts"],"names":[],"mappings":"AAAA,OAAO,OAA8B,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAG5B;;;;;;;;GAQG;AAEH,gCAAgC;AAChC,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,GAAG,IAAI,SAAS,CACxB;QACI,IAAI,EAAE,mBAAmB;QACzB,OAAO,EAAE,OAAO;KACnB,EACD,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,CACpC,CAAC;IAEF,MAAM,CAAC,IAAI,CACP,2BAA2B,EAC3B,uCAAuC,EACvC;QACI,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,gDAAgD,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC;QAC7F,KAAK,EAAE,CAAC,CAAC,MAAM,EA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C;IACD,OAAO,CAAC,GAAG,CAAC,gFAAgF,IAAI,EAAE,CAAC,CAAC;AACxG,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAEvC,6DAA6D;IAC7D,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACjC,IAAI,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,iCAAiC,SAAS,EAAE,CAAC,CAAC;YAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts b/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts new file mode 100644 index 0000000000..0aa4ad2439 --- /dev/null +++ b/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleStatelessStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts.map b/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts.map new file mode 100644 index 0000000000..92deb06ecb --- /dev/null +++ b/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStatelessStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleStatelessStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStatelessStreamableHttp.js b/dist/esm/examples/server/simpleStatelessStreamableHttp.js new file mode 100644 index 0000000000..d9e24a1d0a --- /dev/null +++ b/dist/esm/examples/server/simpleStatelessStreamableHttp.js @@ -0,0 +1,142 @@ +import express from 'express'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import * as z from 'zod/v4'; +import cors from 'cors'; +const getServer = () => { + // Create an MCP server with implementation details + const server = new McpServer({ + name: 'stateless-streamable-http-server', + version: '1.0.0' + }, { capabilities: { logging: {} } }); + // Register a simple prompt + server.prompt('greeting-template', 'A simple greeting prompt template', { + name: z.string().describe('Name to include in greeting') + }, async ({ name }) => { + return { + messages: [ + { + role: 'user', + content: { + type: 'text', + text: `Please greet ${name} in a friendly manner.` + } + } + ] + }; + }); + // Register a tool specifically for testing resumability + server.tool('start-notification-stream', 'Starts sending periodic notifications for testing resumability', { + interval: z.number().describe('Interval in milliseconds between notifications').default(100), + count: z.number().describe('Number of notifications to send (0 for 100)').default(10) + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + while (count === 0 || counter < count) { + counter++; + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Periodic notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + // Wait for the specified interval + await sleep(interval); + } + return { + content: [ + { + type: 'text', + text: `Started sending periodic notifications every ${interval}ms` + } + ] + }; + }); + // Create a simple resource at a fixed URI + server.resource('greeting-resource', 'https://example.com/greetings/default', { mimeType: 'text/plain' }, async () => { + return { + contents: [ + { + uri: 'https://example.com/greetings/default', + text: 'Hello, world!' + } + ] + }; + }); + return server; +}; +const app = express(); +app.use(express.json()); +// Configure CORS to expose Mcp-Session-Id header for browser-based clients +app.use(cors({ + origin: '*', // Allow all origins - adjust as needed for production + exposedHeaders: ['Mcp-Session-Id'] +})); +app.post('/mcp', async (req, res) => { + const server = getServer(); + try { + const transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: undefined + }); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + res.on('close', () => { + console.log('Request closed'); + transport.close(); + server.close(); + }); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +app.get('/mcp', async (req, res) => { + console.log('Received GET MCP request'); + res.writeHead(405).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Method not allowed.' + }, + id: null + })); +}); +app.delete('/mcp', async (req, res) => { + console.log('Received DELETE MCP request'); + res.writeHead(405).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Method not allowed.' + }, + id: null + })); +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Stateless Streamable HTTP Server listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + process.exit(0); +}); +//# sourceMappingURL=simpleStatelessStreamableHttp.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStatelessStreamableHttp.js.map b/dist/esm/examples/server/simpleStatelessStreamableHttp.js.map new file mode 100644 index 0000000000..4963fadc1b --- /dev/null +++ b/dist/esm/examples/server/simpleStatelessStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStatelessStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleStatelessStreamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,OAA8B,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,KAAK,CAAC,MA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AAK;YACZ,OAAO,EAAE,qBAAqB;SACjC;QACD,EAAE,EAAE,IAAI;KACX,CAAC,CACL,CAAC;AACN,CAAC,CAAC,CAAC;AAEH,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,EAAE;IACrD,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAC3C,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,CAClB,IAAI,CAAC,SAAS,CAAC;QACX,OAAO,EAAE,KAAK;QACd,KAAK,EAAE;YACH,IAAI,EAAE,CAAC,KAAK;YACZ,OAAO,EAAE,qBAAqB;SACjC;QACD,EAAE,EAAE,IAAI;KACX,CAAC,CACL,CAAC;AACN,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0DAA0D,IAAI,EAAE,CAAC,CAAC;AAClF,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStreamableHttp.d.ts b/dist/esm/examples/server/simpleStreamableHttp.d.ts new file mode 100644 index 0000000000..a20be42ca4 --- /dev/null +++ b/dist/esm/examples/server/simpleStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=simpleStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStreamableHttp.d.ts.map b/dist/esm/examples/server/simpleStreamableHttp.d.ts.map new file mode 100644 index 0000000000..e3cf042241 --- /dev/null +++ b/dist/esm/examples/server/simpleStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"simpleStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStreamableHttp.js b/dist/esm/examples/server/simpleStreamableHttp.js new file mode 100644 index 0000000000..0af6b16b6b --- /dev/null +++ b/dist/esm/examples/server/simpleStreamableHttp.js @@ -0,0 +1,583 @@ +import express from 'express'; +import { randomUUID } from 'node:crypto'; +import * as z from 'zod/v4'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { getOAuthProtectedResourceMetadataUrl, mcpAuthMetadataRouter } from '../../server/auth/router.js'; +import { requireBearerAuth } from '../../server/auth/middleware/bearerAuth.js'; +import { isInitializeRequest } from '../../types.js'; +import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; +import { setupAuthServer } from './demoInMemoryOAuthProvider.js'; +import { checkResourceAllowed } from '../../shared/auth-utils.js'; +import cors from 'cors'; +// Check for OAuth flag +const useOAuth = process.argv.includes('--oauth'); +const strictOAuth = process.argv.includes('--oauth-strict'); +// Create an MCP server with implementation details +const getServer = () => { + const server = new McpServer({ + name: 'simple-streamable-http-server', + version: '1.0.0', + icons: [{ src: './mcp.svg', sizes: ['512x512'], mimeType: 'image/svg+xml' }], + websiteUrl: 'https://github.com/modelcontextprotocol/typescript-sdk' + }, { capabilities: { logging: {} } }); + // Register a simple tool that returns a greeting + server.registerTool('greet', { + title: 'Greeting Tool', // Display name for UI + description: 'A simple greeting tool', + inputSchema: { + name: z.string().describe('Name to greet') + } + }, async ({ name }) => { + return { + content: [ + { + type: 'text', + text: `Hello, ${name}!` + } + ] + }; + }); + // Register a tool that sends multiple greetings with notifications (with annotations) + server.tool('multi-greet', 'A tool that sends different greetings with delays between them', { + name: z.string().describe('Name to greet') + }, { + title: 'Multiple Greeting Tool', + readOnlyHint: true, + openWorldHint: false + }, async ({ name }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + await server.sendLoggingMessage({ + level: 'debug', + data: `Starting multi-greet for ${name}` + }, extra.sessionId); + await sleep(1000); // Wait 1 second before first greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending first greeting to ${name}` + }, extra.sessionId); + await sleep(1000); // Wait another second before second greeting + await server.sendLoggingMessage({ + level: 'info', + data: `Sending second greeting to ${name}` + }, extra.sessionId); + return { + content: [ + { + type: 'text', + text: `Good morning, ${name}!` + } + ] + }; + }); + // Register a tool that demonstrates form elicitation (user input collection with a schema) + // This creates a closure that captures the server instance + server.tool('collect-user-info', 'A tool that collects user information through form elicitation', { + infoType: z.enum(['contact', 'preferences', 'feedback']).describe('Type of information to collect') + }, async ({ infoType }) => { + let message; + let requestedSchema; + switch (infoType) { + case 'contact': + message = 'Please provide your contact information'; + requestedSchema = { + type: 'object', + properties: { + name: { + type: 'string', + title: 'Full Name', + description: 'Your full name' + }, + email: { + type: 'string', + title: 'Email Address', + description: 'Your email address', + format: 'email' + }, + phone: { + type: 'string', + title: 'Phone Number', + description: 'Your phone number (optional)' + } + }, + required: ['name', 'email'] + }; + break; + case 'preferences': + message = 'Please set your preferences'; + requestedSchema = { + type: 'object', + properties: { + theme: { + type: 'string', + title: 'Theme', + description: 'Choose your preferred theme', + enum: ['light', 'dark', 'auto'], + enumNames: ['Light', 'Dark', 'Auto'] + }, + notifications: { + type: 'boolean', + title: 'Enable Notifications', + description: 'Would you like to receive notifications?', + default: true + }, + frequency: { + type: 'string', + title: 'Notification Frequency', + description: 'How often would you like notifications?', + enum: ['daily', 'weekly', 'monthly'], + enumNames: ['Daily', 'Weekly', 'Monthly'] + } + }, + required: ['theme'] + }; + break; + case 'feedback': + message = 'Please provide your feedback'; + requestedSchema = { + type: 'object', + properties: { + rating: { + type: 'integer', + title: 'Rating', + description: 'Rate your experience (1-5)', + minimum: 1, + maximum: 5 + }, + comments: { + type: 'string', + title: 'Comments', + description: 'Additional comments (optional)', + maxLength: 500 + }, + recommend: { + type: 'boolean', + title: 'Would you recommend this?', + description: 'Would you recommend this to others?' + } + }, + required: ['rating', 'recommend'] + }; + break; + default: + throw new Error(`Unknown info type: ${infoType}`); + } + try { + // Use the underlying server instance to elicit input from the client + const result = await server.server.elicitInput({ + mode: 'form', + message, + requestedSchema + }); + if (result.action === 'accept') { + return { + content: [ + { + type: 'text', + text: `Thank you! Collected ${infoType} information: ${JSON.stringify(result.content, null, 2)}` + } + ] + }; + } + else if (result.action === 'decline') { + return { + content: [ + { + type: 'text', + text: `No information was collected. User declined ${infoType} information request.` + } + ] + }; + } + else { + return { + content: [ + { + type: 'text', + text: `Information collection was cancelled by the user.` + } + ] + }; + } + } + catch (error) { + return { + content: [ + { + type: 'text', + text: `Error collecting ${infoType} information: ${error}` + } + ] + }; + } + }); + // Register a simple prompt with title + server.registerPrompt('greeting-template', { + title: 'Greeting Template', // Display name for UI + description: 'A simple greeting prompt template', + argsSchema: { + name: z.string().describe('Name to include in greeting') + } + }, async ({ name }) => { + return { + messages: [ + { + role: 'user', + content: { + type: 'text', + text: `Please greet ${name} in a friendly manner.` + } + } + ] + }; + }); + // Register a tool specifically for testing resumability + server.tool('start-notification-stream', 'Starts sending periodic notifications for testing resumability', { + interval: z.number().describe('Interval in milliseconds between notifications').default(100), + count: z.number().describe('Number of notifications to send (0 for 100)').default(50) + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + while (count === 0 || counter < count) { + counter++; + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Periodic notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + // Wait for the specified interval + await sleep(interval); + } + return { + content: [ + { + type: 'text', + text: `Started sending periodic notifications every ${interval}ms` + } + ] + }; + }); + // Create a simple resource at a fixed URI + server.registerResource('greeting-resource', 'https://example.com/greetings/default', { + title: 'Default Greeting', // Display name for UI + description: 'A simple greeting resource', + mimeType: 'text/plain' + }, async () => { + return { + contents: [ + { + uri: 'https://example.com/greetings/default', + text: 'Hello, world!' + } + ] + }; + }); + // Create additional resources for ResourceLink demonstration + server.registerResource('example-file-1', 'file:///example/file1.txt', { + title: 'Example File 1', + description: 'First example file for ResourceLink demonstration', + mimeType: 'text/plain' + }, async () => { + return { + contents: [ + { + uri: 'file:///example/file1.txt', + text: 'This is the content of file 1' + } + ] + }; + }); + server.registerResource('example-file-2', 'file:///example/file2.txt', { + title: 'Example File 2', + description: 'Second example file for ResourceLink demonstration', + mimeType: 'text/plain' + }, async () => { + return { + contents: [ + { + uri: 'file:///example/file2.txt', + text: 'This is the content of file 2' + } + ] + }; + }); + // Register a tool that returns ResourceLinks + server.registerTool('list-files', { + title: 'List Files with ResourceLinks', + description: 'Returns a list of files as ResourceLinks without embedding their content', + inputSchema: { + includeDescriptions: z.boolean().optional().describe('Whether to include descriptions in the resource links') + } + }, async ({ includeDescriptions = true }) => { + const resourceLinks = [ + { + type: 'resource_link', + uri: 'https://example.com/greetings/default', + name: 'Default Greeting', + mimeType: 'text/plain', + ...(includeDescriptions && { description: 'A simple greeting resource' }) + }, + { + type: 'resource_link', + uri: 'file:///example/file1.txt', + name: 'Example File 1', + mimeType: 'text/plain', + ...(includeDescriptions && { description: 'First example file for ResourceLink demonstration' }) + }, + { + type: 'resource_link', + uri: 'file:///example/file2.txt', + name: 'Example File 2', + mimeType: 'text/plain', + ...(includeDescriptions && { description: 'Second example file for ResourceLink demonstration' }) + } + ]; + return { + content: [ + { + type: 'text', + text: 'Here are the available files as resource links:' + }, + ...resourceLinks, + { + type: 'text', + text: '\nYou can read any of these resources using their URI.' + } + ] + }; + }); + return server; +}; +const MCP_PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; +const AUTH_PORT = process.env.MCP_AUTH_PORT ? parseInt(process.env.MCP_AUTH_PORT, 10) : 3001; +const app = express(); +app.use(express.json()); +// Allow CORS all domains, expose the Mcp-Session-Id header +app.use(cors({ + origin: '*', // Allow all origins + exposedHeaders: ['Mcp-Session-Id'] +})); +// Set up OAuth if enabled +let authMiddleware = null; +if (useOAuth) { + // Create auth middleware for MCP endpoints + const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`); + const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); + const oauthMetadata = setupAuthServer({ authServerUrl, mcpServerUrl, strictResource: strictOAuth }); + const tokenVerifier = { + verifyAccessToken: async (token) => { + const endpoint = oauthMetadata.introspection_endpoint; + if (!endpoint) { + throw new Error('No token verification endpoint available in metadata'); + } + const response = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: new URLSearchParams({ + token: token + }).toString() + }); + if (!response.ok) { + throw new Error(`Invalid or expired token: ${await response.text()}`); + } + const data = await response.json(); + if (strictOAuth) { + if (!data.aud) { + throw new Error(`Resource Indicator (RFC8707) missing`); + } + if (!checkResourceAllowed({ requestedResource: data.aud, configuredResource: mcpServerUrl })) { + throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); + } + } + // Convert the response to AuthInfo format + return { + token, + clientId: data.client_id, + scopes: data.scope ? data.scope.split(' ') : [], + expiresAt: data.exp + }; + } + }; + // Add metadata routes to the main MCP server + app.use(mcpAuthMetadataRouter({ + oauthMetadata, + resourceServerUrl: mcpServerUrl, + scopesSupported: ['mcp:tools'], + resourceName: 'MCP Demo Server' + })); + authMiddleware = requireBearerAuth({ + verifier: tokenVerifier, + requiredScopes: [], + resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl) + }); +} +// Map to store transports by session ID +const transports = {}; +// MCP POST endpoint with optional auth +const mcpPostHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (sessionId) { + console.log(`Received MCP request for session: ${sessionId}`); + } + else { + console.log('Request body:', req.body); + } + if (useOAuth && req.auth) { + console.log('Authenticated user:', req.auth); + } + try { + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && isInitializeRequest(req.body)) { + // New initialization request + const eventStore = new InMemoryEventStore(); + transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + eventStore, // Enable resumability + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + } + }; + // Connect the transport to the MCP server BEFORE handling the request + // so responses can flow back through the same transport + const server = getServer(); + await server.connect(transport); + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport - no need to reconnect + // The existing transport is already connected to the server + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}; +// Set up routes with conditional auth middleware +if (useOAuth && authMiddleware) { + app.post('/mcp', authMiddleware, mcpPostHandler); +} +else { + app.post('/mcp', mcpPostHandler); +} +// Handle GET requests for SSE streams (using built-in support from StreamableHTTP) +const mcpGetHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + if (useOAuth && req.auth) { + console.log('Authenticated SSE connection from user:', req.auth); + } + // Check for Last-Event-ID header for resumability + const lastEventId = req.headers['last-event-id']; + if (lastEventId) { + console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`); + } + else { + console.log(`Establishing new SSE stream for session ${sessionId}`); + } + const transport = transports[sessionId]; + await transport.handleRequest(req, res); +}; +// Set up GET route with conditional auth middleware +if (useOAuth && authMiddleware) { + app.get('/mcp', authMiddleware, mcpGetHandler); +} +else { + app.get('/mcp', mcpGetHandler); +} +// Handle DELETE requests for session termination (according to MCP spec) +const mcpDeleteHandler = async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Received session termination request for session ${sessionId}`); + try { + const transport = transports[sessionId]; + await transport.handleRequest(req, res); + } + catch (error) { + console.error('Error handling session termination:', error); + if (!res.headersSent) { + res.status(500).send('Error processing session termination'); + } + } +}; +// Set up DELETE route with conditional auth middleware +if (useOAuth && authMiddleware) { + app.delete('/mcp', authMiddleware, mcpDeleteHandler); +} +else { + app.delete('/mcp', mcpDeleteHandler); +} +app.listen(MCP_PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`MCP Streamable HTTP Server listening on port ${MCP_PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=simpleStreamableHttp.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStreamableHttp.js.map b/dist/esm/examples/server/simpleStreamableHttp.js.map new file mode 100644 index 0000000000..56b80e5293 --- /dev/null +++ b/dist/esm/examples/server/simpleStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"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;IAC7B,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,EAAE,gBAAgB,CAAC,CAAC;AACzD,CAAC;KAAM,CAAC;IACJ,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;AACzC,CAAC;AAED,GAAG,CAAC,MAAM,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE;IACzB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,gDAAgD,QAAQ,EAAE,CAAC,CAAC;AAC5E,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAEvC,6DAA6D;IAC7D,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACjC,IAAI,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,iCAAiC,SAAS,EAAE,CAAC,CAAC;YAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts b/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts new file mode 100644 index 0000000000..c536d0c80e --- /dev/null +++ b/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=sseAndStreamableHttpCompatibleServer.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map b/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map new file mode 100644 index 0000000000..fb982c84a6 --- /dev/null +++ b/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sseAndStreamableHttpCompatibleServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/sseAndStreamableHttpCompatibleServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js b/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js new file mode 100644 index 0000000000..3385fac2db --- /dev/null +++ b/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js @@ -0,0 +1,235 @@ +import express from 'express'; +import { randomUUID } from 'node:crypto'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { SSEServerTransport } from '../../server/sse.js'; +import * as z from 'zod/v4'; +import { isInitializeRequest } from '../../types.js'; +import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; +import cors from 'cors'; +/** + * This example server demonstrates backwards compatibility with both: + * 1. The deprecated HTTP+SSE transport (protocol version 2024-11-05) + * 2. The Streamable HTTP transport (protocol version 2025-03-26) + * + * It maintains a single MCP server instance but exposes two transport options: + * - /mcp: The new Streamable HTTP endpoint (supports GET/POST/DELETE) + * - /sse: The deprecated SSE endpoint for older clients (GET to establish stream) + * - /messages: The deprecated POST endpoint for older clients (POST to send messages) + */ +const getServer = () => { + const server = new McpServer({ + name: 'backwards-compatible-server', + version: '1.0.0' + }, { capabilities: { logging: {} } }); + // Register a simple tool that sends notifications over time + server.tool('start-notification-stream', 'Starts sending periodic notifications for testing resumability', { + interval: z.number().describe('Interval in milliseconds between notifications').default(100), + count: z.number().describe('Number of notifications to send (0 for 100)').default(50) + }, async ({ interval, count }, extra) => { + const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); + let counter = 0; + while (count === 0 || counter < count) { + counter++; + try { + await server.sendLoggingMessage({ + level: 'info', + data: `Periodic notification #${counter} at ${new Date().toISOString()}` + }, extra.sessionId); + } + catch (error) { + console.error('Error sending notification:', error); + } + // Wait for the specified interval + await sleep(interval); + } + return { + content: [ + { + type: 'text', + text: `Started sending periodic notifications every ${interval}ms` + } + ] + }; + }); + return server; +}; +// Create Express application +const app = express(); +app.use(express.json()); +// Configure CORS to expose Mcp-Session-Id header for browser-based clients +app.use(cors({ + origin: '*', // Allow all origins - adjust as needed for production + exposedHeaders: ['Mcp-Session-Id'] +})); +// Store transports by session ID +const transports = {}; +//============================================================================= +// STREAMABLE HTTP TRANSPORT (PROTOCOL VERSION 2025-03-26) +//============================================================================= +// Handle all MCP Streamable HTTP requests (GET, POST, DELETE) on a single endpoint +app.all('/mcp', async (req, res) => { + console.log(`Received ${req.method} request to /mcp`); + try { + // Check for existing session ID + const sessionId = req.headers['mcp-session-id']; + let transport; + if (sessionId && transports[sessionId]) { + // Check if the transport is of the correct type + const existingTransport = transports[sessionId]; + if (existingTransport instanceof StreamableHTTPServerTransport) { + // Reuse existing transport + transport = existingTransport; + } + else { + // Transport exists but is not a StreamableHTTPServerTransport (could be SSEServerTransport) + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Session exists but uses a different transport protocol' + }, + id: null + }); + return; + } + } + else if (!sessionId && req.method === 'POST' && isInitializeRequest(req.body)) { + const eventStore = new InMemoryEventStore(); + transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + eventStore, // Enable resumability + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + console.log(`StreamableHTTP session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Set up onclose handler to clean up transport when closed + transport.onclose = () => { + const sid = transport.sessionId; + if (sid && transports[sid]) { + console.log(`Transport closed for session ${sid}, removing from transports map`); + delete transports[sid]; + } + }; + // Connect the transport to the MCP server + const server = getServer(); + await server.connect(transport); + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with the transport + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +//============================================================================= +// DEPRECATED HTTP+SSE TRANSPORT (PROTOCOL VERSION 2024-11-05) +//============================================================================= +app.get('/sse', async (req, res) => { + console.log('Received GET request to /sse (deprecated SSE transport)'); + const transport = new SSEServerTransport('/messages', res); + transports[transport.sessionId] = transport; + res.on('close', () => { + delete transports[transport.sessionId]; + }); + const server = getServer(); + await server.connect(transport); +}); +app.post('/messages', async (req, res) => { + const sessionId = req.query.sessionId; + let transport; + const existingTransport = transports[sessionId]; + if (existingTransport instanceof SSEServerTransport) { + // Reuse existing transport + transport = existingTransport; + } + else { + // Transport exists but is not a SSEServerTransport (could be StreamableHTTPServerTransport) + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Session exists but uses a different transport protocol' + }, + id: null + }); + return; + } + if (transport) { + await transport.handlePostMessage(req, res, req.body); + } + else { + res.status(400).send('No transport found for sessionId'); + } +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Backwards compatible MCP server listening on port ${PORT}`); + console.log(` +============================================== +SUPPORTED TRANSPORT OPTIONS: + +1. Streamable Http(Protocol version: 2025-03-26) + Endpoint: /mcp + Methods: GET, POST, DELETE + Usage: + - Initialize with POST to /mcp + - Establish SSE stream with GET to /mcp + - Send requests with POST to /mcp + - Terminate session with DELETE to /mcp + +2. Http + SSE (Protocol version: 2024-11-05) + Endpoints: /sse (GET) and /messages (POST) + Usage: + - Establish SSE stream with GET to /sse + - Send requests with POST to /messages?sessionId= +============================================== +`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + // Close all active transports to properly clean up resources + for (const sessionId in transports) { + try { + console.log(`Closing transport for session ${sessionId}`); + await transports[sessionId].close(); + delete transports[sessionId]; + } + catch (error) { + console.error(`Error closing transport for session ${sessionId}:`, error); + } + } + console.log('Server shutdown complete'); + process.exit(0); +}); +//# sourceMappingURL=sseAndStreamableHttpCompatibleServer.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js.map b/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js.map new file mode 100644 index 0000000000..f854fbcd6b --- /dev/null +++ b/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sseAndStreamableHttpCompatibleServer.js","sourceRoot":"","sources":["../../../../src/examples/server/sseAndStreamableHttpCompatibleServer.ts"],"names":[],"mappings":"AAAA,OAAO,OAA8B,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAkB,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB;;;;;;;;;GASG;AAEH,MAAM,SAAS,GAAG,GAAG,EAA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AAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAEvC,6DAA6D;IAC7D,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACjC,IAAI,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,iCAAiC,SAAS,EAAE,CAAC,CAAC;YAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts b/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts new file mode 100644 index 0000000000..4df17831b7 --- /dev/null +++ b/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=standaloneSseWithGetStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map b/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map new file mode 100644 index 0000000000..df60dc51b0 --- /dev/null +++ b/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"standaloneSseWithGetStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/standaloneSseWithGetStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js b/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js new file mode 100644 index 0000000000..b67302c968 --- /dev/null +++ b/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js @@ -0,0 +1,111 @@ +import express from 'express'; +import { randomUUID } from 'node:crypto'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { isInitializeRequest } from '../../types.js'; +// Create an MCP server with implementation details +const server = new McpServer({ + name: 'resource-list-changed-notification-server', + version: '1.0.0' +}); +// Store transports by session ID to send notifications +const transports = {}; +const addResource = (name, content) => { + const uri = `https://mcp-example.com/dynamic/${encodeURIComponent(name)}`; + server.resource(name, uri, { mimeType: 'text/plain', description: `Dynamic resource: ${name}` }, async () => { + return { + contents: [{ uri, text: content }] + }; + }); +}; +addResource('example-resource', 'Initial content for example-resource'); +const resourceChangeInterval = setInterval(() => { + const name = randomUUID(); + addResource(name, `Content for ${name}`); +}, 5000); // Change resources every 5 seconds for testing +const app = express(); +app.use(express.json()); +app.post('/mcp', async (req, res) => { + console.log('Received MCP request:', req.body); + try { + // Check for existing session ID + const sessionId = req.headers['mcp-session-id']; + let transport; + if (sessionId && transports[sessionId]) { + // Reuse existing transport + transport = transports[sessionId]; + } + else if (!sessionId && isInitializeRequest(req.body)) { + // New initialization request + transport = new StreamableHTTPServerTransport({ + sessionIdGenerator: () => randomUUID(), + onsessioninitialized: sessionId => { + // Store the transport by session ID when session is initialized + // This avoids race conditions where requests might come in before the session is stored + console.log(`Session initialized with ID: ${sessionId}`); + transports[sessionId] = transport; + } + }); + // Connect the transport to the MCP server + await server.connect(transport); + // Handle the request - the onsessioninitialized callback will store the transport + await transport.handleRequest(req, res, req.body); + return; // Already handled + } + else { + // Invalid request - no session ID or not initialization request + res.status(400).json({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: No valid session ID provided' + }, + id: null + }); + return; + } + // Handle the request with existing transport + await transport.handleRequest(req, res, req.body); + } + catch (error) { + console.error('Error handling MCP request:', error); + if (!res.headersSent) { + res.status(500).json({ + jsonrpc: '2.0', + error: { + code: -32603, + message: 'Internal server error' + }, + id: null + }); + } + } +}); +// Handle GET requests for SSE streams (now using built-in support from StreamableHTTP) +app.get('/mcp', async (req, res) => { + const sessionId = req.headers['mcp-session-id']; + if (!sessionId || !transports[sessionId]) { + res.status(400).send('Invalid or missing session ID'); + return; + } + console.log(`Establishing SSE stream for session ${sessionId}`); + const transport = transports[sessionId]; + await transport.handleRequest(req, res); +}); +// Start the server +const PORT = 3000; +app.listen(PORT, error => { + if (error) { + console.error('Failed to start server:', error); + process.exit(1); + } + console.log(`Server listening on port ${PORT}`); +}); +// Handle server shutdown +process.on('SIGINT', async () => { + console.log('Shutting down server...'); + clearInterval(resourceChangeInterval); + await server.close(); + process.exit(0); +}); +//# sourceMappingURL=standaloneSseWithGetStreamableHttp.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js.map b/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js.map new file mode 100644 index 0000000000..8caa419a85 --- /dev/null +++ b/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"standaloneSseWithGetStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/standaloneSseWithGetStreamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,OAA8B,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,mBAAmB,EAAsB,MAAM,gBAAgB,CAAC;AAEzE,mDAAmD;AACnD,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC;IACzB,IAAI,EAAE,2CAA2C;IACjD,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,uDAAuD;AACvD,MAAM,UAAU,GA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,CAAC,KAAK,EAAE,CAAC;IACrB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/toolWithSampleServer.d.ts b/dist/esm/examples/server/toolWithSampleServer.d.ts new file mode 100644 index 0000000000..acc24b6a53 --- /dev/null +++ b/dist/esm/examples/server/toolWithSampleServer.d.ts @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=toolWithSampleServer.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/toolWithSampleServer.d.ts.map b/dist/esm/examples/server/toolWithSampleServer.d.ts.map new file mode 100644 index 0000000000..bd0cebcf19 --- /dev/null +++ b/dist/esm/examples/server/toolWithSampleServer.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"toolWithSampleServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/toolWithSampleServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/toolWithSampleServer.js b/dist/esm/examples/server/toolWithSampleServer.js new file mode 100644 index 0000000000..326a288cd5 --- /dev/null +++ b/dist/esm/examples/server/toolWithSampleServer.js @@ -0,0 +1,46 @@ +// Run with: npx tsx src/examples/server/toolWithSampleServer.ts +import { McpServer } from '../../server/mcp.js'; +import { StdioServerTransport } from '../../server/stdio.js'; +import * as z from 'zod/v4'; +const mcpServer = new McpServer({ + name: 'tools-with-sample-server', + version: '1.0.0' +}); +// Tool that uses LLM sampling to summarize any text +mcpServer.registerTool('summarize', { + description: 'Summarize any text using an LLM', + inputSchema: { + text: z.string().describe('Text to summarize') + } +}, async ({ text }) => { + // Call the LLM through MCP sampling + const response = await mcpServer.server.createMessage({ + messages: [ + { + role: 'user', + content: { + type: 'text', + text: `Please summarize the following text concisely:\n\n${text}` + } + } + ], + maxTokens: 500 + }); + const contents = Array.isArray(response.content) ? response.content : [response.content]; + return { + content: contents.map(content => ({ + type: 'text', + text: content.type === 'text' ? content.text : 'Unable to generate summary' + })) + }; +}); +async function main() { + const transport = new StdioServerTransport(); + await mcpServer.connect(transport); + console.log('MCP server is running...'); +} +main().catch(error => { + console.error('Server error:', error); + process.exit(1); +}); +//# sourceMappingURL=toolWithSampleServer.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/toolWithSampleServer.js.map b/dist/esm/examples/server/toolWithSampleServer.js.map new file mode 100644 index 0000000000..f4fb4337eb --- /dev/null +++ b/dist/esm/examples/server/toolWithSampleServer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"toolWithSampleServer.js","sourceRoot":"","sources":["../../../../src/examples/server/toolWithSampleServer.ts"],"names":[],"mappings":"AAAA,gEAAgE;AAEhE,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC;IAC5B,IAAI,EAAE,0BAA0B;IAChC,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,oDAAoD;AACpD,SAAS,CAAC,YAAY,CAClB,WAAW,EACX;IACI,WAAW,EAAE,iCAAiC;IAC9C,WAAW,EAAE;QACT,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,mBAAmB,CAAC;KACjD;CACJ,EACD,KAAK,EAAE,EAAE,IAAI,EAAE,EAAE,EAAE;IACf,oCAAoC;IACpC,MAAM,QAAQ,GAAG,MAAM,SAAS,CAAC,MAAM,CAAC,aAAa,CAAC;QAClD,QAAQ,EAAE;YACN;gBACI,IAAI,EAAE,MAAM;gBACZ,OAAO,EAAE;oBACL,IAAI,EAAE,MAAM;oBACZ,IAAI,EAAE,qDAAqD,IAAI,EAAE;iBACpE;aACJ;SACJ;QACD,SAAS,EAAE,GAAG;KACjB,CAAC,CAAC;IAEH,MAAM,QAAQ,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACzF,OAAO;QACH,OAAO,EAAE,QAAQ,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;YAC9B,IAAI,EAAE,MAAM;YACZ,IAAI,EAAE,OAAO,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,4BAA4B;SAC9E,CAAC,CAAC;KACN,CAAC;AACN,CAAC,CACJ,CAAC;AAEF,KAAK,UAAU,IAAI;IACf,MAAM,SAAS,GAAG,IAAI,oBAAoB,EAAE,CAAC;IAC7C,MAAM,SAAS,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACnC,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;AAC5C,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/shared/inMemoryEventStore.d.ts b/dist/esm/examples/shared/inMemoryEventStore.d.ts new file mode 100644 index 0000000000..26ff38cf93 --- /dev/null +++ b/dist/esm/examples/shared/inMemoryEventStore.d.ts @@ -0,0 +1,31 @@ +import { JSONRPCMessage } from '../../types.js'; +import { EventStore } from '../../server/streamableHttp.js'; +/** + * Simple in-memory implementation of the EventStore interface for resumability + * This is primarily intended for examples and testing, not for production use + * where a persistent storage solution would be more appropriate. + */ +export declare class InMemoryEventStore implements EventStore { + private events; + /** + * Generates a unique event ID for a given stream ID + */ + private generateEventId; + /** + * Extracts the stream ID from an event ID + */ + private getStreamIdFromEventId; + /** + * Stores an event with a generated event ID + * Implements EventStore.storeEvent + */ + storeEvent(streamId: string, message: JSONRPCMessage): Promise; + /** + * Replays events that occurred after a specific event ID + * Implements EventStore.replayEventsAfter + */ + replayEventsAfter(lastEventId: string, { send }: { + send: (eventId: string, message: JSONRPCMessage) => Promise; + }): Promise; +} +//# sourceMappingURL=inMemoryEventStore.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/shared/inMemoryEventStore.d.ts.map b/dist/esm/examples/shared/inMemoryEventStore.d.ts.map new file mode 100644 index 0000000000..a67ee6cd17 --- /dev/null +++ b/dist/esm/examples/shared/inMemoryEventStore.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"inMemoryEventStore.d.ts","sourceRoot":"","sources":["../../../../src/examples/shared/inMemoryEventStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAE5D;;;;GAIG;AACH,qBAAa,kBAAmB,YAAW,UAAU;IACjD,OAAO,CAAC,MAAM,CAAyE;IAEvF;;OAEG;IACH,OAAO,CAAC,eAAe;IAIvB;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAK9B;;;OAGG;IACG,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;IAM5E;;;OAGG;IACG,iBAAiB,CACnB,WAAW,EAAE,MAAM,EACnB,EAAE,IAAI,EAAE,EAAE;QAAE,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;KAAE,GAChF,OAAO,CAAC,MAAM,CAAC;CAkCrB"} \ No newline at end of file diff --git a/dist/esm/examples/shared/inMemoryEventStore.js b/dist/esm/examples/shared/inMemoryEventStore.js new file mode 100644 index 0000000000..35f6dbb7c3 --- /dev/null +++ b/dist/esm/examples/shared/inMemoryEventStore.js @@ -0,0 +1,65 @@ +/** + * Simple in-memory implementation of the EventStore interface for resumability + * This is primarily intended for examples and testing, not for production use + * where a persistent storage solution would be more appropriate. + */ +export class InMemoryEventStore { + constructor() { + this.events = new Map(); + } + /** + * Generates a unique event ID for a given stream ID + */ + generateEventId(streamId) { + return `${streamId}_${Date.now()}_${Math.random().toString(36).substring(2, 10)}`; + } + /** + * Extracts the stream ID from an event ID + */ + getStreamIdFromEventId(eventId) { + const parts = eventId.split('_'); + return parts.length > 0 ? parts[0] : ''; + } + /** + * Stores an event with a generated event ID + * Implements EventStore.storeEvent + */ + async storeEvent(streamId, message) { + const eventId = this.generateEventId(streamId); + this.events.set(eventId, { streamId, message }); + return eventId; + } + /** + * Replays events that occurred after a specific event ID + * Implements EventStore.replayEventsAfter + */ + async replayEventsAfter(lastEventId, { send }) { + if (!lastEventId || !this.events.has(lastEventId)) { + return ''; + } + // Extract the stream ID from the event ID + const streamId = this.getStreamIdFromEventId(lastEventId); + if (!streamId) { + return ''; + } + let foundLastEvent = false; + // Sort events by eventId for chronological ordering + const sortedEvents = [...this.events.entries()].sort((a, b) => a[0].localeCompare(b[0])); + for (const [eventId, { streamId: eventStreamId, message }] of sortedEvents) { + // Only include events from the same stream + if (eventStreamId !== streamId) { + continue; + } + // Start sending events after we find the lastEventId + if (eventId === lastEventId) { + foundLastEvent = true; + continue; + } + if (foundLastEvent) { + await send(eventId, message); + } + } + return streamId; + } +} +//# sourceMappingURL=inMemoryEventStore.js.map \ No newline at end of file diff --git a/dist/esm/examples/shared/inMemoryEventStore.js.map b/dist/esm/examples/shared/inMemoryEventStore.js.map new file mode 100644 index 0000000000..b9e6af66aa --- /dev/null +++ b/dist/esm/examples/shared/inMemoryEventStore.js.map @@ -0,0 +1 @@ +{"version":3,"file":"inMemoryEventStore.js","sourceRoot":"","sources":["../../../../src/examples/shared/inMemoryEventStore.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,MAAM,OAAO,kBAAkB;IAA/B;QACY,WAAM,GAA+D,IAAI,GAAG,EAAE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AC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAEzF,KAAK,MAAM,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,aAAa,EAAE,OAAO,EAAE,CAAC,IAAI,YAAY,EAAE,CAAC;YACzE,2CAA2C;YAC3C,IAAI,aAAa,KAAK,QAAQ,EAAE,CAAC;gBAC7B,SAAS;YACb,CAAC;YAED,qDAAqD;YACrD,IAAI,OAAO,KAAK,WAAW,EAAE,CAAC;gBAC1B,cAAc,GAAG,IAAI,CAAC;gBACtB,SAAS;YACb,CAAC;YAED,IAAI,cAAc,EAAE,CAAC;gBACjB,MAAM,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACjC,CAAC;QACL,CAAC;QACD,OAAO,QAAQ,CAAC;IACpB,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/inMemory.d.ts b/dist/esm/inMemory.d.ts new file mode 100644 index 0000000000..32a931a863 --- /dev/null +++ b/dist/esm/inMemory.d.ts @@ -0,0 +1,31 @@ +import { Transport } from './shared/transport.js'; +import { JSONRPCMessage, RequestId } from './types.js'; +import { AuthInfo } from './server/auth/types.js'; +/** + * In-memory transport for creating clients and servers that talk to each other within the same process. + */ +export declare class InMemoryTransport implements Transport { + private _otherTransport?; + private _messageQueue; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage, extra?: { + authInfo?: AuthInfo; + }) => void; + sessionId?: string; + /** + * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a Client and one to a Server. + */ + static createLinkedPair(): [InMemoryTransport, InMemoryTransport]; + start(): Promise; + close(): Promise; + /** + * Sends a message with optional auth info. + * This is useful for testing authentication scenarios. + */ + send(message: JSONRPCMessage, options?: { + relatedRequestId?: RequestId; + authInfo?: AuthInfo; + }): Promise; +} +//# sourceMappingURL=inMemory.d.ts.map \ No newline at end of file diff --git a/dist/esm/inMemory.d.ts.map b/dist/esm/inMemory.d.ts.map new file mode 100644 index 0000000000..46bc74be17 --- /dev/null +++ b/dist/esm/inMemory.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"inMemory.d.ts","sourceRoot":"","sources":["../../src/inMemory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAOlD;;GAEG;AACH,qBAAa,iBAAkB,YAAW,SAAS;IAC/C,OAAO,CAAC,eAAe,CAAC,CAAoB;IAC5C,OAAO,CAAC,aAAa,CAAuB;IAE5C,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,KAAK,IAAI,CAAC;IAC/E,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,MAAM,CAAC,gBAAgB,IAAI,CAAC,iBAAiB,EAAE,iBAAiB,CAAC;IAQ3D,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAQtB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAO5B;;;OAGG;IACG,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,SAAS,CAAC;QAAC,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAWtH"} \ No newline at end of file diff --git a/dist/esm/inMemory.js b/dist/esm/inMemory.js new file mode 100644 index 0000000000..930bbff511 --- /dev/null +++ b/dist/esm/inMemory.js @@ -0,0 +1,49 @@ +/** + * In-memory transport for creating clients and servers that talk to each other within the same process. + */ +export class InMemoryTransport { + constructor() { + this._messageQueue = []; + } + /** + * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a Client and one to a Server. + */ + static createLinkedPair() { + const clientTransport = new InMemoryTransport(); + const serverTransport = new InMemoryTransport(); + clientTransport._otherTransport = serverTransport; + serverTransport._otherTransport = clientTransport; + return [clientTransport, serverTransport]; + } + async start() { + var _a; + // Process any messages that were queued before start was called + while (this._messageQueue.length > 0) { + const queuedMessage = this._messageQueue.shift(); + (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, queuedMessage.message, queuedMessage.extra); + } + } + async close() { + var _a; + const other = this._otherTransport; + this._otherTransport = undefined; + await (other === null || other === void 0 ? void 0 : other.close()); + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + } + /** + * Sends a message with optional auth info. + * This is useful for testing authentication scenarios. + */ + async send(message, options) { + if (!this._otherTransport) { + throw new Error('Not connected'); + } + if (this._otherTransport.onmessage) { + this._otherTransport.onmessage(message, { authInfo: options === null || options === void 0 ? void 0 : options.authInfo }); + } + else { + this._otherTransport._messageQueue.push({ message, extra: { authInfo: options === null || options === void 0 ? void 0 : options.authInfo } }); + } + } +} +//# sourceMappingURL=inMemory.js.map \ No newline at end of file diff --git a/dist/esm/inMemory.js.map b/dist/esm/inMemory.js.map new file mode 100644 index 0000000000..f001ce163b --- /dev/null +++ b/dist/esm/inMemory.js.map @@ -0,0 +1 @@ +{"version":3,"file":"inMemory.js","sourceRoot":"","sources":["../../src/inMemory.ts"],"names":[],"mappings":"AASA;;GAEG;AACH,MAAM,OAAO,iBAAiB;IAA9B;QAEY,kBAAa,GAAoB,EAAE,CAAC;IAgDhD,CAAC;IAzCG;;OAEG;IACH,MAAM,CAAC,gBAAgB;QACnB,MAAM,eAAe,GAAG,IAAI,iBAAiB,EAAE,CAAC;QAChD,MAAM,eAA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,CAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;QACjG,CAAC;IACL,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/package.json b/dist/esm/package.json new file mode 100644 index 0000000000..6990891ff3 --- /dev/null +++ b/dist/esm/package.json @@ -0,0 +1 @@ +{"type": "module"} diff --git a/dist/esm/server/auth/clients.d.ts b/dist/esm/server/auth/clients.d.ts new file mode 100644 index 0000000000..be6899a198 --- /dev/null +++ b/dist/esm/server/auth/clients.d.ts @@ -0,0 +1,19 @@ +import { OAuthClientInformationFull } from '../../shared/auth.js'; +/** + * Stores information about registered OAuth clients for this server. + */ +export interface OAuthRegisteredClientsStore { + /** + * Returns information about a registered client, based on its ID. + */ + getClient(clientId: string): OAuthClientInformationFull | undefined | Promise; + /** + * Registers a new client with the server. The client ID and secret will be automatically generated by the library. A modified version of the client information can be returned to reflect specific values enforced by the server. + * + * NOTE: Implementations should NOT delete expired client secrets in-place. Auth middleware provided by this library will automatically check the `client_secret_expires_at` field and reject requests with expired secrets. Any custom logic for authenticating clients should check the `client_secret_expires_at` field as well. + * + * If unimplemented, dynamic client registration is unsupported. + */ + registerClient?(client: Omit): OAuthClientInformationFull | Promise; +} +//# sourceMappingURL=clients.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/clients.d.ts.map b/dist/esm/server/auth/clients.d.ts.map new file mode 100644 index 0000000000..ab3851db35 --- /dev/null +++ b/dist/esm/server/auth/clients.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"clients.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/clients.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAElE;;GAEG;AACH,MAAM,WAAW,2BAA2B;IACxC;;OAEG;IACH,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,0BAA0B,GAAG,SAAS,GAAG,OAAO,CAAC,0BAA0B,GAAG,SAAS,CAAC,CAAC;IAEtH;;;;;;OAMG;IACH,cAAc,CAAC,CACX,MAAM,EAAE,IAAI,CAAC,0BAA0B,EAAE,WAAW,GAAG,qBAAqB,CAAC,GAC9E,0BAA0B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAAC;CACvE"} \ No newline at end of file diff --git a/dist/esm/server/auth/clients.js b/dist/esm/server/auth/clients.js new file mode 100644 index 0000000000..6181a5709d --- /dev/null +++ b/dist/esm/server/auth/clients.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=clients.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/clients.js.map b/dist/esm/server/auth/clients.js.map new file mode 100644 index 0000000000..0210104422 --- /dev/null +++ b/dist/esm/server/auth/clients.js.map @@ -0,0 +1 @@ +{"version":3,"file":"clients.js","sourceRoot":"","sources":["../../../../src/server/auth/clients.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/server/auth/errors.d.ts b/dist/esm/server/auth/errors.d.ts new file mode 100644 index 0000000000..b487760fc2 --- /dev/null +++ b/dist/esm/server/auth/errors.d.ts @@ -0,0 +1,141 @@ +import { OAuthErrorResponse } from '../../shared/auth.js'; +/** + * Base class for all OAuth errors + */ +export declare class OAuthError extends Error { + readonly errorUri?: string | undefined; + static errorCode: string; + constructor(message: string, errorUri?: string | undefined); + /** + * Converts the error to a standard OAuth error response object + */ + toResponseObject(): OAuthErrorResponse; + get errorCode(): string; +} +/** + * Invalid request error - The request is missing a required parameter, + * includes an invalid parameter value, includes a parameter more than once, + * or is otherwise malformed. + */ +export declare class InvalidRequestError extends OAuthError { + static errorCode: string; +} +/** + * Invalid client error - Client authentication failed (e.g., unknown client, no client + * authentication included, or unsupported authentication method). + */ +export declare class InvalidClientError extends OAuthError { + static errorCode: string; +} +/** + * Invalid grant error - The provided authorization grant or refresh token is + * invalid, expired, revoked, does not match the redirection URI used in the + * authorization request, or was issued to another client. + */ +export declare class InvalidGrantError extends OAuthError { + static errorCode: string; +} +/** + * Unauthorized client error - The authenticated client is not authorized to use + * this authorization grant type. + */ +export declare class UnauthorizedClientError extends OAuthError { + static errorCode: string; +} +/** + * Unsupported grant type error - The authorization grant type is not supported + * by the authorization server. + */ +export declare class UnsupportedGrantTypeError extends OAuthError { + static errorCode: string; +} +/** + * Invalid scope error - The requested scope is invalid, unknown, malformed, or + * exceeds the scope granted by the resource owner. + */ +export declare class InvalidScopeError extends OAuthError { + static errorCode: string; +} +/** + * Access denied error - The resource owner or authorization server denied the request. + */ +export declare class AccessDeniedError extends OAuthError { + static errorCode: string; +} +/** + * Server error - The authorization server encountered an unexpected condition + * that prevented it from fulfilling the request. + */ +export declare class ServerError extends OAuthError { + static errorCode: string; +} +/** + * Temporarily unavailable error - The authorization server is currently unable to + * handle the request due to a temporary overloading or maintenance of the server. + */ +export declare class TemporarilyUnavailableError extends OAuthError { + static errorCode: string; +} +/** + * Unsupported response type error - The authorization server does not support + * obtaining an authorization code using this method. + */ +export declare class UnsupportedResponseTypeError extends OAuthError { + static errorCode: string; +} +/** + * Unsupported token type error - The authorization server does not support + * the requested token type. + */ +export declare class UnsupportedTokenTypeError extends OAuthError { + static errorCode: string; +} +/** + * Invalid token error - The access token provided is expired, revoked, malformed, + * or invalid for other reasons. + */ +export declare class InvalidTokenError extends OAuthError { + static errorCode: string; +} +/** + * Method not allowed error - The HTTP method used is not allowed for this endpoint. + * (Custom, non-standard error) + */ +export declare class MethodNotAllowedError extends OAuthError { + static errorCode: string; +} +/** + * Too many requests error - Rate limit exceeded. + * (Custom, non-standard error based on RFC 6585) + */ +export declare class TooManyRequestsError extends OAuthError { + static errorCode: string; +} +/** + * Invalid client metadata error - The client metadata is invalid. + * (Custom error for dynamic client registration - RFC 7591) + */ +export declare class InvalidClientMetadataError extends OAuthError { + static errorCode: string; +} +/** + * Insufficient scope error - The request requires higher privileges than provided by the access token. + */ +export declare class InsufficientScopeError extends OAuthError { + static errorCode: string; +} +/** + * A utility class for defining one-off error codes + */ +export declare class CustomOAuthError extends OAuthError { + private readonly customErrorCode; + constructor(customErrorCode: string, message: string, errorUri?: string); + get errorCode(): string; +} +/** + * A full list of all OAuthErrors, enabling parsing from error responses + */ +export declare const OAUTH_ERRORS: { + readonly [x: string]: typeof InvalidRequestError; +}; +//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/errors.d.ts.map b/dist/esm/server/auth/errors.d.ts.map new file mode 100644 index 0000000000..5141085c26 --- /dev/null +++ b/dist/esm/server/auth/errors.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE1D;;GAEG;AACH,qBAAa,UAAW,SAAQ,KAAK;aAKb,QAAQ,CAAC,EAAE,MAAM;IAJrC,MAAM,CAAC,SAAS,EAAE,MAAM,CAAC;gBAGrB,OAAO,EAAE,MAAM,EACC,QAAQ,CAAC,EAAE,MAAM,YAAA;IAMrC;;OAEG;IACH,gBAAgB,IAAI,kBAAkB;IAatC,IAAI,SAAS,IAAI,MAAM,CAEtB;CACJ;AAED;;;;GAIG;AACH,qBAAa,mBAAoB,SAAQ,UAAU;IAC/C,MAAM,CAAC,SAAS,SAAqB;CACxC;AAED;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,UAAU;IAC9C,MAAM,CAAC,SAAS,SAAoB;CACvC;AAED;;;;GAIG;AACH,qBAAa,iBAAkB,SAAQ,UAAU;IAC7C,MAAM,CAAC,SAAS,SAAmB;CACtC;AAED;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,UAAU;IACnD,MAAM,CAAC,SAAS,SAAyB;CAC5C;AAED;;;GAGG;AACH,qBAAa,yBAA0B,SAAQ,UAAU;IACrD,MAAM,CAAC,SAAS,SAA4B;CAC/C;AAED;;;GAGG;AACH,qBAAa,iBAAkB,SAAQ,UAAU;IAC7C,MAAM,CAAC,SAAS,SAAmB;CACtC;AAED;;GAEG;AACH,qBAAa,iBAAkB,SAAQ,UAAU;IAC7C,MAAM,CAAC,SAAS,SAAmB;CACtC;AAED;;;GAGG;AACH,qBAAa,WAAY,SAAQ,UAAU;IACvC,MAAM,CAAC,SAAS,SAAkB;CACrC;AAED;;;GAGG;AACH,qBAAa,2BAA4B,SAAQ,UAAU;IACvD,MAAM,CAAC,SAAS,SAA6B;CAChD;AAED;;;GAGG;AACH,qBAAa,4BAA6B,SAAQ,UAAU;IACxD,MAAM,CAAC,SAAS,SAA+B;CAClD;AAED;;;GAGG;AACH,qBAAa,yBAA0B,SAAQ,UAAU;IACrD,MAAM,CAAC,SAAS,SAA4B;CAC/C;AAED;;;GAGG;AACH,qBAAa,iBAAkB,SAAQ,UAAU;IAC7C,MAAM,CAAC,SAAS,SAAmB;CACtC;AAED;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,UAAU;IACjD,MAAM,CAAC,SAAS,SAAwB;CAC3C;AAED;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,UAAU;IAChD,MAAM,CAAC,SAAS,SAAuB;CAC1C;AAED;;;GAGG;AACH,qBAAa,0BAA2B,SAAQ,UAAU;IACtD,MAAM,CAAC,SAAS,SAA6B;CAChD;AAED;;GAEG;AACH,qBAAa,sBAAuB,SAAQ,UAAU;IAClD,MAAM,CAAC,SAAS,SAAwB;CAC3C;AAED;;GAEG;AACH,qBAAa,gBAAiB,SAAQ,UAAU;IAExC,OAAO,CAAC,QAAQ,CAAC,eAAe;gBAAf,eAAe,EAAE,MAAM,EACxC,OAAO,EAAE,MAAM,EACf,QAAQ,CAAC,EAAE,MAAM;IAKrB,IAAI,SAAS,IAAI,MAAM,CAEtB;CACJ;AAED;;GAEG;AACH,eAAO,MAAM,YAAY;;CAiBf,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/errors.js b/dist/esm/server/auth/errors.js new file mode 100644 index 0000000000..e5dcdbe051 --- /dev/null +++ b/dist/esm/server/auth/errors.js @@ -0,0 +1,172 @@ +/** + * Base class for all OAuth errors + */ +export class OAuthError extends Error { + constructor(message, errorUri) { + super(message); + this.errorUri = errorUri; + this.name = this.constructor.name; + } + /** + * Converts the error to a standard OAuth error response object + */ + toResponseObject() { + const response = { + error: this.errorCode, + error_description: this.message + }; + if (this.errorUri) { + response.error_uri = this.errorUri; + } + return response; + } + get errorCode() { + return this.constructor.errorCode; + } +} +/** + * Invalid request error - The request is missing a required parameter, + * includes an invalid parameter value, includes a parameter more than once, + * or is otherwise malformed. + */ +export class InvalidRequestError extends OAuthError { +} +InvalidRequestError.errorCode = 'invalid_request'; +/** + * Invalid client error - Client authentication failed (e.g., unknown client, no client + * authentication included, or unsupported authentication method). + */ +export class InvalidClientError extends OAuthError { +} +InvalidClientError.errorCode = 'invalid_client'; +/** + * Invalid grant error - The provided authorization grant or refresh token is + * invalid, expired, revoked, does not match the redirection URI used in the + * authorization request, or was issued to another client. + */ +export class InvalidGrantError extends OAuthError { +} +InvalidGrantError.errorCode = 'invalid_grant'; +/** + * Unauthorized client error - The authenticated client is not authorized to use + * this authorization grant type. + */ +export class UnauthorizedClientError extends OAuthError { +} +UnauthorizedClientError.errorCode = 'unauthorized_client'; +/** + * Unsupported grant type error - The authorization grant type is not supported + * by the authorization server. + */ +export class UnsupportedGrantTypeError extends OAuthError { +} +UnsupportedGrantTypeError.errorCode = 'unsupported_grant_type'; +/** + * Invalid scope error - The requested scope is invalid, unknown, malformed, or + * exceeds the scope granted by the resource owner. + */ +export class InvalidScopeError extends OAuthError { +} +InvalidScopeError.errorCode = 'invalid_scope'; +/** + * Access denied error - The resource owner or authorization server denied the request. + */ +export class AccessDeniedError extends OAuthError { +} +AccessDeniedError.errorCode = 'access_denied'; +/** + * Server error - The authorization server encountered an unexpected condition + * that prevented it from fulfilling the request. + */ +export class ServerError extends OAuthError { +} +ServerError.errorCode = 'server_error'; +/** + * Temporarily unavailable error - The authorization server is currently unable to + * handle the request due to a temporary overloading or maintenance of the server. + */ +export class TemporarilyUnavailableError extends OAuthError { +} +TemporarilyUnavailableError.errorCode = 'temporarily_unavailable'; +/** + * Unsupported response type error - The authorization server does not support + * obtaining an authorization code using this method. + */ +export class UnsupportedResponseTypeError extends OAuthError { +} +UnsupportedResponseTypeError.errorCode = 'unsupported_response_type'; +/** + * Unsupported token type error - The authorization server does not support + * the requested token type. + */ +export class UnsupportedTokenTypeError extends OAuthError { +} +UnsupportedTokenTypeError.errorCode = 'unsupported_token_type'; +/** + * Invalid token error - The access token provided is expired, revoked, malformed, + * or invalid for other reasons. + */ +export class InvalidTokenError extends OAuthError { +} +InvalidTokenError.errorCode = 'invalid_token'; +/** + * Method not allowed error - The HTTP method used is not allowed for this endpoint. + * (Custom, non-standard error) + */ +export class MethodNotAllowedError extends OAuthError { +} +MethodNotAllowedError.errorCode = 'method_not_allowed'; +/** + * Too many requests error - Rate limit exceeded. + * (Custom, non-standard error based on RFC 6585) + */ +export class TooManyRequestsError extends OAuthError { +} +TooManyRequestsError.errorCode = 'too_many_requests'; +/** + * Invalid client metadata error - The client metadata is invalid. + * (Custom error for dynamic client registration - RFC 7591) + */ +export class InvalidClientMetadataError extends OAuthError { +} +InvalidClientMetadataError.errorCode = 'invalid_client_metadata'; +/** + * Insufficient scope error - The request requires higher privileges than provided by the access token. + */ +export class InsufficientScopeError extends OAuthError { +} +InsufficientScopeError.errorCode = 'insufficient_scope'; +/** + * A utility class for defining one-off error codes + */ +export class CustomOAuthError extends OAuthError { + constructor(customErrorCode, message, errorUri) { + super(message, errorUri); + this.customErrorCode = customErrorCode; + } + get errorCode() { + return this.customErrorCode; + } +} +/** + * A full list of all OAuthErrors, enabling parsing from error responses + */ +export const OAUTH_ERRORS = { + [InvalidRequestError.errorCode]: InvalidRequestError, + [InvalidClientError.errorCode]: InvalidClientError, + [InvalidGrantError.errorCode]: InvalidGrantError, + [UnauthorizedClientError.errorCode]: UnauthorizedClientError, + [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError, + [InvalidScopeError.errorCode]: InvalidScopeError, + [AccessDeniedError.errorCode]: AccessDeniedError, + [ServerError.errorCode]: ServerError, + [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError, + [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError, + [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError, + [InvalidTokenError.errorCode]: InvalidTokenError, + [MethodNotAllowedError.errorCode]: MethodNotAllowedError, + [TooManyRequestsError.errorCode]: TooManyRequestsError, + [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError, + [InsufficientScopeError.errorCode]: InsufficientScopeError +}; +//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/errors.js.map b/dist/esm/server/auth/errors.js.map new file mode 100644 index 0000000000..374731d279 --- /dev/null +++ b/dist/esm/server/auth/errors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../src/server/auth/errors.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,OAAO,UAAW,SAAQ,KAAK;IAGjC,YACI,OAAe,EACC,QAAiB;QAEjC,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,aAAQ,GAAR,QAAQ,CAAS;QAGjC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;IACtC,CAAC;IAED;;OAEG;IACH,gBAAgB;QACZ,MAAM,QAAQ,GAAuB;YACjC,KAAK,EAAE,IAAI,CAAC,SAAS;YACrB,iBAAiB,EAAE,IAAI,CAAC,OAAO;SAClC,CAAC;QAEF,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAChB,QAAQ,CAAC,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC;QACvC,CAAC;QAED,OAAO,QAAQ,CAAC;IACpB,CAAC;IAED,IAAI,SAAS;QACT,OAAQ,IAAI,CAAC,WAAiC,CAAC,SAAS,CAAC;IAC7D,CAAC;CACJ;AAED;;;;GAIG;AACH,MAAM,OAAO,mBAAoB,SAAQ,UAAU;;AACxC,6BAAS,GAAG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CAAC,SAAS,CAAC,EAAE,sBAAsB;CACpD,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/authorize.d.ts b/dist/esm/server/auth/handlers/authorize.d.ts new file mode 100644 index 0000000000..38e9829bd2 --- /dev/null +++ b/dist/esm/server/auth/handlers/authorize.d.ts @@ -0,0 +1,13 @@ +import { RequestHandler } from 'express'; +import { OAuthServerProvider } from '../provider.js'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type AuthorizationHandlerOptions = { + provider: OAuthServerProvider; + /** + * Rate limiting configuration for the authorization endpoint. + * Set to false to disable rate limiting for this endpoint. + */ + rateLimit?: Partial | false; +}; +export declare function authorizationHandler({ provider, rateLimit: rateLimitConfig }: AuthorizationHandlerOptions): RequestHandler; +//# sourceMappingURL=authorize.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/authorize.d.ts.map b/dist/esm/server/auth/handlers/authorize.d.ts.map new file mode 100644 index 0000000000..b067988349 --- /dev/null +++ b/dist/esm/server/auth/handlers/authorize.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"authorize.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/authorize.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAGzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,2BAA2B,GAAG;IACtC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAqBF,wBAAgB,oBAAoB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,2BAA2B,GAAG,cAAc,CAgH1H"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/authorize.js b/dist/esm/server/auth/handlers/authorize.js new file mode 100644 index 0000000000..e29f09438e --- /dev/null +++ b/dist/esm/server/auth/handlers/authorize.js @@ -0,0 +1,138 @@ +import * as z from 'zod/v4'; +import express from 'express'; +import { rateLimit } from 'express-rate-limit'; +import { allowedMethods } from '../middleware/allowedMethods.js'; +import { InvalidRequestError, InvalidClientError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; +// Parameters that must be validated in order to issue redirects. +const ClientAuthorizationParamsSchema = z.object({ + client_id: z.string(), + redirect_uri: z + .string() + .optional() + .refine(value => value === undefined || URL.canParse(value), { message: 'redirect_uri must be a valid URL' }) +}); +// Parameters that must be validated for a successful authorization request. Failure can be reported to the redirect URI. +const RequestAuthorizationParamsSchema = z.object({ + response_type: z.literal('code'), + code_challenge: z.string(), + code_challenge_method: z.literal('S256'), + scope: z.string().optional(), + state: z.string().optional(), + resource: z.string().url().optional() +}); +export function authorizationHandler({ provider, rateLimit: rateLimitConfig }) { + // Create a router to apply middleware + const router = express.Router(); + router.use(allowedMethods(['GET', 'POST'])); + router.use(express.urlencoded({ extended: false })); + // Apply rate limiting unless explicitly disabled + if (rateLimitConfig !== false) { + router.use(rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, // 100 requests per windowMs + standardHeaders: true, + legacyHeaders: false, + message: new TooManyRequestsError('You have exceeded the rate limit for authorization requests').toResponseObject(), + ...rateLimitConfig + })); + } + router.all('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + // In the authorization flow, errors are split into two categories: + // 1. Pre-redirect errors (direct response with 400) + // 2. Post-redirect errors (redirect with error parameters) + // Phase 1: Validate client_id and redirect_uri. Any errors here must be direct responses. + let client_id, redirect_uri, client; + try { + const result = ClientAuthorizationParamsSchema.safeParse(req.method === 'POST' ? req.body : req.query); + if (!result.success) { + throw new InvalidRequestError(result.error.message); + } + client_id = result.data.client_id; + redirect_uri = result.data.redirect_uri; + client = await provider.clientsStore.getClient(client_id); + if (!client) { + throw new InvalidClientError('Invalid client_id'); + } + if (redirect_uri !== undefined) { + if (!client.redirect_uris.includes(redirect_uri)) { + throw new InvalidRequestError('Unregistered redirect_uri'); + } + } + else if (client.redirect_uris.length === 1) { + redirect_uri = client.redirect_uris[0]; + } + else { + throw new InvalidRequestError('redirect_uri must be specified when client has multiple registered URIs'); + } + } + catch (error) { + // Pre-redirect errors - return direct response + // + // These don't need to be JSON encoded, as they'll be displayed in a user + // agent, but OTOH they all represent exceptional situations (arguably, + // "programmer error"), so presenting a nice HTML page doesn't help the + // user anyway. + if (error instanceof OAuthError) { + const status = error instanceof ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + return; + } + // Phase 2: Validate other parameters. Any errors here should go into redirect responses. + let state; + try { + // Parse and validate authorization parameters + const parseResult = RequestAuthorizationParamsSchema.safeParse(req.method === 'POST' ? req.body : req.query); + if (!parseResult.success) { + throw new InvalidRequestError(parseResult.error.message); + } + const { scope, code_challenge, resource } = parseResult.data; + state = parseResult.data.state; + // Validate scopes + let requestedScopes = []; + if (scope !== undefined) { + requestedScopes = scope.split(' '); + } + // All validation passed, proceed with authorization + await provider.authorize(client, { + state, + scopes: requestedScopes, + redirectUri: redirect_uri, + codeChallenge: code_challenge, + resource: resource ? new URL(resource) : undefined + }, res); + } + catch (error) { + // Post-redirect errors - redirect with error parameters + if (error instanceof OAuthError) { + res.redirect(302, createErrorRedirect(redirect_uri, error, state)); + } + else { + const serverError = new ServerError('Internal Server Error'); + res.redirect(302, createErrorRedirect(redirect_uri, serverError, state)); + } + } + }); + return router; +} +/** + * Helper function to create redirect URL with error parameters + */ +function createErrorRedirect(redirectUri, error, state) { + const errorUrl = new URL(redirectUri); + errorUrl.searchParams.set('error', error.errorCode); + errorUrl.searchParams.set('error_description', error.message); + if (error.errorUri) { + errorUrl.searchParams.set('error_uri', error.errorUri); + } + if (state) { + errorUrl.searchParams.set('state', state); + } + return errorUrl.href; +} +//# sourceMappingURL=authorize.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/authorize.js.map b/dist/esm/server/auth/handlers/authorize.js.map new file mode 100644 index 0000000000..6911f9a386 --- /dev/null +++ b/dist/esm/server/auth/handlers/authorize.js.map @@ -0,0 +1 @@ +{"version":3,"file":"authorize.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/authorize.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,OAAO,MAAM,SAAS,CAAC;AAE9B,OAAO,EAAE,SAAS,EAA+B,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,WAAW,EAAE,oBAAoB,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAWtH,iEAAiE;AACjE,MAAM,+BAA+B,GAAG,CAAC,CAAC,MAAM,CAAC;IAC7C,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,YAAY,EAAE,CAAC;SACV,MAAM,EAAE;SACR,QAAQ,EAAE;SACV,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,KAAK,SAAS,IAAI,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,EAAE,OAAO,EAAE,kCAAkC,EAAE,CAAC;CACpH,CAAC,CAAC;AAEH,yHAAyH;AACzH,MAAM,gCAAgC,GAAG,CAAC,CAAC,MAAM,CAAC;IAC9C,aAAa,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC;IAChC,cAAc,EAAE,CAAC,CAAC,MAAM,EAAE;IAC1B,qBAAqB,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC;IACxC,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC5B,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;I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xD,IAAI,KAAK,YAAY,UAAU,EAAE,CAAC;gBAC9B,GAAG,CAAC,QAAQ,CAAC,GAAG,EAAE,mBAAmB,CAAC,YAAY,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;YACvE,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,WAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,QAAQ,CAAC,GAAG,EAAE,mBAAmB,CAAC,YAAY,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC,CAAC;YAC7E,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;GAEG;AACH,SAAS,mBAAmB,CAAC,WAAmB,EAAE,KAAiB,EAAE,KAAc;IAC/E,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,WAAW,CAAC,CAAC;IACtC,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IACpD,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,mBAAmB,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;IAC9D,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;QACjB,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,WAAW,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC3D,CAAC;IACD,IAAI,KAAK,EAAE,CAAC;QACR,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC9C,CAAC;IACD,OAAO,QAAQ,CAAC,IAAI,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/metadata.d.ts b/dist/esm/server/auth/handlers/metadata.d.ts new file mode 100644 index 0000000000..4d03286170 --- /dev/null +++ b/dist/esm/server/auth/handlers/metadata.d.ts @@ -0,0 +1,4 @@ +import { RequestHandler } from 'express'; +import { OAuthMetadata, OAuthProtectedResourceMetadata } from '../../../shared/auth.js'; +export declare function metadataHandler(metadata: OAuthMetadata | OAuthProtectedResourceMetadata): RequestHandler; +//# sourceMappingURL=metadata.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/metadata.d.ts.map b/dist/esm/server/auth/handlers/metadata.d.ts.map new file mode 100644 index 0000000000..55e3a50dc1 --- /dev/null +++ b/dist/esm/server/auth/handlers/metadata.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"metadata.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/metadata.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,8BAA8B,EAAE,MAAM,yBAAyB,CAAC;AAIxF,wBAAgB,eAAe,CAAC,QAAQ,EAAE,aAAa,GAAG,8BAA8B,GAAG,cAAc,CAaxG"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/metadata.js b/dist/esm/server/auth/handlers/metadata.js new file mode 100644 index 0000000000..94dadb709e --- /dev/null +++ b/dist/esm/server/auth/handlers/metadata.js @@ -0,0 +1,15 @@ +import express from 'express'; +import cors from 'cors'; +import { allowedMethods } from '../middleware/allowedMethods.js'; +export function metadataHandler(metadata) { + // Nested router so we can configure middleware and restrict HTTP method + const router = express.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use(cors()); + router.use(allowedMethods(['GET', 'OPTIONS'])); + router.get('/', (req, res) => { + res.status(200).json(metadata); + }); + return router; +} +//# sourceMappingURL=metadata.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/metadata.js.map b/dist/esm/server/auth/handlers/metadata.js.map new file mode 100644 index 0000000000..625ed947d2 --- /dev/null +++ b/dist/esm/server/auth/handlers/metadata.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/metadata.ts"],"names":[],"mappings":"AAAA,OAAO,OAA2B,MAAM,SAAS,CAAC;AAElD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAEjE,MAAM,UAAU,eAAe,CAAC,QAAwD;IACpF,wEAAwE;IACxE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAEhC,kFAAkF;IAClF,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;IAEnB,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;IAC/C,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;QACzB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACnC,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/register.d.ts b/dist/esm/server/auth/handlers/register.d.ts new file mode 100644 index 0000000000..e9add28458 --- /dev/null +++ b/dist/esm/server/auth/handlers/register.d.ts @@ -0,0 +1,29 @@ +import { RequestHandler } from 'express'; +import { OAuthRegisteredClientsStore } from '../clients.js'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type ClientRegistrationHandlerOptions = { + /** + * A store used to save information about dynamically registered OAuth clients. + */ + clientsStore: OAuthRegisteredClientsStore; + /** + * The number of seconds after which to expire issued client secrets, or 0 to prevent expiration of client secrets (not recommended). + * + * If not set, defaults to 30 days. + */ + clientSecretExpirySeconds?: number; + /** + * Rate limiting configuration for the client registration endpoint. + * Set to false to disable rate limiting for this endpoint. + * Registration endpoints are particularly sensitive to abuse and should be rate limited. + */ + rateLimit?: Partial | false; + /** + * Whether to generate a client ID before calling the client registration endpoint. + * + * If not set, defaults to true. + */ + clientIdGeneration?: boolean; +}; +export declare function clientRegistrationHandler({ clientsStore, clientSecretExpirySeconds, rateLimit: rateLimitConfig, clientIdGeneration }: ClientRegistrationHandlerOptions): RequestHandler; +//# sourceMappingURL=register.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/register.d.ts.map b/dist/esm/server/auth/handlers/register.d.ts.map new file mode 100644 index 0000000000..a38ebdb89e --- /dev/null +++ b/dist/esm/server/auth/handlers/register.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"register.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/register.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAIlD,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,gCAAgC,GAAG;IAC3C;;OAEG;IACH,YAAY,EAAE,2BAA2B,CAAC;IAE1C;;;;OAIG;IACH,yBAAyB,CAAC,EAAE,MAAM,CAAC;IAEnC;;;;OAIG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;IAE9C;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAChC,CAAC;AAIF,wBAAgB,yBAAyB,CAAC,EACtC,YAAY,EACZ,yBAAgE,EAChE,SAAS,EAAE,eAAe,EAC1B,kBAAyB,EAC5B,EAAE,gCAAgC,GAAG,cAAc,CA0EnD"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/register.js b/dist/esm/server/auth/handlers/register.js new file mode 100644 index 0000000000..ef6c44d518 --- /dev/null +++ b/dist/esm/server/auth/handlers/register.js @@ -0,0 +1,71 @@ +import express from 'express'; +import { OAuthClientMetadataSchema } from '../../../shared/auth.js'; +import crypto from 'node:crypto'; +import cors from 'cors'; +import { rateLimit } from 'express-rate-limit'; +import { allowedMethods } from '../middleware/allowedMethods.js'; +import { InvalidClientMetadataError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; +const DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS = 30 * 24 * 60 * 60; // 30 days +export function clientRegistrationHandler({ clientsStore, clientSecretExpirySeconds = DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS, rateLimit: rateLimitConfig, clientIdGeneration = true }) { + if (!clientsStore.registerClient) { + throw new Error('Client registration store does not support registering clients'); + } + // Nested router so we can configure middleware and restrict HTTP method + const router = express.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use(cors()); + router.use(allowedMethods(['POST'])); + router.use(express.json()); + // Apply rate limiting unless explicitly disabled - stricter limits for registration + if (rateLimitConfig !== false) { + router.use(rateLimit({ + windowMs: 60 * 60 * 1000, // 1 hour + max: 20, // 20 requests per hour - stricter as registration is sensitive + standardHeaders: true, + legacyHeaders: false, + message: new TooManyRequestsError('You have exceeded the rate limit for client registration requests').toResponseObject(), + ...rateLimitConfig + })); + } + router.post('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + try { + const parseResult = OAuthClientMetadataSchema.safeParse(req.body); + if (!parseResult.success) { + throw new InvalidClientMetadataError(parseResult.error.message); + } + const clientMetadata = parseResult.data; + const isPublicClient = clientMetadata.token_endpoint_auth_method === 'none'; + // Generate client credentials + const clientSecret = isPublicClient ? undefined : crypto.randomBytes(32).toString('hex'); + const clientIdIssuedAt = Math.floor(Date.now() / 1000); + // Calculate client secret expiry time + const clientsDoExpire = clientSecretExpirySeconds > 0; + const secretExpiryTime = clientsDoExpire ? clientIdIssuedAt + clientSecretExpirySeconds : 0; + const clientSecretExpiresAt = isPublicClient ? undefined : secretExpiryTime; + let clientInfo = { + ...clientMetadata, + client_secret: clientSecret, + client_secret_expires_at: clientSecretExpiresAt + }; + if (clientIdGeneration) { + clientInfo.client_id = crypto.randomUUID(); + clientInfo.client_id_issued_at = clientIdIssuedAt; + } + clientInfo = await clientsStore.registerClient(clientInfo); + res.status(201).json(clientInfo); + } + catch (error) { + if (error instanceof OAuthError) { + const status = error instanceof ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }); + return router; +} +//# sourceMappingURL=register.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/register.js.map b/dist/esm/server/auth/handlers/register.js.map new file mode 100644 index 0000000000..3f4c082f04 --- /dev/null +++ b/dist/esm/server/auth/handlers/register.js.map @@ -0,0 +1 @@ +{"version":3,"file":"register.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/register.ts"],"names":[],"mappings":"AAAA,OAAO,OAA2B,MAAM,SAAS,CAAC;AAClD,OAAO,EAA8B,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AAChG,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,OAAO,EAAE,SAAS,EAA+B,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,0BAA0B,EAAE,WAAW,EAAE,oBAAoB,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AA8BzG,MAAM,oCAAoC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,UAAU;AAE1E,MAAM,UAAU,yBAAyB,CAAC,EACtC,YAAY,EACZ,yBAAyB,GAAG,oCAAoC,EAChE,SAAS,EAAE,eAAe,EAC1B,kBAAkB,GAAG,IAAI,EACM;IAC/B,IAAI,CAAC,YAAY,CAAC,cAAc,EAAE,CAAC;QAC/B,MAAM,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAC;IACtF,CAAC;IAED,wEAAwE;IACxE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAEhC,kFAAkF;IAClF,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;IAEnB,MAAM,CAAC,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ClB,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/revoke.d.ts b/dist/esm/server/auth/handlers/revoke.d.ts new file mode 100644 index 0000000000..2be32bb3ca --- /dev/null +++ b/dist/esm/server/auth/handlers/revoke.d.ts @@ -0,0 +1,13 @@ +import { OAuthServerProvider } from '../provider.js'; +import { RequestHandler } from 'express'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type RevocationHandlerOptions = { + provider: OAuthServerProvider; + /** + * Rate limiting configuration for the token revocation endpoint. + * Set to false to disable rate limiting for this endpoint. + */ + rateLimit?: Partial | false; +}; +export declare function revocationHandler({ provider, rateLimit: rateLimitConfig }: RevocationHandlerOptions): RequestHandler; +//# sourceMappingURL=revoke.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/revoke.d.ts.map b/dist/esm/server/auth/handlers/revoke.d.ts.map new file mode 100644 index 0000000000..fb13cf19fe --- /dev/null +++ b/dist/esm/server/auth/handlers/revoke.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"revoke.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/revoke.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAIlD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,wBAAwB,GAAG;IACnC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAEF,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,wBAAwB,GAAG,cAAc,CA4DpH"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/revoke.js b/dist/esm/server/auth/handlers/revoke.js new file mode 100644 index 0000000000..68f5284dd4 --- /dev/null +++ b/dist/esm/server/auth/handlers/revoke.js @@ -0,0 +1,59 @@ +import express from 'express'; +import cors from 'cors'; +import { authenticateClient } from '../middleware/clientAuth.js'; +import { OAuthTokenRevocationRequestSchema } from '../../../shared/auth.js'; +import { rateLimit } from 'express-rate-limit'; +import { allowedMethods } from '../middleware/allowedMethods.js'; +import { InvalidRequestError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; +export function revocationHandler({ provider, rateLimit: rateLimitConfig }) { + if (!provider.revokeToken) { + throw new Error('Auth provider does not support revoking tokens'); + } + // Nested router so we can configure middleware and restrict HTTP method + const router = express.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use(cors()); + router.use(allowedMethods(['POST'])); + router.use(express.urlencoded({ extended: false })); + // Apply rate limiting unless explicitly disabled + if (rateLimitConfig !== false) { + router.use(rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 50, // 50 requests per windowMs + standardHeaders: true, + legacyHeaders: false, + message: new TooManyRequestsError('You have exceeded the rate limit for token revocation requests').toResponseObject(), + ...rateLimitConfig + })); + } + // Authenticate and extract client details + router.use(authenticateClient({ clientsStore: provider.clientsStore })); + router.post('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + try { + const parseResult = OAuthTokenRevocationRequestSchema.safeParse(req.body); + if (!parseResult.success) { + throw new InvalidRequestError(parseResult.error.message); + } + const client = req.client; + if (!client) { + // This should never happen + throw new ServerError('Internal Server Error'); + } + await provider.revokeToken(client, parseResult.data); + res.status(200).json({}); + } + catch (error) { + if (error instanceof OAuthError) { + const status = error instanceof ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }); + return router; +} +//# sourceMappingURL=revoke.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/revoke.js.map b/dist/esm/server/auth/handlers/revoke.js.map new file mode 100644 index 0000000000..e1a0b1db98 --- /dev/null +++ b/dist/esm/server/auth/handlers/revoke.js.map @@ -0,0 +1 @@ +{"version":3,"file":"revoke.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/revoke.ts"],"names":[],"mappings":"AACA,OAAO,OAA2B,MAAM,SAAS,CAAC;AAClD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,iCAAiC,EAAE,MAAM,yBAAyB,CAAC;AAC5E,OAAO,EAAE,SAAS,EAA+B,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,oBAAoB,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAWlG,MAAM,UAAU,iBAAiB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAA4B;IAChG,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;IACtE,CAAC;IAED,wEAAwE;IACxE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAEhC,kFAAkF;IAClF,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;IAEnB,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACrC,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC;IAEpD,iDAAiD;IACjD,IAAI,eAAe,KAAK,KAAK,EAAE,CAAC;QAC5B,MAAM,CAAC,GAAG,CACN,SAAS,CAAC;YACN,QAAQ,EAAE,EAAE,GAAG,EAAE,GAAG,IAAI,EAAE,aAAa;YACvC,GAAG,EAAE,EAAE,EAAE,2BAA2B;YACpC,eAAe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K,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,WAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/token.d.ts b/dist/esm/server/auth/handlers/token.d.ts new file mode 100644 index 0000000000..24d1c8783b --- /dev/null +++ b/dist/esm/server/auth/handlers/token.d.ts @@ -0,0 +1,13 @@ +import { RequestHandler } from 'express'; +import { OAuthServerProvider } from '../provider.js'; +import { Options as RateLimitOptions } from 'express-rate-limit'; +export type TokenHandlerOptions = { + provider: OAuthServerProvider; + /** + * Rate limiting configuration for the token endpoint. + * Set to false to disable rate limiting for this endpoint. + */ + rateLimit?: Partial | false; +}; +export declare function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHandlerOptions): RequestHandler; +//# sourceMappingURL=token.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/token.d.ts.map b/dist/esm/server/auth/handlers/token.d.ts.map new file mode 100644 index 0000000000..3d539f3451 --- /dev/null +++ b/dist/esm/server/auth/handlers/token.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/token.ts"],"names":[],"mappings":"AACA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAIrD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAW5E,MAAM,MAAM,mBAAmB,GAAG;IAC9B,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAmBF,wBAAgB,YAAY,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,mBAAmB,GAAG,cAAc,CAiH1G"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/token.js b/dist/esm/server/auth/handlers/token.js new file mode 100644 index 0000000000..da9341e278 --- /dev/null +++ b/dist/esm/server/auth/handlers/token.js @@ -0,0 +1,107 @@ +import * as z from 'zod/v4'; +import express from 'express'; +import cors from 'cors'; +import { verifyChallenge } from 'pkce-challenge'; +import { authenticateClient } from '../middleware/clientAuth.js'; +import { rateLimit } from 'express-rate-limit'; +import { allowedMethods } from '../middleware/allowedMethods.js'; +import { InvalidRequestError, InvalidGrantError, UnsupportedGrantTypeError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; +const TokenRequestSchema = z.object({ + grant_type: z.string() +}); +const AuthorizationCodeGrantSchema = z.object({ + code: z.string(), + code_verifier: z.string(), + redirect_uri: z.string().optional(), + resource: z.string().url().optional() +}); +const RefreshTokenGrantSchema = z.object({ + refresh_token: z.string(), + scope: z.string().optional(), + resource: z.string().url().optional() +}); +export function tokenHandler({ provider, rateLimit: rateLimitConfig }) { + // Nested router so we can configure middleware and restrict HTTP method + const router = express.Router(); + // Configure CORS to allow any origin, to make accessible to web-based MCP clients + router.use(cors()); + router.use(allowedMethods(['POST'])); + router.use(express.urlencoded({ extended: false })); + // Apply rate limiting unless explicitly disabled + if (rateLimitConfig !== false) { + router.use(rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 50, // 50 requests per windowMs + standardHeaders: true, + legacyHeaders: false, + message: new TooManyRequestsError('You have exceeded the rate limit for token requests').toResponseObject(), + ...rateLimitConfig + })); + } + // Authenticate and extract client details + router.use(authenticateClient({ clientsStore: provider.clientsStore })); + router.post('/', async (req, res) => { + res.setHeader('Cache-Control', 'no-store'); + try { + const parseResult = TokenRequestSchema.safeParse(req.body); + if (!parseResult.success) { + throw new InvalidRequestError(parseResult.error.message); + } + const { grant_type } = parseResult.data; + const client = req.client; + if (!client) { + // This should never happen + throw new ServerError('Internal Server Error'); + } + switch (grant_type) { + case 'authorization_code': { + const parseResult = AuthorizationCodeGrantSchema.safeParse(req.body); + if (!parseResult.success) { + throw new InvalidRequestError(parseResult.error.message); + } + const { code, code_verifier, redirect_uri, resource } = parseResult.data; + const skipLocalPkceValidation = provider.skipLocalPkceValidation; + // Perform local PKCE validation unless explicitly skipped + // (e.g. to validate code_verifier in upstream server) + if (!skipLocalPkceValidation) { + const codeChallenge = await provider.challengeForAuthorizationCode(client, code); + if (!(await verifyChallenge(code_verifier, codeChallenge))) { + throw new InvalidGrantError('code_verifier does not match the challenge'); + } + } + // Passes the code_verifier to the provider if PKCE validation didn't occur locally + const tokens = await provider.exchangeAuthorizationCode(client, code, skipLocalPkceValidation ? code_verifier : undefined, redirect_uri, resource ? new URL(resource) : undefined); + res.status(200).json(tokens); + break; + } + case 'refresh_token': { + const parseResult = RefreshTokenGrantSchema.safeParse(req.body); + if (!parseResult.success) { + throw new InvalidRequestError(parseResult.error.message); + } + const { refresh_token, scope, resource } = parseResult.data; + const scopes = scope === null || scope === void 0 ? void 0 : scope.split(' '); + const tokens = await provider.exchangeRefreshToken(client, refresh_token, scopes, resource ? new URL(resource) : undefined); + res.status(200).json(tokens); + break; + } + // Not supported right now + //case "client_credentials": + default: + throw new UnsupportedGrantTypeError('The grant type is not supported by this authorization server.'); + } + } + catch (error) { + if (error instanceof OAuthError) { + const status = error instanceof ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }); + return router; +} +//# sourceMappingURL=token.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/token.js.map b/dist/esm/server/auth/handlers/token.js.map new file mode 100644 index 0000000000..312f568a2f --- /dev/null +++ b/dist/esm/server/auth/handlers/token.js.map @@ -0,0 +1 @@ +{"version":3,"file":"token.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/token.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,OAA2B,MAAM,SAAS,CAAC;AAElD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,SAAS,EAA+B,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EACH,mBAAmB,EACnB,iBAAiB,EACjB,yBAAyB,EACzB,WAAW,EACX,oBAAoB,EACpB,UAAU,EACb,MAAM,cAAc,CAAC;AAWtB,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAC;IAChC,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE;CACzB,CAAC,CAAC;AAEH,MAAM,4BAA4B,GAAG,CAAC,CAAC,MAAM,CAAC;IAC1C,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE;IAChB,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE;IACzB,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IACnC,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE;CACxC,CAAC,CAAC;AAEH,MAAM,uBAAuB,GAAG,CAAC,CAAC,MAAM,CAAC;IACrC,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE;IACzB,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC5B,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE;CACxC,CAAC,CAAC;AAEH,MAAM,UAAU,YA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AK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,WAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/allowedMethods.d.ts b/dist/esm/server/auth/middleware/allowedMethods.d.ts new file mode 100644 index 0000000000..ee6037e0de --- /dev/null +++ b/dist/esm/server/auth/middleware/allowedMethods.d.ts @@ -0,0 +1,9 @@ +import { RequestHandler } from 'express'; +/** + * Middleware to handle unsupported HTTP methods with a 405 Method Not Allowed response. + * + * @param allowedMethods Array of allowed HTTP methods for this endpoint (e.g., ['GET', 'POST']) + * @returns Express middleware that returns a 405 error if method not in allowed list + */ +export declare function allowedMethods(allowedMethods: string[]): RequestHandler; +//# sourceMappingURL=allowedMethods.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/allowedMethods.d.ts.map b/dist/esm/server/auth/middleware/allowedMethods.d.ts.map new file mode 100644 index 0000000000..d3de93e242 --- /dev/null +++ b/dist/esm/server/auth/middleware/allowedMethods.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"allowedMethods.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/allowedMethods.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAGzC;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,cAAc,EAAE,MAAM,EAAE,GAAG,cAAc,CAUvE"} \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/allowedMethods.js b/dist/esm/server/auth/middleware/allowedMethods.js new file mode 100644 index 0000000000..af2ba08923 --- /dev/null +++ b/dist/esm/server/auth/middleware/allowedMethods.js @@ -0,0 +1,18 @@ +import { MethodNotAllowedError } from '../errors.js'; +/** + * Middleware to handle unsupported HTTP methods with a 405 Method Not Allowed response. + * + * @param allowedMethods Array of allowed HTTP methods for this endpoint (e.g., ['GET', 'POST']) + * @returns Express middleware that returns a 405 error if method not in allowed list + */ +export function allowedMethods(allowedMethods) { + return (req, res, next) => { + if (allowedMethods.includes(req.method)) { + next(); + return; + } + const error = new MethodNotAllowedError(`The method ${req.method} is not allowed for this endpoint`); + res.status(405).set('Allow', allowedMethods.join(', ')).json(error.toResponseObject()); + }; +} +//# sourceMappingURL=allowedMethods.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/allowedMethods.js.map b/dist/esm/server/auth/middleware/allowedMethods.js.map new file mode 100644 index 0000000000..c410979868 --- /dev/null +++ b/dist/esm/server/auth/middleware/allowedMethods.js.map @@ -0,0 +1 @@ +{"version":3,"file":"allowedMethods.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/allowedMethods.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAErD;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,cAAwB;IACnD,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACtB,IAAI,cAAc,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;YACtC,IAAI,EAAE,CAAC;YACP,OAAO;QACX,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,qBAAqB,CAAC,cAAc,GAAG,CAAC,MAAM,mCAAmC,CAAC,CAAC;QACrG,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;IAC3F,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/bearerAuth.d.ts b/dist/esm/server/auth/middleware/bearerAuth.d.ts new file mode 100644 index 0000000000..10730758bc --- /dev/null +++ b/dist/esm/server/auth/middleware/bearerAuth.d.ts @@ -0,0 +1,35 @@ +import { RequestHandler } from 'express'; +import { OAuthTokenVerifier } from '../provider.js'; +import { AuthInfo } from '../types.js'; +export type BearerAuthMiddlewareOptions = { + /** + * A provider used to verify tokens. + */ + verifier: OAuthTokenVerifier; + /** + * Optional scopes that the token must have. + */ + requiredScopes?: string[]; + /** + * Optional resource metadata URL to include in WWW-Authenticate header. + */ + resourceMetadataUrl?: string; +}; +declare module 'express-serve-static-core' { + interface Request { + /** + * Information about the validated access token, if the `requireBearerAuth` middleware was used. + */ + auth?: AuthInfo; + } +} +/** + * Middleware that requires a valid Bearer token in the Authorization header. + * + * This will validate the token with the auth provider and add the resulting auth info to the request object. + * + * If resourceMetadataUrl is provided, it will be included in the WWW-Authenticate header + * for 401 responses as per the OAuth 2.0 Protected Resource Metadata spec. + */ +export declare function requireBearerAuth({ verifier, requiredScopes, resourceMetadataUrl }: BearerAuthMiddlewareOptions): RequestHandler; +//# sourceMappingURL=bearerAuth.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/bearerAuth.d.ts.map b/dist/esm/server/auth/middleware/bearerAuth.d.ts.map new file mode 100644 index 0000000000..c9d939f3b7 --- /dev/null +++ b/dist/esm/server/auth/middleware/bearerAuth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"bearerAuth.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/bearerAuth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,MAAM,MAAM,2BAA2B,GAAG;IACtC;;OAEG;IACH,QAAQ,EAAE,kBAAkB,CAAC;IAE7B;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAE1B;;OAEG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAChC,CAAC;AAEF,OAAO,QAAQ,2BAA2B,CAAC;IACvC,UAAU,OAAO;QACb;;WAEG;QACH,IAAI,CAAC,EAAE,QAAQ,CAAC;KACnB;CACJ;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,cAAmB,EAAE,mBAAmB,EAAE,EAAE,2BAA2B,GAAG,cAAc,CA8DrI"} \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/bearerAuth.js b/dist/esm/server/auth/middleware/bearerAuth.js new file mode 100644 index 0000000000..0c527b4f42 --- /dev/null +++ b/dist/esm/server/auth/middleware/bearerAuth.js @@ -0,0 +1,72 @@ +import { InsufficientScopeError, InvalidTokenError, OAuthError, ServerError } from '../errors.js'; +/** + * Middleware that requires a valid Bearer token in the Authorization header. + * + * This will validate the token with the auth provider and add the resulting auth info to the request object. + * + * If resourceMetadataUrl is provided, it will be included in the WWW-Authenticate header + * for 401 responses as per the OAuth 2.0 Protected Resource Metadata spec. + */ +export function requireBearerAuth({ verifier, requiredScopes = [], resourceMetadataUrl }) { + return async (req, res, next) => { + try { + const authHeader = req.headers.authorization; + if (!authHeader) { + throw new InvalidTokenError('Missing Authorization header'); + } + const [type, token] = authHeader.split(' '); + if (type.toLowerCase() !== 'bearer' || !token) { + throw new InvalidTokenError("Invalid Authorization header format, expected 'Bearer TOKEN'"); + } + const authInfo = await verifier.verifyAccessToken(token); + // Check if token has the required scopes (if any) + if (requiredScopes.length > 0) { + const hasAllScopes = requiredScopes.every(scope => authInfo.scopes.includes(scope)); + if (!hasAllScopes) { + throw new InsufficientScopeError('Insufficient scope'); + } + } + // Check if the token is set to expire or if it is expired + if (typeof authInfo.expiresAt !== 'number' || isNaN(authInfo.expiresAt)) { + throw new InvalidTokenError('Token has no expiration time'); + } + else if (authInfo.expiresAt < Date.now() / 1000) { + throw new InvalidTokenError('Token has expired'); + } + req.auth = authInfo; + next(); + } + catch (error) { + // Build WWW-Authenticate header parts + const buildWwwAuthHeader = (errorCode, message) => { + let header = `Bearer error="${errorCode}", error_description="${message}"`; + if (requiredScopes.length > 0) { + header += `, scope="${requiredScopes.join(' ')}"`; + } + if (resourceMetadataUrl) { + header += `, resource_metadata="${resourceMetadataUrl}"`; + } + return header; + }; + if (error instanceof InvalidTokenError) { + res.set('WWW-Authenticate', buildWwwAuthHeader(error.errorCode, error.message)); + res.status(401).json(error.toResponseObject()); + } + else if (error instanceof InsufficientScopeError) { + res.set('WWW-Authenticate', buildWwwAuthHeader(error.errorCode, error.message)); + res.status(403).json(error.toResponseObject()); + } + else if (error instanceof ServerError) { + res.status(500).json(error.toResponseObject()); + } + else if (error instanceof OAuthError) { + res.status(400).json(error.toResponseObject()); + } + else { + const serverError = new ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }; +} +//# sourceMappingURL=bearerAuth.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/bearerAuth.js.map b/dist/esm/server/auth/middleware/bearerAuth.js.map new file mode 100644 index 0000000000..d8d0179b76 --- /dev/null +++ b/dist/esm/server/auth/middleware/bearerAuth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bearerAuth.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/bearerAuth.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AA8BlG;;;;;;;GAOG;AACH,MAAM,UAAU,iBAAiB,CAAC,EAAE,QAAQ,EAAE,cAAc,GAAG,EAAE,EAAE,mBAAmB,EAA+B;IACjH,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC5B,IAAI,CAAC;YACD,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,C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AAE,CAAC,CAAC;YACnD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,WAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/clientAuth.d.ts b/dist/esm/server/auth/middleware/clientAuth.d.ts new file mode 100644 index 0000000000..837f95fd29 --- /dev/null +++ b/dist/esm/server/auth/middleware/clientAuth.d.ts @@ -0,0 +1,19 @@ +import { RequestHandler } from 'express'; +import { OAuthRegisteredClientsStore } from '../clients.js'; +import { OAuthClientInformationFull } from '../../../shared/auth.js'; +export type ClientAuthenticationMiddlewareOptions = { + /** + * A store used to read information about registered OAuth clients. + */ + clientsStore: OAuthRegisteredClientsStore; +}; +declare module 'express-serve-static-core' { + interface Request { + /** + * The authenticated client for this request, if the `authenticateClient` middleware was used. + */ + client?: OAuthClientInformationFull; + } +} +export declare function authenticateClient({ clientsStore }: ClientAuthenticationMiddlewareOptions): RequestHandler; +//# sourceMappingURL=clientAuth.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/clientAuth.d.ts.map b/dist/esm/server/auth/middleware/clientAuth.d.ts.map new file mode 100644 index 0000000000..5dfa3924f2 --- /dev/null +++ b/dist/esm/server/auth/middleware/clientAuth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"clientAuth.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/clientAuth.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AAGrE,MAAM,MAAM,qCAAqC,GAAG;IAChD;;OAEG;IACH,YAAY,EAAE,2BAA2B,CAAC;CAC7C,CAAC;AAOF,OAAO,QAAQ,2BAA2B,CAAC;IACvC,UAAU,OAAO;QACb;;WAEG;QACH,MAAM,CAAC,EAAE,0BAA0B,CAAC;KACvC;CACJ;AAED,wBAAgB,kBAAkB,CAAC,EAAE,YAAY,EAAE,EAAE,qCAAqC,GAAG,cAAc,CA4C1G"} \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/clientAuth.js b/dist/esm/server/auth/middleware/clientAuth.js new file mode 100644 index 0000000000..04e5dfe74c --- /dev/null +++ b/dist/esm/server/auth/middleware/clientAuth.js @@ -0,0 +1,49 @@ +import * as z from 'zod/v4'; +import { InvalidRequestError, InvalidClientError, ServerError, OAuthError } from '../errors.js'; +const ClientAuthenticatedRequestSchema = z.object({ + client_id: z.string(), + client_secret: z.string().optional() +}); +export function authenticateClient({ clientsStore }) { + return async (req, res, next) => { + try { + const result = ClientAuthenticatedRequestSchema.safeParse(req.body); + if (!result.success) { + throw new InvalidRequestError(String(result.error)); + } + const { client_id, client_secret } = result.data; + const client = await clientsStore.getClient(client_id); + if (!client) { + throw new InvalidClientError('Invalid client_id'); + } + // If client has a secret, validate it + if (client.client_secret) { + // Check if client_secret is required but not provided + if (!client_secret) { + throw new InvalidClientError('Client secret is required'); + } + // Check if client_secret matches + if (client.client_secret !== client_secret) { + throw new InvalidClientError('Invalid client_secret'); + } + // Check if client_secret has expired + if (client.client_secret_expires_at && client.client_secret_expires_at < Math.floor(Date.now() / 1000)) { + throw new InvalidClientError('Client secret has expired'); + } + } + req.client = client; + next(); + } + catch (error) { + if (error instanceof OAuthError) { + const status = error instanceof ServerError ? 500 : 400; + res.status(status).json(error.toResponseObject()); + } + else { + const serverError = new ServerError('Internal Server Error'); + res.status(500).json(serverError.toResponseObject()); + } + } + }; +} +//# sourceMappingURL=clientAuth.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/clientAuth.js.map b/dist/esm/server/auth/middleware/clientAuth.js.map new file mode 100644 index 0000000000..a5f969f941 --- /dev/null +++ b/dist/esm/server/auth/middleware/clientAuth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"clientAuth.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/clientAuth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAI5B,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAShG,MAAM,gCAAgC,GAAG,CAAC,CAAC,MAAM,CAAC;IAC9C,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACvC,CAAC,CAAC;AAWH,MAAM,UAAU,kBAAkB,CAAC,EAAE,YAAY,EAAyC;IACtF,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC5B,IAAI,CAAC;YACD,MAAM,MAAM,GAAG,gCAAgC,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YACpE,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;gBAClB,MAAM,IAAI,mBAAmB,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;YACxD,CAAC;YAED,MAAM,EAAE,SAAS,EAAE,aAAa,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC;YACjD,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC;YACvD,IAAI,CAAC,MAAM,EAAE,CAAC;gBACV,MAAM,IAAI,kBAAkB,CAAC,mBAAmB,CAAC,CAAC;YACtD,CAAC;YAED,sCAAsC;YACtC,IAAI,MAAM,CAAC,aAAa,EAAE,CAAC;gBACvB,sDAAsD;gBACtD,IAAI,CAAC,aAAa,EAAE,CAAC;oBACjB,MAAM,IAAI,kBAAkB,CAAC,2BAA2B,CAAC,CAAC;gBAC9D,CAAC;gBAED,iCAAiC;gBACjC,IAAI,MAAM,CAAC,aAAa,KAAK,aAAa,EAAE,CAAC;oBACzC,MAAM,IAAI,kBAAkB,CAAC,uBAAuB,CAAC,CAAC;gBAC1D,CAAC;gBAED,qCAAqC;gBACrC,IAAI,MAAM,CAAC,wBAAwB,IAAI,MAAM,CAAC,wBAAwB,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,EAAE,CAAC;oBACrG,MAAM,IAAI,kBAAkB,CAAC,2BAA2B,CAAC,CAAC;gBAC9D,CAAC;YACL,CAAC;YAED,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC;YACpB,IAAI,EAAE,CAAC;QACX,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,KAAK,YAAY,UAAU,EAAE,CAAC;gBAC9B,MAAM,MAAM,GAAG,KAAK,YAAY,WAAW,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;gBACxD,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,WAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/provider.d.ts b/dist/esm/server/auth/provider.d.ts new file mode 100644 index 0000000000..3e4eca392c --- /dev/null +++ b/dist/esm/server/auth/provider.d.ts @@ -0,0 +1,68 @@ +import { Response } from 'express'; +import { OAuthRegisteredClientsStore } from './clients.js'; +import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../shared/auth.js'; +import { AuthInfo } from './types.js'; +export type AuthorizationParams = { + state?: string; + scopes?: string[]; + codeChallenge: string; + redirectUri: string; + resource?: URL; +}; +/** + * Implements an end-to-end OAuth server. + */ +export interface OAuthServerProvider { + /** + * A store used to read information about registered OAuth clients. + */ + get clientsStore(): OAuthRegisteredClientsStore; + /** + * Begins the authorization flow, which can either be implemented by this server itself or via redirection to a separate authorization server. + * + * This server must eventually issue a redirect with an authorization response or an error response to the given redirect URI. Per OAuth 2.1: + * - In the successful case, the redirect MUST include the `code` and `state` (if present) query parameters. + * - In the error case, the redirect MUST include the `error` query parameter, and MAY include an optional `error_description` query parameter. + */ + authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; + /** + * Returns the `codeChallenge` that was used when the indicated authorization began. + */ + challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise; + /** + * Exchanges an authorization code for an access token. + */ + exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, redirectUri?: string, resource?: URL): Promise; + /** + * Exchanges a refresh token for an access token. + */ + exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; + /** + * Verifies an access token and returns information about it. + */ + verifyAccessToken(token: string): Promise; + /** + * Revokes an access or refresh token. If unimplemented, token revocation is not supported (not recommended). + * + * If the given token is invalid or already revoked, this method should do nothing. + */ + revokeToken?(client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest): Promise; + /** + * Whether to skip local PKCE validation. + * + * If true, the server will not perform PKCE validation locally and will pass the code_verifier to the upstream server. + * + * NOTE: This should only be true if the upstream server is performing the actual PKCE validation. + */ + skipLocalPkceValidation?: boolean; +} +/** + * Slim implementation useful for token verification + */ +export interface OAuthTokenVerifier { + /** + * Verifies an access token and returns information about it. + */ + verifyAccessToken(token: string): Promise; +} +//# sourceMappingURL=provider.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/provider.d.ts.map b/dist/esm/server/auth/provider.d.ts.map new file mode 100644 index 0000000000..d1a4bfff0b --- /dev/null +++ b/dist/esm/server/auth/provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,2BAA2B,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC5G,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC,MAAM,MAAM,mBAAmB,GAAG;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,GAAG,CAAC;CAClB,CAAC;AAEF;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAChC;;OAEG;IACH,IAAI,YAAY,IAAI,2BAA2B,CAAC;IAEhD;;;;;;OAMG;IACH,SAAS,CAAC,MAAM,EAAE,0BAA0B,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEzG;;OAEG;IACH,6BAA6B,CAAC,MAAM,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAE9G;;OAEG;IACH,yBAAyB,CACrB,MAAM,EAAE,0BAA0B,EAClC,iBAAiB,EAAE,MAAM,EACzB,YAAY,CAAC,EAAE,MAAM,EACrB,WAAW,CAAC,EAAE,MAAM,EACpB,QAAQ,CAAC,EAAE,GAAG,GACf,OAAO,CAAC,WAAW,CAAC,CAAC;IAExB;;OAEG;IACH,oBAAoB,CAAC,MAAM,EAAE,0BAA0B,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,EAAE,QAAQ,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IAExI;;OAEG;IACH,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAEpD;;;;OAIG;IACH,WAAW,CAAC,CAAC,MAAM,EAAE,0BAA0B,EAAE,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEtG;;;;;;OAMG;IACH,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACrC;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IAC/B;;OAEG;IACH,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CACvD"} \ No newline at end of file diff --git a/dist/esm/server/auth/provider.js b/dist/esm/server/auth/provider.js new file mode 100644 index 0000000000..be31058cd5 --- /dev/null +++ b/dist/esm/server/auth/provider.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=provider.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/provider.js.map b/dist/esm/server/auth/provider.js.map new file mode 100644 index 0000000000..b968414aa9 --- /dev/null +++ b/dist/esm/server/auth/provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../../src/server/auth/provider.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/server/auth/providers/proxyProvider.d.ts b/dist/esm/server/auth/providers/proxyProvider.d.ts new file mode 100644 index 0000000000..ee6f350817 --- /dev/null +++ b/dist/esm/server/auth/providers/proxyProvider.d.ts @@ -0,0 +1,49 @@ +import { Response } from 'express'; +import { OAuthRegisteredClientsStore } from '../clients.js'; +import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../../shared/auth.js'; +import { AuthInfo } from '../types.js'; +import { AuthorizationParams, OAuthServerProvider } from '../provider.js'; +import { FetchLike } from '../../../shared/transport.js'; +export type ProxyEndpoints = { + authorizationUrl: string; + tokenUrl: string; + revocationUrl?: string; + registrationUrl?: string; +}; +export type ProxyOptions = { + /** + * Individual endpoint URLs for proxying specific OAuth operations + */ + endpoints: ProxyEndpoints; + /** + * Function to verify access tokens and return auth info + */ + verifyAccessToken: (token: string) => Promise; + /** + * Function to fetch client information from the upstream server + */ + getClient: (clientId: string) => Promise; + /** + * Custom fetch implementation used for all network requests. + */ + fetch?: FetchLike; +}; +/** + * Implements an OAuth server that proxies requests to another OAuth server. + */ +export declare class ProxyOAuthServerProvider implements OAuthServerProvider { + protected readonly _endpoints: ProxyEndpoints; + protected readonly _verifyAccessToken: (token: string) => Promise; + protected readonly _getClient: (clientId: string) => Promise; + protected readonly _fetch?: FetchLike; + skipLocalPkceValidation: boolean; + revokeToken?: (client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest) => Promise; + constructor(options: ProxyOptions); + get clientsStore(): OAuthRegisteredClientsStore; + authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; + challengeForAuthorizationCode(_client: OAuthClientInformationFull, _authorizationCode: string): Promise; + exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, redirectUri?: string, resource?: URL): Promise; + exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; + verifyAccessToken(token: string): Promise; +} +//# sourceMappingURL=proxyProvider.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/providers/proxyProvider.d.ts.map b/dist/esm/server/auth/providers/proxyProvider.d.ts.map new file mode 100644 index 0000000000..ba2efd1aab --- /dev/null +++ b/dist/esm/server/auth/providers/proxyProvider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"proxyProvider.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/providers/proxyProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAA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BAAuB,UAAQ;IAE/B,WAAW,CAAC,EAAE,CAAC,MAAM,EAAE,0BAA0B,EAAE,OAAO,EAAE,2BAA2B,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;gBAE9F,OAAO,EAAE,YAAY;IAsCjC,IAAI,YAAY,IAAI,2BAA2B,CAuB9C;IAEK,SAAS,CAAC,MAAM,EAAE,0BAA0B,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAoBxG,6BAA6B,CAAC,OAAO,EAAE,0BAA0B,EAAE,kBAAkB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAM/G,yBAAyB,CAC3B,MAAM,EAAE,0BAA0B,EAClC,iBAAiB,EAAE,MAAM,EACzB,YAAY,CAAC,EAAE,MAAM,EACrB,WAAW,CAAC,EAAE,MAAM,EACpB,QAAQ,CAAC,EAAE,GAAG,GACf,OAAO,CAAC,WAAW,CAAC;IAuCjB,oBAAoB,CACtB,MAAM,EAAE,0BAA0B,EAClC,YAAY,EAAE,MAAM,EACpB,MAAM,CAAC,EAAE,MAAM,EAAE,EACjB,QAAQ,CAAC,EAAE,GAAG,GACf,OAAO,CAAC,WAAW,CAAC;IAmCjB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;CAG5D"} \ No newline at end of file diff --git a/dist/esm/server/auth/providers/proxyProvider.js b/dist/esm/server/auth/providers/proxyProvider.js new file mode 100644 index 0000000000..40fb0f1cb7 --- /dev/null +++ b/dist/esm/server/auth/providers/proxyProvider.js @@ -0,0 +1,157 @@ +import { OAuthClientInformationFullSchema, OAuthTokensSchema } from '../../../shared/auth.js'; +import { ServerError } from '../errors.js'; +/** + * Implements an OAuth server that proxies requests to another OAuth server. + */ +export class ProxyOAuthServerProvider { + constructor(options) { + var _a; + this.skipLocalPkceValidation = true; + this._endpoints = options.endpoints; + this._verifyAccessToken = options.verifyAccessToken; + this._getClient = options.getClient; + this._fetch = options.fetch; + if ((_a = options.endpoints) === null || _a === void 0 ? void 0 : _a.revocationUrl) { + this.revokeToken = async (client, request) => { + var _a; + const revocationUrl = this._endpoints.revocationUrl; + if (!revocationUrl) { + throw new Error('No revocation endpoint configured'); + } + const params = new URLSearchParams(); + params.set('token', request.token); + params.set('client_id', client.client_id); + if (client.client_secret) { + params.set('client_secret', client.client_secret); + } + if (request.token_type_hint) { + params.set('token_type_hint', request.token_type_hint); + } + const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(revocationUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: params.toString() + }); + if (!response.ok) { + throw new ServerError(`Token revocation failed: ${response.status}`); + } + }; + } + } + get clientsStore() { + const registrationUrl = this._endpoints.registrationUrl; + return { + getClient: this._getClient, + ...(registrationUrl && { + registerClient: async (client) => { + var _a; + const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(registrationUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(client) + }); + if (!response.ok) { + throw new ServerError(`Client registration failed: ${response.status}`); + } + const data = await response.json(); + return OAuthClientInformationFullSchema.parse(data); + } + }) + }; + } + async authorize(client, params, res) { + var _a; + // Start with required OAuth parameters + const targetUrl = new URL(this._endpoints.authorizationUrl); + const searchParams = new URLSearchParams({ + client_id: client.client_id, + response_type: 'code', + redirect_uri: params.redirectUri, + code_challenge: params.codeChallenge, + code_challenge_method: 'S256' + }); + // Add optional standard OAuth parameters + if (params.state) + searchParams.set('state', params.state); + if ((_a = params.scopes) === null || _a === void 0 ? void 0 : _a.length) + searchParams.set('scope', params.scopes.join(' ')); + if (params.resource) + searchParams.set('resource', params.resource.href); + targetUrl.search = searchParams.toString(); + res.redirect(targetUrl.toString()); + } + async challengeForAuthorizationCode(_client, _authorizationCode) { + // In a proxy setup, we don't store the code challenge ourselves + // Instead, we proxy the token request and let the upstream server validate it + return ''; + } + async exchangeAuthorizationCode(client, authorizationCode, codeVerifier, redirectUri, resource) { + var _a; + const params = new URLSearchParams({ + grant_type: 'authorization_code', + client_id: client.client_id, + code: authorizationCode + }); + if (client.client_secret) { + params.append('client_secret', client.client_secret); + } + if (codeVerifier) { + params.append('code_verifier', codeVerifier); + } + if (redirectUri) { + params.append('redirect_uri', redirectUri); + } + if (resource) { + params.append('resource', resource.href); + } + const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(this._endpoints.tokenUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: params.toString() + }); + if (!response.ok) { + throw new ServerError(`Token exchange failed: ${response.status}`); + } + const data = await response.json(); + return OAuthTokensSchema.parse(data); + } + async exchangeRefreshToken(client, refreshToken, scopes, resource) { + var _a; + const params = new URLSearchParams({ + grant_type: 'refresh_token', + client_id: client.client_id, + refresh_token: refreshToken + }); + if (client.client_secret) { + params.set('client_secret', client.client_secret); + } + if (scopes === null || scopes === void 0 ? void 0 : scopes.length) { + params.set('scope', scopes.join(' ')); + } + if (resource) { + params.set('resource', resource.href); + } + const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(this._endpoints.tokenUrl, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + }, + body: params.toString() + }); + if (!response.ok) { + throw new ServerError(`Token refresh failed: ${response.status}`); + } + const data = await response.json(); + return OAuthTokensSchema.parse(data); + } + async verifyAccessToken(token) { + return this._verifyAccessToken(token); + } +} +//# sourceMappingURL=proxyProvider.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/providers/proxyProvider.js.map b/dist/esm/server/auth/providers/proxyProvider.js.map new file mode 100644 index 0000000000..896667e58f --- /dev/null +++ b/dist/esm/server/auth/providers/proxyProvider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"proxyProvider.js","sourceRoot":"","sources":["../../../../../src/server/auth/providers/proxyProvider.ts"],"names":[],"mappings":"AAEA,OAAO,EAEH,gCAAgC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,aAAa,CAAC,CAAC;QACtD,CAAC;QAED,IAAI,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,MAAM,EAAE,CAAC;YACjB,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QAC1C,CAAC;QAED,IAAI,QAAQ,EAAE,CAAC;YACX,MAAM,CAAC,GAAG,CAAC,UAAU,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC;QAC1C,CAAC;QAED,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAA,IAAI,CAAC,MAAM,mCAAI,KAAK,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE;YACpE,MAAM,EAAE,MAAM;YACd,OAAO,EAAE;gBACL,cAAc,EAAE,mCAAmC;aACtD;YACD,IAAI,EAAE,MAAM,CAAC,QAAQ,EAAE;SAC1B,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACf,MAAM,IAAI,WAAW,CAAC,yBAAyB,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;QACtE,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,OAAO,iBAAiB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACzC,CAAC;IAED,KAAK,CAAC,iBAAiB,CAAC,KAAa;QACjC,OAAO,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/server/auth/router.d.ts b/dist/esm/server/auth/router.d.ts new file mode 100644 index 0000000000..43dabde7d2 --- /dev/null +++ b/dist/esm/server/auth/router.d.ts @@ -0,0 +1,101 @@ +import express, { RequestHandler } from 'express'; +import { ClientRegistrationHandlerOptions } from './handlers/register.js'; +import { TokenHandlerOptions } from './handlers/token.js'; +import { AuthorizationHandlerOptions } from './handlers/authorize.js'; +import { RevocationHandlerOptions } from './handlers/revoke.js'; +import { OAuthServerProvider } from './provider.js'; +import { OAuthMetadata } from '../../shared/auth.js'; +export type AuthRouterOptions = { + /** + * A provider implementing the actual authorization logic for this router. + */ + provider: OAuthServerProvider; + /** + * The authorization server's issuer identifier, which is a URL that uses the "https" scheme and has no query or fragment components. + */ + issuerUrl: URL; + /** + * The base URL of the authorization server to use for the metadata endpoints. + * + * If not provided, the issuer URL will be used as the base URL. + */ + baseUrl?: URL; + /** + * An optional URL of a page containing human-readable information that developers might want or need to know when using the authorization server. + */ + serviceDocumentationUrl?: URL; + /** + * An optional list of scopes supported by this authorization server + */ + scopesSupported?: string[]; + /** + * The resource name to be displayed in protected resource metadata + */ + resourceName?: string; + /** + * The URL of the protected resource (RS) whose metadata we advertise. + * If not provided, falls back to `baseUrl` and then to `issuerUrl` (AS=RS). + */ + resourceServerUrl?: URL; + authorizationOptions?: Omit; + clientRegistrationOptions?: Omit; + revocationOptions?: Omit; + tokenOptions?: Omit; +}; +export declare const createOAuthMetadata: (options: { + provider: OAuthServerProvider; + issuerUrl: URL; + baseUrl?: URL; + serviceDocumentationUrl?: URL; + scopesSupported?: string[]; +}) => OAuthMetadata; +/** + * Installs standard MCP authorization server endpoints, including dynamic client registration and token revocation (if supported). + * Also advertises standard authorization server metadata, for easier discovery of supported configurations by clients. + * Note: if your MCP server is only a resource server and not an authorization server, use mcpAuthMetadataRouter instead. + * + * By default, rate limiting is applied to all endpoints to prevent abuse. + * + * This router MUST be installed at the application root, like so: + * + * const app = express(); + * app.use(mcpAuthRouter(...)); + */ +export declare function mcpAuthRouter(options: AuthRouterOptions): RequestHandler; +export type AuthMetadataOptions = { + /** + * OAuth Metadata as would be returned from the authorization server + * this MCP server relies on + */ + oauthMetadata: OAuthMetadata; + /** + * The url of the MCP server, for use in protected resource metadata + */ + resourceServerUrl: URL; + /** + * The url for documentation for the MCP server + */ + serviceDocumentationUrl?: URL; + /** + * An optional list of scopes supported by this MCP server + */ + scopesSupported?: string[]; + /** + * An optional resource name to display in resource metadata + */ + resourceName?: string; +}; +export declare function mcpAuthMetadataRouter(options: AuthMetadataOptions): express.Router; +/** + * Helper function to construct the OAuth 2.0 Protected Resource Metadata URL + * from a given server URL. This replaces the path with the standard metadata endpoint. + * + * @param serverUrl - The base URL of the protected resource server + * @returns The URL for the OAuth protected resource metadata endpoint + * + * @example + * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) + * // Returns: 'https://api.example.com/.well-known/oauth-protected-resource/mcp' + */ +export declare function getOAuthProtectedResourceMetadataUrl(serverUrl: URL): string; +//# sourceMappingURL=router.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/router.d.ts.map b/dist/esm/server/auth/router.d.ts.map new file mode 100644 index 0000000000..54e90be267 --- /dev/null +++ b/dist/esm/server/auth/router.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/router.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,EAAE,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAA6B,gCAAgC,EAAE,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAgB,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAAwB,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AAC5F,OAAO,EAAqB,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAEnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,aAAa,EAAkC,MAAM,sBAAsB,CAAC;AAErF,MAAM,MAAM,iBAAiB,GAAG;IAC5B;;OAEG;IACH,QAAQ,EAAE,mBAAmB,CAAC;IAE9B;;OAEG;IACH,SAAS,EAAE,GAAG,CAAC;IAEf;;;;OAIG;IACH,OAAO,CAAC,EAAE,GAAG,CAAC;IAEd;;OAEG;IACH,uBAAuB,CAAC,EAAE,GAAG,CAAC;IAE9B;;OAEG;IACH,eAAe,CAA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dist/esm/server/auth/router.js b/dist/esm/server/auth/router.js new file mode 100644 index 0000000000..ff72f643f3 --- /dev/null +++ b/dist/esm/server/auth/router.js @@ -0,0 +1,115 @@ +import express from 'express'; +import { clientRegistrationHandler } from './handlers/register.js'; +import { tokenHandler } from './handlers/token.js'; +import { authorizationHandler } from './handlers/authorize.js'; +import { revocationHandler } from './handlers/revoke.js'; +import { metadataHandler } from './handlers/metadata.js'; +const checkIssuerUrl = (issuer) => { + // Technically RFC 8414 does not permit a localhost HTTPS exemption, but this will be necessary for ease of testing + if (issuer.protocol !== 'https:' && issuer.hostname !== 'localhost' && issuer.hostname !== '127.0.0.1') { + throw new Error('Issuer URL must be HTTPS'); + } + if (issuer.hash) { + throw new Error(`Issuer URL must not have a fragment: ${issuer}`); + } + if (issuer.search) { + throw new Error(`Issuer URL must not have a query string: ${issuer}`); + } +}; +export const createOAuthMetadata = (options) => { + var _a; + const issuer = options.issuerUrl; + const baseUrl = options.baseUrl; + checkIssuerUrl(issuer); + const authorization_endpoint = '/authorize'; + const token_endpoint = '/token'; + const registration_endpoint = options.provider.clientsStore.registerClient ? '/register' : undefined; + const revocation_endpoint = options.provider.revokeToken ? '/revoke' : undefined; + const metadata = { + issuer: issuer.href, + service_documentation: (_a = options.serviceDocumentationUrl) === null || _a === void 0 ? void 0 : _a.href, + authorization_endpoint: new URL(authorization_endpoint, baseUrl || issuer).href, + response_types_supported: ['code'], + code_challenge_methods_supported: ['S256'], + token_endpoint: new URL(token_endpoint, baseUrl || issuer).href, + token_endpoint_auth_methods_supported: ['client_secret_post', 'none'], + grant_types_supported: ['authorization_code', 'refresh_token'], + scopes_supported: options.scopesSupported, + revocation_endpoint: revocation_endpoint ? new URL(revocation_endpoint, baseUrl || issuer).href : undefined, + revocation_endpoint_auth_methods_supported: revocation_endpoint ? ['client_secret_post'] : undefined, + registration_endpoint: registration_endpoint ? new URL(registration_endpoint, baseUrl || issuer).href : undefined + }; + return metadata; +}; +/** + * Installs standard MCP authorization server endpoints, including dynamic client registration and token revocation (if supported). + * Also advertises standard authorization server metadata, for easier discovery of supported configurations by clients. + * Note: if your MCP server is only a resource server and not an authorization server, use mcpAuthMetadataRouter instead. + * + * By default, rate limiting is applied to all endpoints to prevent abuse. + * + * This router MUST be installed at the application root, like so: + * + * const app = express(); + * app.use(mcpAuthRouter(...)); + */ +export function mcpAuthRouter(options) { + var _a, _b; + const oauthMetadata = createOAuthMetadata(options); + const router = express.Router(); + router.use(new URL(oauthMetadata.authorization_endpoint).pathname, authorizationHandler({ provider: options.provider, ...options.authorizationOptions })); + router.use(new URL(oauthMetadata.token_endpoint).pathname, tokenHandler({ provider: options.provider, ...options.tokenOptions })); + router.use(mcpAuthMetadataRouter({ + oauthMetadata, + // Prefer explicit RS; otherwise fall back to AS baseUrl, then to issuer (back-compat) + resourceServerUrl: (_b = (_a = options.resourceServerUrl) !== null && _a !== void 0 ? _a : options.baseUrl) !== null && _b !== void 0 ? _b : new URL(oauthMetadata.issuer), + serviceDocumentationUrl: options.serviceDocumentationUrl, + scopesSupported: options.scopesSupported, + resourceName: options.resourceName + })); + if (oauthMetadata.registration_endpoint) { + router.use(new URL(oauthMetadata.registration_endpoint).pathname, clientRegistrationHandler({ + clientsStore: options.provider.clientsStore, + ...options.clientRegistrationOptions + })); + } + if (oauthMetadata.revocation_endpoint) { + router.use(new URL(oauthMetadata.revocation_endpoint).pathname, revocationHandler({ provider: options.provider, ...options.revocationOptions })); + } + return router; +} +export function mcpAuthMetadataRouter(options) { + var _a; + checkIssuerUrl(new URL(options.oauthMetadata.issuer)); + const router = express.Router(); + const protectedResourceMetadata = { + resource: options.resourceServerUrl.href, + authorization_servers: [options.oauthMetadata.issuer], + scopes_supported: options.scopesSupported, + resource_name: options.resourceName, + resource_documentation: (_a = options.serviceDocumentationUrl) === null || _a === void 0 ? void 0 : _a.href + }; + // Serve PRM at the path-specific URL per RFC 9728 + const rsPath = new URL(options.resourceServerUrl.href).pathname; + router.use(`/.well-known/oauth-protected-resource${rsPath === '/' ? '' : rsPath}`, metadataHandler(protectedResourceMetadata)); + // Always add this for OAuth Authorization Server metadata per RFC 8414 + router.use('/.well-known/oauth-authorization-server', metadataHandler(options.oauthMetadata)); + return router; +} +/** + * Helper function to construct the OAuth 2.0 Protected Resource Metadata URL + * from a given server URL. This replaces the path with the standard metadata endpoint. + * + * @param serverUrl - The base URL of the protected resource server + * @returns The URL for the OAuth protected resource metadata endpoint + * + * @example + * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) + * // Returns: 'https://api.example.com/.well-known/oauth-protected-resource/mcp' + */ +export function getOAuthProtectedResourceMetadataUrl(serverUrl) { + const u = new URL(serverUrl.href); + const rsPath = u.pathname && u.pathname !== '/' ? u.pathname : ''; + return new URL(`/.well-known/oauth-protected-resource${rsPath}`, u).href; +} +//# sourceMappingURL=router.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/router.js.map b/dist/esm/server/auth/router.js.map new file mode 100644 index 0000000000..363e49566b --- /dev/null +++ b/dist/esm/server/auth/router.js.map @@ -0,0 +1 @@ +{"version":3,"file":"router.js","sourceRoot":"","sources":["../../../../src/server/auth/router.ts"],"names":[],"mappings":"AAAA,OAAO,OAA2B,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,yBAAyB,EAAoC,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAE,YAAY,EAAuB,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAAE,oBAAoB,EAA+B,MAAM,yBAAyB,CAAC;AAC5F,OAAO,EAAE,iBAAiB,EAA4B,MAAM,sBAAsB,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAkDzD,MAAM,cAAc,GAAG,CAAC,MAAW,EAAQ,EAAE;IACzC,mHAAmH;IACnH,IAAI,MAAM,CAAC,QAAQ,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,KAAK,WAAW,IAAI,MAAM,CAAC,QAAQ,KAAK,WAAW,EAAE,CAAC;QACrG,MA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;KAChE,CAAC;IAEF,kDAAkD;IAClD,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC;IAChE,MAAM,CAAC,GAAG,CAAC,wCAAwC,MAAM,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,eAAe,CAAC,yBAAyB,CAAC,CAAC,CAAC;IAE/H,uEAAuE;IACvE,MAAM,CAAC,GAAG,CAAC,yCAAyC,EAAE,eAAe,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC;IAE9F,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,oCAAoC,CAAC,SAAc;IAC/D,MAAM,CAAC,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IAClC,MAAM,MAAM,GAAG,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,QAAQ,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC;IAClE,OAAO,IAAI,GAAG,CAAC,wCAAwC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAC7E,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/types.d.ts b/dist/esm/server/auth/types.d.ts new file mode 100644 index 0000000000..05ec8485a5 --- /dev/null +++ b/dist/esm/server/auth/types.d.ts @@ -0,0 +1,32 @@ +/** + * Information about a validated access token, provided to request handlers. + */ +export interface AuthInfo { + /** + * The access token. + */ + token: string; + /** + * The client ID associated with this token. + */ + clientId: string; + /** + * Scopes associated with this token. + */ + scopes: string[]; + /** + * When the token expires (in seconds since epoch). + */ + expiresAt?: number; + /** + * The RFC 8707 resource server identifier for which this token is valid. + * If set, this MUST match the MCP server's resource identifier (minus hash fragment). + */ + resource?: URL; + /** + * Additional data associated with the token. + * This field should be used for any additional data that needs to be attached to the auth info. + */ + extra?: Record; +} +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/types.d.ts.map b/dist/esm/server/auth/types.d.ts.map new file mode 100644 index 0000000000..021e947401 --- /dev/null +++ b/dist/esm/server/auth/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,QAAQ;IACrB;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,MAAM,EAAE,MAAM,EAAE,CAAC;IAEjB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,QAAQ,CAAC,EAAE,GAAG,CAAC;IAEf;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC"} \ No newline at end of file diff --git a/dist/esm/server/auth/types.js b/dist/esm/server/auth/types.js new file mode 100644 index 0000000000..718fd38ae4 --- /dev/null +++ b/dist/esm/server/auth/types.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/types.js.map b/dist/esm/server/auth/types.js.map new file mode 100644 index 0000000000..0d8063dee4 --- /dev/null +++ b/dist/esm/server/auth/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/server/auth/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/server/completable.d.ts b/dist/esm/server/completable.d.ts new file mode 100644 index 0000000000..1b3159ac8f --- /dev/null +++ b/dist/esm/server/completable.d.ts @@ -0,0 +1,38 @@ +import { AnySchema, SchemaInput } from './zod-compat.js'; +export declare const COMPLETABLE_SYMBOL: unique symbol; +export type CompleteCallback = (value: SchemaInput, context?: { + arguments?: Record; +}) => SchemaInput[] | Promise[]>; +export type CompletableMeta = { + complete: CompleteCallback; +}; +export type CompletableSchema = T & { + [COMPLETABLE_SYMBOL]: CompletableMeta; +}; +/** + * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. + * Works with both Zod v3 and v4 schemas. + */ +export declare function completable(schema: T, complete: CompleteCallback): CompletableSchema; +/** + * Checks if a schema is completable (has completion metadata). + */ +export declare function isCompletable(schema: unknown): schema is CompletableSchema; +/** + * Gets the completer callback from a completable schema, if it exists. + */ +export declare function getCompleter(schema: T): CompleteCallback | undefined; +/** + * Unwraps a completable schema to get the underlying schema. + * For backward compatibility with code that called `.unwrap()`. + */ +export declare function unwrapCompletable(schema: CompletableSchema): T; +export declare enum McpZodTypeKind { + Completable = "McpCompletable" +} +export interface CompletableDef { + type: T; + complete: CompleteCallback; + typeName: McpZodTypeKind.Completable; +} +//# sourceMappingURL=completable.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/completable.d.ts.map b/dist/esm/server/completable.d.ts.map new file mode 100644 index 0000000000..83ea2f1e27 --- /dev/null +++ b/dist/esm/server/completable.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"completable.d.ts","sourceRoot":"","sources":["../../../src/server/completable.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEzD,eAAO,MAAM,kBAAkB,EAAE,OAAO,MAAsC,CAAC;AAE/E,MAAM,MAAM,gBAAgB,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS,IAAI,CAC5D,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,EACrB,OAAO,CAAC,EAAE;IACN,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACtC,KACA,WAAW,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;AAElD,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS,IAAI;IAC3D,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC;CACjC,CAAC;AAEF,MAAM,MAAM,iBAAiB,CAAC,CAAC,SAAS,SAAS,IAAI,CAAC,GAAG;IACrD,CAAC,kBAAkB,CAAC,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC;CAC5C,CAAC;AAEF;;;GAGG;AACH,wBAAgB,WAAW,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,CAAC,EAAE,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAQ/G;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,IAAI,iBAAiB,CAAC,SAAS,CAAC,CAErF;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,CAAC,GAAG,gBAAgB,CAAC,CAAC,CAAC,GAAG,SAAS,CAG5F;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,CAAC,CAEtF;AAID,oBAAY,cAAc;IACtB,WAAW,mBAAmB;CACjC;AAED,MAAM,WAAW,cAAc,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS;IAC3D,IAAI,EAAE,CAAC,CAAC;IACR,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC;IAC9B,QAAQ,EAAE,cAAc,CAAC,WAAW,CAAC;CACxC"} \ No newline at end of file diff --git a/dist/esm/server/completable.js b/dist/esm/server/completable.js new file mode 100644 index 0000000000..4f636e3eaa --- /dev/null +++ b/dist/esm/server/completable.js @@ -0,0 +1,41 @@ +export const COMPLETABLE_SYMBOL = Symbol.for('mcp.completable'); +/** + * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. + * Works with both Zod v3 and v4 schemas. + */ +export function completable(schema, complete) { + Object.defineProperty(schema, COMPLETABLE_SYMBOL, { + value: { complete }, + enumerable: false, + writable: false, + configurable: false + }); + return schema; +} +/** + * Checks if a schema is completable (has completion metadata). + */ +export function isCompletable(schema) { + return !!schema && typeof schema === 'object' && COMPLETABLE_SYMBOL in schema; +} +/** + * Gets the completer callback from a completable schema, if it exists. + */ +export function getCompleter(schema) { + const meta = schema[COMPLETABLE_SYMBOL]; + return meta === null || meta === void 0 ? void 0 : meta.complete; +} +/** + * Unwraps a completable schema to get the underlying schema. + * For backward compatibility with code that called `.unwrap()`. + */ +export function unwrapCompletable(schema) { + return schema; +} +// Legacy exports for backward compatibility +// These types are deprecated but kept for existing code +export var McpZodTypeKind; +(function (McpZodTypeKind) { + McpZodTypeKind["Completable"] = "McpCompletable"; +})(McpZodTypeKind || (McpZodTypeKind = {})); +//# sourceMappingURL=completable.js.map \ No newline at end of file diff --git a/dist/esm/server/completable.js.map b/dist/esm/server/completable.js.map new file mode 100644 index 0000000000..d8700d494b --- /dev/null +++ b/dist/esm/server/completable.js.map @@ -0,0 +1 @@ +{"version":3,"file":"completable.js","sourceRoot":"","sources":["../../../src/server/completable.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,kBAAkB,GAAkB,MAAM,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;AAiB/E;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAsB,MAAS,EAAE,QAA6B;IACrF,MAAM,CAAC,cAAc,CAAC,MAAgB,EAAE,kBAAkB,EAAE;QACxD,KAAK,EAAE,EAAE,QAAQ,EAAwB;QACzC,UAAU,EAAE,KAAK;QACjB,QAAQ,EAAE,KAAK;QACf,YAAY,EAAE,KAAK;KACtB,CAAC,CAAC;IACH,OAAO,MAA8B,CAAC;AAC1C,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa,CAAC,MAAe;IACzC,OAAO,CAAC,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,kBAAkB,IAAK,MAAiB,CAAC;AAC9F,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,YAAY,CAAsB,MAAS;IACvD,MAAM,IAAI,GAAI,MAAmE,CAAC,kBAAkB,CAAC,CAAC;IACtG,OAAO,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,QAA2C,CAAC;AAC7D,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAsB,MAA4B;IAC/E,OAAO,MAAM,CAAC;AAClB,CAAC;AAED,4CAA4C;AAC5C,wDAAwD;AACxD,MAAM,CAAN,IAAY,cAEX;AAFD,WAAY,cAAc;IACtB,gDAA8B,CAAA;AAClC,CAAC,EAFW,cAAc,KAAd,cAAc,QAEzB"} \ No newline at end of file diff --git a/dist/esm/server/index.d.ts b/dist/esm/server/index.d.ts new file mode 100644 index 0000000000..8aabf3c536 --- /dev/null +++ b/dist/esm/server/index.d.ts @@ -0,0 +1,333 @@ +import { Protocol, type NotificationOptions, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; +import { type ClientCapabilities, type CreateMessageRequest, type ElicitRequestFormParams, type ElicitRequestURLParams, type ElicitResult, type Implementation, type ListRootsRequest, type LoggingMessageNotification, type Notification, type Request, type ResourceUpdatedNotification, type Result, type ServerCapabilities, type ServerNotification, type ServerRequest, type ServerResult } from '../types.js'; +import type { jsonSchemaValidator } from '../validation/types.js'; +type LegacyElicitRequestFormParams = Omit; +export type ServerOptions = ProtocolOptions & { + /** + * Capabilities to advertise as being supported by this server. + */ + capabilities?: ServerCapabilities; + /** + * Optional instructions describing how to use the server and its features. + */ + instructions?: string; + /** + * JSON Schema validator for elicitation response validation. + * + * The validator is used to validate user input returned from elicitation + * requests against the requested schema. + * + * @default AjvJsonSchemaValidator + * + * @example + * ```typescript + * // ajv (default) + * const server = new Server( + * { name: 'my-server', version: '1.0.0' }, + * { + * capabilities: {} + * jsonSchemaValidator: new AjvJsonSchemaValidator() + * } + * ); + * + * // @cfworker/json-schema + * const server = new Server( + * { name: 'my-server', version: '1.0.0' }, + * { + * capabilities: {}, + * jsonSchemaValidator: new CfWorkerJsonSchemaValidator() + * } + * ); + * ``` + */ + jsonSchemaValidator?: jsonSchemaValidator; +}; +/** + * An MCP server on top of a pluggable transport. + * + * This server will automatically respond to the initialization flow as initiated from the client. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed server + * const server = new Server({ + * name: "CustomServer", + * version: "1.0.0" + * }) + * ``` + * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. + */ +export declare class Server extends Protocol { + private _serverInfo; + private _clientCapabilities?; + private _clientVersion?; + private _capabilities; + private _instructions?; + private _jsonSchemaValidator; + /** + * Callback for when initialization has fully completed (i.e., the client has sent an `initialized` notification). + */ + oninitialized?: () => void; + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo: Implementation, options?: ServerOptions); + private _loggingLevels; + private readonly LOG_LEVEL_SEVERITY; + private isMessageIgnored; + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities: ServerCapabilities): void; + protected assertCapabilityForMethod(method: RequestT['method']): void; + protected assertNotificationCapability(method: (ServerNotification | NotificationT)['method']): void; + protected assertRequestHandlerCapability(method: string): void; + private _oninitialize; + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + */ + getClientCapabilities(): ClientCapabilities | undefined; + /** + * After initialization has completed, this will be populated with information about the client's name and version. + */ + getClientVersion(): Implementation | undefined; + private getCapabilities; + ping(): Promise<{ + _meta?: Record | undefined; + }>; + createMessage(params: CreateMessageRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + model: string; + role: "user" | "assistant"; + content: { + type: "text"; + text: string; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + [x: string]: unknown; + type: "tool_use"; + name: string; + id: string; + input: { + [x: string]: unknown; + }; + _meta?: { + [x: string]: unknown; + } | undefined; + } | { + [x: string]: unknown; + type: "tool_result"; + toolUseId: string; + content: ({ + type: "text"; + text: string; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "resource"; + resource: { + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + }; + _meta?: Record | undefined; + } | { + uri: string; + name: string; + type: "resource_link"; + description?: string | undefined; + mimeType?: string | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + })[]; + structuredContent?: { + [x: string]: unknown; + } | undefined; + isError?: boolean | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + } | ({ + type: "text"; + text: string; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + [x: string]: unknown; + type: "tool_use"; + name: string; + id: string; + input: { + [x: string]: unknown; + }; + _meta?: { + [x: string]: unknown; + } | undefined; + } | { + [x: string]: unknown; + type: "tool_result"; + toolUseId: string; + content: ({ + type: "text"; + text: string; + _meta?: Record | undefined; + } | { + type: "image"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "audio"; + data: string; + mimeType: string; + _meta?: Record | undefined; + } | { + type: "resource"; + resource: { + uri: string; + text: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + } | { + uri: string; + blob: string; + mimeType?: string | undefined; + _meta?: Record | undefined; + }; + _meta?: Record | undefined; + } | { + uri: string; + name: string; + type: "resource_link"; + description?: string | undefined; + mimeType?: string | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + icons?: { + src: string; + mimeType?: string | undefined; + sizes?: string[] | undefined; + }[] | undefined; + title?: string | undefined; + })[]; + structuredContent?: { + [x: string]: unknown; + } | undefined; + isError?: boolean | undefined; + _meta?: { + [x: string]: unknown; + } | undefined; + })[]; + _meta?: Record | undefined; + stopReason?: string | undefined; + }>; + /** + * Creates an elicitation request for the given parameters. + * @param params The parameters for the form elicitation request (explicit mode: 'form'). + * @param options Optional request options. + * @returns The result of the elicitation request. + */ + elicitInput(params: ElicitRequestFormParams, options?: RequestOptions): Promise; + /** + * Creates an elicitation request for the given parameters. + * @param params The parameters for the URL elicitation request (with url and elicitationId). + * @param options Optional request options. + * @returns The result of the elicitation request. + */ + elicitInput(params: ElicitRequestURLParams, options?: RequestOptions): Promise; + /** + * Creates an elicitation request for the given parameters. + * @deprecated Use the overloads with explicit `mode: 'form' | 'url'` instead. + * @param params The parameters for the form elicitation request (legacy signature without mode). + * @param options Optional request options. + * @returns The result of the elicitation request. + */ + elicitInput(params: LegacyElicitRequestFormParams, options?: RequestOptions): Promise; + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId: string, options?: NotificationOptions): () => Promise; + listRoots(params?: ListRootsRequest['params'], options?: RequestOptions): Promise<{ + [x: string]: unknown; + roots: { + uri: string; + name?: string | undefined; + _meta?: Record | undefined; + }[]; + _meta?: Record | undefined; + }>; + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string): Promise; + sendResourceUpdated(params: ResourceUpdatedNotification['params']): Promise; + sendResourceListChanged(): Promise; + sendToolListChanged(): Promise; + sendPromptListChanged(): Promise; +} +export {}; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/index.d.ts.map b/dist/esm/server/index.d.ts.map new file mode 100644 index 0000000000..4b8cc1c0a0 --- /dev/null +++ b/dist/esm/server/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAAE,KAAK,mBAAmB,EAAE,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACzI,OAAO,EACH,KAAK,kBAAkB,EACvB,KAAK,oBAAoB,EAEzB,KAAK,uBAAuB,EAC5B,KAAK,sBAAsB,EAC3B,KAAK,YAAY,EAIjB,KAAK,cAAc,EAMnB,KAAK,gBAAgB,EAIrB,KAAK,0BAA0B,EAE/B,KAAK,YAAY,EACjB,KAAK,OAAO,EACZ,KAAK,2BAA2B,EAChC,KAAK,MAAM,EACX,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,YAAY,EAGpB,MAAM,aAAa,CAAC;AAErB,OAAO,KAAK,EAAkB,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAElF,KAAK,6BAA6B,GAAG,IAAI,CAAC,uBAAuB,EAAE,MAAM,CAAC,CAAC;AAE3E,MAAM,MAAM,aAAa,GAAG,eAAe,GAAG;IAC1C;;OAEG;IACH,YAAY,CAAC,EAAE,kBAAkB,CAAC;IAElC;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4B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AO,CAAC,eAAe;IAIjB,IAAI;;;IAIJ,aAAa,CAAC,MAAM,EAAE,oBAAoB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAIpF;;;;;OAKG;IACG,WAAW,CAAC,MAAM,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC;IACnG;;;;;OAKG;IACG,WAAW,CAAC,MAAM,EAAE,sBAAsB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC;IAClG;;;;;;OAMG;IACG,WAAW,CAAC,MAAM,EAAE,6BAA6B,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC;IAuDzG;;;;;;;OAOG;IACH,mCAAmC,CAAC,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC;IAiBxG,SAAS,CAAC,MAAM,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;IAI7E;;;;;;OAMG;IACG,kBAAkB,CAAC,MAAM,EAAE,0BAA0B,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC,EAAE,MAAM;IAQnF,mBAAmB,CAAC,MAAM,EAAE,2BAA2B,CAAC,QAAQ,CAAC;IAOjE,uBAAuB;IAMvB,mBAAmB;IAInB,qBAAqB;CAG9B"} \ No newline at end of file diff --git a/dist/esm/server/index.js b/dist/esm/server/index.js new file mode 100644 index 0000000000..9a0afd2801 --- /dev/null +++ b/dist/esm/server/index.js @@ -0,0 +1,300 @@ +import { mergeCapabilities, Protocol } from '../shared/protocol.js'; +import { CreateMessageResultSchema, ElicitResultSchema, EmptyResultSchema, ErrorCode, InitializedNotificationSchema, InitializeRequestSchema, LATEST_PROTOCOL_VERSION, ListRootsResultSchema, LoggingLevelSchema, McpError, SetLevelRequestSchema, SUPPORTED_PROTOCOL_VERSIONS } from '../types.js'; +import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; +/** + * An MCP server on top of a pluggable transport. + * + * This server will automatically respond to the initialization flow as initiated from the client. + * + * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: + * + * ```typescript + * // Custom schemas + * const CustomRequestSchema = RequestSchema.extend({...}) + * const CustomNotificationSchema = NotificationSchema.extend({...}) + * const CustomResultSchema = ResultSchema.extend({...}) + * + * // Type aliases + * type CustomRequest = z.infer + * type CustomNotification = z.infer + * type CustomResult = z.infer + * + * // Create typed server + * const server = new Server({ + * name: "CustomServer", + * version: "1.0.0" + * }) + * ``` + * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. + */ +export class Server extends Protocol { + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo, options) { + var _a, _b; + super(options); + this._serverInfo = _serverInfo; + // Map log levels by session id + this._loggingLevels = new Map(); + // Map LogLevelSchema to severity index + this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); + // Is a message with the given level ignored in the log level set for the given session id? + this.isMessageIgnored = (level, sessionId) => { + const currentLevel = this._loggingLevels.get(sessionId); + return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; + }; + this._capabilities = (_a = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a !== void 0 ? _a : {}; + this._instructions = options === null || options === void 0 ? void 0 : options.instructions; + this._jsonSchemaValidator = (_b = options === null || options === void 0 ? void 0 : options.jsonSchemaValidator) !== null && _b !== void 0 ? _b : new AjvJsonSchemaValidator(); + this.setRequestHandler(InitializeRequestSchema, request => this._oninitialize(request)); + this.setNotificationHandler(InitializedNotificationSchema, () => { var _a; return (_a = this.oninitialized) === null || _a === void 0 ? void 0 : _a.call(this); }); + if (this._capabilities.logging) { + this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => { + var _a; + const transportSessionId = extra.sessionId || ((_a = extra.requestInfo) === null || _a === void 0 ? void 0 : _a.headers['mcp-session-id']) || undefined; + const { level } = request.params; + const parseResult = LoggingLevelSchema.safeParse(level); + if (parseResult.success) { + this._loggingLevels.set(transportSessionId, parseResult.data); + } + return {}; + }); + } + } + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) { + throw new Error('Cannot register capabilities after connecting to transport'); + } + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + } + assertCapabilityForMethod(method) { + var _a, _b, _c; + switch (method) { + case 'sampling/createMessage': + if (!((_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.sampling)) { + throw new Error(`Client does not support sampling (required for ${method})`); + } + break; + case 'elicitation/create': + if (!((_b = this._clientCapabilities) === null || _b === void 0 ? void 0 : _b.elicitation)) { + throw new Error(`Client does not support elicitation (required for ${method})`); + } + break; + case 'roots/list': + if (!((_c = this._clientCapabilities) === null || _c === void 0 ? void 0 : _c.roots)) { + throw new Error(`Client does not support listing roots (required for ${method})`); + } + break; + case 'ping': + // No specific capability required for ping + break; + } + } + assertNotificationCapability(method) { + var _a, _b; + switch (method) { + case 'notifications/message': + if (!this._capabilities.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case 'notifications/resources/updated': + case 'notifications/resources/list_changed': + if (!this._capabilities.resources) { + throw new Error(`Server does not support notifying about resources (required for ${method})`); + } + break; + case 'notifications/tools/list_changed': + if (!this._capabilities.tools) { + throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); + } + break; + case 'notifications/prompts/list_changed': + if (!this._capabilities.prompts) { + throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); + } + break; + case 'notifications/elicitation/complete': + if (!((_b = (_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.elicitation) === null || _b === void 0 ? void 0 : _b.url)) { + throw new Error(`Client does not support URL elicitation (required for ${method})`); + } + break; + case 'notifications/cancelled': + // Cancellation notifications are always allowed + break; + case 'notifications/progress': + // Progress notifications are always allowed + break; + } + } + assertRequestHandlerCapability(method) { + switch (method) { + case 'completion/complete': + if (!this._capabilities.completions) { + throw new Error(`Server does not support completions (required for ${method})`); + } + break; + case 'logging/setLevel': + if (!this._capabilities.logging) { + throw new Error(`Server does not support logging (required for ${method})`); + } + break; + case 'prompts/get': + case 'prompts/list': + if (!this._capabilities.prompts) { + throw new Error(`Server does not support prompts (required for ${method})`); + } + break; + case 'resources/list': + case 'resources/templates/list': + case 'resources/read': + if (!this._capabilities.resources) { + throw new Error(`Server does not support resources (required for ${method})`); + } + break; + case 'tools/call': + case 'tools/list': + if (!this._capabilities.tools) { + throw new Error(`Server does not support tools (required for ${method})`); + } + break; + case 'ping': + case 'initialize': + // No specific capability required for these methods + break; + } + } + async _oninitialize(request) { + const requestedVersion = request.params.protocolVersion; + this._clientCapabilities = request.params.capabilities; + this._clientVersion = request.params.clientInfo; + const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION; + return { + protocolVersion, + capabilities: this.getCapabilities(), + serverInfo: this._serverInfo, + ...(this._instructions && { instructions: this._instructions }) + }; + } + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + */ + getClientCapabilities() { + return this._clientCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the client's name and version. + */ + getClientVersion() { + return this._clientVersion; + } + getCapabilities() { + return this._capabilities; + } + async ping() { + return this.request({ method: 'ping' }, EmptyResultSchema); + } + async createMessage(params, options) { + return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultSchema, options); + } + // Implementation (not visible to callers) + async elicitInput(params, options) { + var _a, _b, _c, _d; + const mode = ('mode' in params ? params.mode : 'form'); + switch (mode) { + case 'url': { + if (!((_b = (_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.elicitation) === null || _b === void 0 ? void 0 : _b.url)) { + throw new Error('Client does not support url elicitation.'); + } + const urlParams = params; + return this.request({ method: 'elicitation/create', params: urlParams }, ElicitResultSchema, options); + } + case 'form': { + if (!((_d = (_c = this._clientCapabilities) === null || _c === void 0 ? void 0 : _c.elicitation) === null || _d === void 0 ? void 0 : _d.form)) { + throw new Error('Client does not support form elicitation.'); + } + const formParams = 'mode' in params + ? params + : { ...params, mode: 'form' }; + const result = await this.request({ method: 'elicitation/create', params: formParams }, ElicitResultSchema, options); + if (result.action === 'accept' && result.content && formParams.requestedSchema) { + try { + const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); + const validationResult = validator(result.content); + if (!validationResult.valid) { + throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); + } + } + catch (error) { + if (error instanceof McpError) { + throw error; + } + throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); + } + } + return result; + } + } + } + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId, options) { + var _a, _b; + if (!((_b = (_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.elicitation) === null || _b === void 0 ? void 0 : _b.url)) { + throw new Error('Client does not support URL elicitation (required for notifications/elicitation/complete)'); + } + return () => this.notification({ + method: 'notifications/elicitation/complete', + params: { + elicitationId + } + }, options); + } + async listRoots(params, options) { + return this.request({ method: 'roots/list', params }, ListRootsResultSchema, options); + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + async sendLoggingMessage(params, sessionId) { + if (this._capabilities.logging) { + if (!this.isMessageIgnored(params.level, sessionId)) { + return this.notification({ method: 'notifications/message', params }); + } + } + } + async sendResourceUpdated(params) { + return this.notification({ + method: 'notifications/resources/updated', + params + }); + } + async sendResourceListChanged() { + return this.notification({ + method: 'notifications/resources/list_changed' + }); + } + async sendToolListChanged() { + return this.notification({ method: 'notifications/tools/list_changed' }); + } + async sendPromptListChanged() { + return this.notification({ method: 'notifications/prompts/list_changed' }); + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/esm/server/index.js.map b/dist/esm/server/index.js.map new file mode 100644 index 0000000000..654cd3dce9 --- /dev/null +++ b/dist/esm/server/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAAuE,MAAM,uBAAuB,CAAC;AACzI,OAAO,EAGH,yBAAyB,EAIzB,kBAAkB,EAClB,iBAAiB,EACjB,SAAS,EAET,6BAA6B,EAE7B,uBAAuB,EAEvB,uBAAuB,EAEvB,qBAAqB,EAErB,kBAAkB,EAElB,QAAQ,EASR,qBAAqB,EACrB,2BAA2B,EAC9B,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AAgDvE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,OAAO,MAIX,SAAQ,QAA8F;IAYpG;;OAEG;IACH,YACY,WAA2B,EACnC,OAAuB;;QAEvB,KAAK,CAAC,OAAO,CAAC,CAAC;QAHP,gBAAW,GAAX,WAAW,CAAgB;QAyBvC,+BAA+B;QACvB,mBAAc,GAAG,IAAI,GAAG,EAAoC,CAAC;QAErE,uCAAuC;QACtB,uBAAkB,GAAG,IAAI,GA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,CAAC;gBAClD,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,uBAAuB,EAAE,MAAM,EAAE,CAAC,CAAC;YAC1E,CAAC;QACL,CAAC;IACL,CAAC;IAED,KAAK,CAAC,mBAAmB,CAAC,MAA6C;QACnE,OAAO,IAAI,CAAC,YAAY,CAAC;YACrB,MAAM,EAAE,iCAAiC;YACzC,MAAM;SACT,CAAC,CAAC;IACP,CAAC;IAED,KAAK,CAAC,uBAAuB;QACzB,OAAO,IAAI,CAAC,YAAY,CAAC;YACrB,MAAM,EAAE,sCAAsC;SACjD,CAAC,CAAC;IACP,CAAC;IAED,KAAK,CAAC,mBAAmB;QACrB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,kCAAkC,EAAE,CAAC,CAAC;IAC7E,CAAC;IAED,KAAK,CAAC,qBAAqB;QACvB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,oCAAoC,EAAE,CAAC,CAAC;IAC/E,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/server/mcp.d.ts b/dist/esm/server/mcp.d.ts new file mode 100644 index 0000000000..c0294b5698 --- /dev/null +++ b/dist/esm/server/mcp.d.ts @@ -0,0 +1,332 @@ +import { Server, ServerOptions } from './index.js'; +import { AnySchema, AnyObjectSchema, ZodRawShapeCompat, SchemaOutput, ShapeOutput } from './zod-compat.js'; +import { Implementation, CallToolResult, Resource, ListResourcesResult, GetPromptResult, ReadResourceResult, ServerRequest, ServerNotification, ToolAnnotations, SecurityScheme, LoggingMessageNotification } from '../types.js'; +import { UriTemplate, Variables } from '../shared/uriTemplate.js'; +import { RequestHandlerExtra } from '../shared/protocol.js'; +import { Transport } from '../shared/transport.js'; +/** + * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. + * For advanced usage (like sending notifications or setting custom request handlers), use the underlying + * Server instance available via the `server` property. + */ +export declare class McpServer { + /** + * The underlying Server instance, useful for advanced operations like sending notifications. + */ + readonly server: Server; + private _registeredResources; + private _registeredResourceTemplates; + private _registeredTools; + private _registeredPrompts; + constructor(serverInfo: Implementation, options?: ServerOptions); + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + connect(transport: Transport): Promise; + /** + * Closes the connection. + */ + close(): Promise; + private _toolHandlersInitialized; + private setToolRequestHandlers; + /** + * Creates a tool error result. + * + * @param errorMessage - The error message. + * @returns The tool error result. + */ + private createToolError; + private _completionHandlerInitialized; + private setCompletionRequestHandler; + private handlePromptCompletion; + private handleResourceCompletion; + private _resourceHandlersInitialized; + private setResourceRequestHandlers; + private _promptHandlersInitialized; + private setPromptRequestHandlers; + /** + * Registers a resource `name` at a fixed URI, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, uri: string, readCallback: ReadResourceCallback): RegisteredResource; + /** + * Registers a resource `name` at a fixed URI with metadata, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, uri: string, metadata: ResourceMetadata, readCallback: ReadResourceCallback): RegisteredResource; + /** + * Registers a resource `name` with a template pattern, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, template: ResourceTemplate, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; + /** + * Registers a resource `name` with a template pattern and metadata, which will use the given callback to respond to read requests. + * @deprecated Use `registerResource` instead. + */ + resource(name: string, template: ResourceTemplate, metadata: ResourceMetadata, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; + /** + * Registers a resource with a config object and callback. + * For static resources, use a URI string. For dynamic resources, use a ResourceTemplate. + */ + registerResource(name: string, uriOrTemplate: string, config: ResourceMetadata, readCallback: ReadResourceCallback): RegisteredResource; + registerResource(name: string, uriOrTemplate: ResourceTemplate, config: ResourceMetadata, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; + private _createRegisteredResource; + private _createRegisteredResourceTemplate; + private _createRegisteredPrompt; + private _createRegisteredTool; + /** + * Registers a zero-argument tool `name`, which will run the given function when the client calls it. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, cb: ToolCallback): RegisteredTool; + /** + * Registers a zero-argument tool `name` (with a description) which will run the given function when the client calls it. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, description: string, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool taking either a parameter schema for validation or annotations for additional metadata. + * This unified overload handles both `tool(name, paramsSchema, cb)` and `tool(name, annotations, cb)` cases. + * + * Note: We use a union type for the second parameter because TypeScript cannot reliably disambiguate + * between ToolAnnotations and ZodRawShape during overload resolution, as both are plain object types. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, paramsSchemaOrAnnotations: Args | ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool `name` (with a description) taking either parameter schema or annotations. + * This unified overload handles both `tool(name, description, paramsSchema, cb)` and + * `tool(name, description, annotations, cb)` cases. + * + * Note: We use a union type for the third parameter because TypeScript cannot reliably disambiguate + * between ToolAnnotations and ZodRawShape during overload resolution, as both are plain object types. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, description: string, paramsSchemaOrAnnotations: Args | ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool with both parameter schema and annotations. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, paramsSchema: Args, annotations: ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool with description, parameter schema, and annotations. + * @deprecated Use `registerTool` instead. + */ + tool(name: string, description: string, paramsSchema: Args, annotations: ToolAnnotations, cb: ToolCallback): RegisteredTool; + /** + * Registers a tool with a config object and callback. + */ + registerTool(name: string, config: { + title?: string; + description?: string; + inputSchema?: InputArgs; + outputSchema?: OutputArgs; + annotations?: ToolAnnotations; + securitySchemes?: SecurityScheme[]; + _meta?: Record; + }, cb: ToolCallback): RegisteredTool; + /** + * Registers a zero-argument prompt `name`, which will run the given function when the client calls it. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a zero-argument prompt `name` (with a description) which will run the given function when the client calls it. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, description: string, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a prompt `name` accepting the given arguments, which must be an object containing named properties associated with Zod schemas. When the client calls it, the function will be run with the parsed and validated arguments. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, argsSchema: Args, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a prompt `name` (with a description) accepting the given arguments, which must be an object containing named properties associated with Zod schemas. When the client calls it, the function will be run with the parsed and validated arguments. + * @deprecated Use `registerPrompt` instead. + */ + prompt(name: string, description: string, argsSchema: Args, cb: PromptCallback): RegisteredPrompt; + /** + * Registers a prompt with a config object and callback. + */ + registerPrompt(name: string, config: { + title?: string; + description?: string; + argsSchema?: Args; + }, cb: PromptCallback): RegisteredPrompt; + /** + * Checks if the server is connected to a transport. + * @returns True if the server is connected + */ + isConnected(): boolean; + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string): Promise; + /** + * Sends a resource list changed event to the client, if connected. + */ + sendResourceListChanged(): void; + /** + * Sends a tool list changed event to the client, if connected. + */ + sendToolListChanged(): void; + /** + * Sends a prompt list changed event to the client, if connected. + */ + sendPromptListChanged(): void; +} +/** + * A callback to complete one variable within a resource template's URI template. + */ +export type CompleteResourceTemplateCallback = (value: string, context?: { + arguments?: Record; +}) => string[] | Promise; +/** + * A resource template combines a URI pattern with optional functionality to enumerate + * all resources matching that pattern. + */ +export declare class ResourceTemplate { + private _callbacks; + private _uriTemplate; + constructor(uriTemplate: string | UriTemplate, _callbacks: { + /** + * A callback to list all resources matching this template. This is required to specified, even if `undefined`, to avoid accidentally forgetting resource listing. + */ + list: ListResourcesCallback | undefined; + /** + * An optional callback to autocomplete variables within the URI template. Useful for clients and users to discover possible values. + */ + complete?: { + [variable: string]: CompleteResourceTemplateCallback; + }; + }); + /** + * Gets the URI template pattern. + */ + get uriTemplate(): UriTemplate; + /** + * Gets the list callback, if one was provided. + */ + get listCallback(): ListResourcesCallback | undefined; + /** + * Gets the callback for completing a specific URI template variable, if one was provided. + */ + completeCallback(variable: string): CompleteResourceTemplateCallback | undefined; +} +/** + * Callback for a tool handler registered with Server.tool(). + * + * Parameters will include tool arguments, if applicable, as well as other request handler context. + * + * The callback should return: + * - `structuredContent` if the tool has an outputSchema defined + * - `content` if the tool does not have an outputSchema + * - Both fields are optional but typically one should be provided + */ +export type ToolCallback = Args extends ZodRawShapeCompat ? (args: ShapeOutput, extra: RequestHandlerExtra) => CallToolResult | Promise : Args extends AnySchema ? (args: SchemaOutput, extra: RequestHandlerExtra) => CallToolResult | Promise : (extra: RequestHandlerExtra) => CallToolResult | Promise; +export type RegisteredTool = { + title?: string; + description?: string; + inputSchema?: AnySchema; + outputSchema?: AnySchema; + annotations?: ToolAnnotations; + securitySchemes?: SecurityScheme[]; + _meta?: Record; + callback: ToolCallback; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string | null; + title?: string; + description?: string; + paramsSchema?: InputArgs; + outputSchema?: OutputArgs; + annotations?: ToolAnnotations; + securitySchemes?: SecurityScheme[]; + _meta?: Record; + callback?: ToolCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +/** + * Additional, optional information for annotating a resource. + */ +export type ResourceMetadata = Omit; +/** + * Callback to list all resources matching a given template. + */ +export type ListResourcesCallback = (extra: RequestHandlerExtra) => ListResourcesResult | Promise; +/** + * Callback to read a resource at a given URI. + */ +export type ReadResourceCallback = (uri: URL, extra: RequestHandlerExtra) => ReadResourceResult | Promise; +export type RegisteredResource = { + name: string; + title?: string; + metadata?: ResourceMetadata; + readCallback: ReadResourceCallback; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string; + title?: string; + uri?: string | null; + metadata?: ResourceMetadata; + callback?: ReadResourceCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +/** + * Callback to read a resource at a given URI, following a filled-in URI template. + */ +export type ReadResourceTemplateCallback = (uri: URL, variables: Variables, extra: RequestHandlerExtra) => ReadResourceResult | Promise; +export type RegisteredResourceTemplate = { + resourceTemplate: ResourceTemplate; + title?: string; + metadata?: ResourceMetadata; + readCallback: ReadResourceTemplateCallback; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string | null; + title?: string; + template?: ResourceTemplate; + metadata?: ResourceMetadata; + callback?: ReadResourceTemplateCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +type PromptArgsRawShape = ZodRawShapeCompat; +export type PromptCallback = Args extends PromptArgsRawShape ? (args: ShapeOutput, extra: RequestHandlerExtra) => GetPromptResult | Promise : (extra: RequestHandlerExtra) => GetPromptResult | Promise; +export type RegisteredPrompt = { + title?: string; + description?: string; + argsSchema?: AnyObjectSchema; + callback: PromptCallback; + enabled: boolean; + enable(): void; + disable(): void; + update(updates: { + name?: string | null; + title?: string; + description?: string; + argsSchema?: Args; + callback?: PromptCallback; + enabled?: boolean; + }): void; + remove(): void; +}; +export {}; +//# sourceMappingURL=mcp.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/mcp.d.ts.map b/dist/esm/server/mcp.d.ts.map new file mode 100644 index 0000000000..9ed3a0fd27 --- /dev/null +++ b/dist/esm/server/mcp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../../../src/server/mcp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACH,SAAS,EACT,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,WAAW,EASd,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EACH,cAAc,EAGd,cAAc,EAOd,QAAQ,EACR,mBAAmB,EAYnB,e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K,kBAAkB,GAAG,iBAAiB,CAAC;AAE5C,MAAM,MAAM,cAAc,CAAC,IAAI,SAAS,SAAS,GAAG,kBAAkB,GAAG,SAAS,IAAI,IAAI,SAAS,kBAAkB,GAC/G,CAAC,IAAI,EAAE,WAAW,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,mBAAmB,CAAC,aAAa,EAAE,kBAAkB,CAAC,KAAK,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,GACtI,CAAC,KAAK,EAAE,mBAAmB,CAAC,aAAa,EAAE,kBAAkB,CAAC,KAAK,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;AAEpH,MAAM,MAAM,gBAAgB,GAAG;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,eAAe,CAAC;IAC7B,QAAQ,EAAE,cAAc,CAAC,SAAS,GAAG,kBAAkB,CAAC,CAAC;IACzD,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,IAAI,IAAI,CAAC;IACf,OAAO,IAAI,IAAI,CAAC;IAChB,MAAM,CAAC,IAAI,SAAS,kBAAkB,EAAE,OAAO,EAAE;QAC7C,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QACrB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,UAAU,CAAC,EAAE,IAAI,CAAC;QAClB,QAAQ,CAAC,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC;QAChC,OAAO,CAAC,EAAE,OAAO,CAAC;KACrB,GAAG,IAAI,CAAC;IACT,MAAM,IAAI,IAAI,CAAC;CAClB,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/mcp.js b/dist/esm/server/mcp.js new file mode 100644 index 0000000000..b0392350b5 --- /dev/null +++ b/dist/esm/server/mcp.js @@ -0,0 +1,753 @@ +import { Server } from './index.js'; +import { normalizeObjectSchema, safeParseAsync, getObjectShape, objectFromShape, getParseErrorMessage, getSchemaDescription, isSchemaOptional, getLiteralValue } from './zod-compat.js'; +import { toJsonSchemaCompat } from './zod-json-schema-compat.js'; +import { McpError, ErrorCode, ListResourceTemplatesRequestSchema, ReadResourceRequestSchema, ListToolsRequestSchema, CallToolRequestSchema, ListResourcesRequestSchema, ListPromptsRequestSchema, GetPromptRequestSchema, CompleteRequestSchema, assertCompleteRequestPrompt, assertCompleteRequestResourceTemplate } from '../types.js'; +import { isCompletable, getCompleter } from './completable.js'; +import { UriTemplate } from '../shared/uriTemplate.js'; +import { validateAndWarnToolName } from '../shared/toolNameValidation.js'; +/** + * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. + * For advanced usage (like sending notifications or setting custom request handlers), use the underlying + * Server instance available via the `server` property. + */ +export class McpServer { + constructor(serverInfo, options) { + this._registeredResources = {}; + this._registeredResourceTemplates = {}; + this._registeredTools = {}; + this._registeredPrompts = {}; + this._toolHandlersInitialized = false; + this._completionHandlerInitialized = false; + this._resourceHandlersInitialized = false; + this._promptHandlersInitialized = false; + this.server = new Server(serverInfo, options); + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + async connect(transport) { + return await this.server.connect(transport); + } + /** + * Closes the connection. + */ + async close() { + await this.server.close(); + } + setToolRequestHandlers() { + if (this._toolHandlersInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)); + this.server.registerCapabilities({ + tools: { + listChanged: true + } + }); + this.server.setRequestHandler(ListToolsRequestSchema, () => { + // eslint-disable-next-line no-console + console.log('Tool list handler called'); + return { + tools: Object.entries(this._registeredTools) + .filter(([, tool]) => tool.enabled) + .map(([name, tool]) => { + const toolDefinition = { + name, + title: tool.title, + description: tool.description, + inputSchema: (() => { + const obj = normalizeObjectSchema(tool.inputSchema); + return obj + ? toJsonSchemaCompat(obj, { + strictUnions: true, + pipeStrategy: 'input' + }) + : EMPTY_OBJECT_JSON_SCHEMA; + })(), + annotations: tool.annotations, + securitySchemes: tool.securitySchemes, + _meta: tool._meta + }; + if (tool.outputSchema) { + const obj = normalizeObjectSchema(tool.outputSchema); + if (obj) { + toolDefinition.outputSchema = toJsonSchemaCompat(obj, { + strictUnions: true, + pipeStrategy: 'output' + }); + } + } + return toolDefinition; + }) + }; + }); + this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { + const tool = this._registeredTools[request.params.name]; + let result; + try { + if (!tool) { + throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`); + } + if (!tool.enabled) { + throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); + } + if (tool.inputSchema) { + const cb = tool.callback; + // Try to normalize to object schema first (for raw shapes and object schemas) + // If that fails, use the schema directly (for union/intersection/etc) + const inputObj = normalizeObjectSchema(tool.inputSchema); + const schemaToParse = inputObj !== null && inputObj !== void 0 ? inputObj : tool.inputSchema; + const parseResult = await safeParseAsync(schemaToParse, request.params.arguments); + if (!parseResult.success) { + throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${request.params.name}: ${getParseErrorMessage(parseResult.error)}`); + } + const args = parseResult.data; + result = await Promise.resolve(cb(args, extra)); + } + else { + const cb = tool.callback; + result = await Promise.resolve(cb(extra)); + } + if (tool.outputSchema && !result.isError) { + if (!result.structuredContent) { + throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${request.params.name} has an output schema but no structured content was provided`); + } + // if the tool has an output schema, validate structured content + const outputObj = normalizeObjectSchema(tool.outputSchema); + const parseResult = await safeParseAsync(outputObj, result.structuredContent); + if (!parseResult.success) { + throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${request.params.name}: ${getParseErrorMessage(parseResult.error)}`); + } + } + } + catch (error) { + if (error instanceof McpError) { + if (error.code === ErrorCode.UrlElicitationRequired) { + throw error; // Return the error to the caller without wrapping in CallToolResult + } + } + return this.createToolError(error instanceof Error ? error.message : String(error)); + } + return result; + }); + this._toolHandlersInitialized = true; + } + /** + * Creates a tool error result. + * + * @param errorMessage - The error message. + * @returns The tool error result. + */ + createToolError(errorMessage) { + return { + content: [ + { + type: 'text', + text: errorMessage + } + ], + isError: true + }; + } + setCompletionRequestHandler() { + if (this._completionHandlerInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)); + this.server.registerCapabilities({ + completions: {} + }); + this.server.setRequestHandler(CompleteRequestSchema, async (request) => { + switch (request.params.ref.type) { + case 'ref/prompt': + assertCompleteRequestPrompt(request); + return this.handlePromptCompletion(request, request.params.ref); + case 'ref/resource': + assertCompleteRequestResourceTemplate(request); + return this.handleResourceCompletion(request, request.params.ref); + default: + throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); + } + }); + this._completionHandlerInitialized = true; + } + async handlePromptCompletion(request, ref) { + const prompt = this._registeredPrompts[ref.name]; + if (!prompt) { + throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`); + } + if (!prompt.enabled) { + throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); + } + if (!prompt.argsSchema) { + return EMPTY_COMPLETION_RESULT; + } + const promptShape = getObjectShape(prompt.argsSchema); + const field = promptShape === null || promptShape === void 0 ? void 0 : promptShape[request.params.argument.name]; + if (!isCompletable(field)) { + return EMPTY_COMPLETION_RESULT; + } + const completer = getCompleter(field); + if (!completer) { + return EMPTY_COMPLETION_RESULT; + } + const suggestions = await completer(request.params.argument.value, request.params.context); + return createCompletionResult(suggestions); + } + async handleResourceCompletion(request, ref) { + const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri); + if (!template) { + if (this._registeredResources[ref.uri]) { + // Attempting to autocomplete a fixed resource URI is not an error in the spec (but probably should be). + return EMPTY_COMPLETION_RESULT; + } + throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); + } + const completer = template.resourceTemplate.completeCallback(request.params.argument.name); + if (!completer) { + return EMPTY_COMPLETION_RESULT; + } + const suggestions = await completer(request.params.argument.value, request.params.context); + return createCompletionResult(suggestions); + } + setResourceRequestHandlers() { + if (this._resourceHandlersInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)); + this.server.registerCapabilities({ + resources: { + listChanged: true + } + }); + this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => { + const resources = Object.entries(this._registeredResources) + .filter(([_, resource]) => resource.enabled) + .map(([uri, resource]) => ({ + uri, + name: resource.name, + ...resource.metadata + })); + const templateResources = []; + for (const template of Object.values(this._registeredResourceTemplates)) { + if (!template.resourceTemplate.listCallback) { + continue; + } + const result = await template.resourceTemplate.listCallback(extra); + for (const resource of result.resources) { + templateResources.push({ + ...template.metadata, + // the defined resource metadata should override the template metadata if present + ...resource + }); + } + } + return { resources: [...resources, ...templateResources] }; + }); + this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => { + const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ + name, + uriTemplate: template.resourceTemplate.uriTemplate.toString(), + ...template.metadata + })); + return { resourceTemplates }; + }); + this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => { + const uri = new URL(request.params.uri); + // First check for exact resource match + const resource = this._registeredResources[uri.toString()]; + if (resource) { + if (!resource.enabled) { + throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`); + } + return resource.readCallback(uri, extra); + } + // Then check templates + for (const template of Object.values(this._registeredResourceTemplates)) { + const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); + if (variables) { + return template.readCallback(uri, variables, extra); + } + } + throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`); + }); + this.setCompletionRequestHandler(); + this._resourceHandlersInitialized = true; + } + setPromptRequestHandlers() { + if (this._promptHandlersInitialized) { + return; + } + this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)); + this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)); + this.server.registerCapabilities({ + prompts: { + listChanged: true + } + }); + this.server.setRequestHandler(ListPromptsRequestSchema, () => ({ + prompts: Object.entries(this._registeredPrompts) + .filter(([, prompt]) => prompt.enabled) + .map(([name, prompt]) => { + return { + name, + title: prompt.title, + description: prompt.description, + arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined + }; + }) + })); + this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => { + const prompt = this._registeredPrompts[request.params.name]; + if (!prompt) { + throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); + } + if (!prompt.enabled) { + throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); + } + if (prompt.argsSchema) { + const argsObj = normalizeObjectSchema(prompt.argsSchema); + const parseResult = await safeParseAsync(argsObj, request.params.arguments); + if (!parseResult.success) { + throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${getParseErrorMessage(parseResult.error)}`); + } + const args = parseResult.data; + const cb = prompt.callback; + return await Promise.resolve(cb(args, extra)); + } + else { + const cb = prompt.callback; + return await Promise.resolve(cb(extra)); + } + }); + this.setCompletionRequestHandler(); + this._promptHandlersInitialized = true; + } + resource(name, uriOrTemplate, ...rest) { + let metadata; + if (typeof rest[0] === 'object') { + metadata = rest.shift(); + } + const readCallback = rest[0]; + if (typeof uriOrTemplate === 'string') { + if (this._registeredResources[uriOrTemplate]) { + throw new Error(`Resource ${uriOrTemplate} is already registered`); + } + const registeredResource = this._createRegisteredResource(name, undefined, uriOrTemplate, metadata, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } + else { + if (this._registeredResourceTemplates[name]) { + throw new Error(`Resource template ${name} is already registered`); + } + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, undefined, uriOrTemplate, metadata, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + registerResource(name, uriOrTemplate, config, readCallback) { + if (typeof uriOrTemplate === 'string') { + if (this._registeredResources[uriOrTemplate]) { + throw new Error(`Resource ${uriOrTemplate} is already registered`); + } + const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } + else { + if (this._registeredResourceTemplates[name]) { + throw new Error(`Resource template ${name} is already registered`); + } + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback); + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + _createRegisteredResource(name, title, uri, metadata, readCallback) { + const registeredResource = { + name, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResource.update({ enabled: false }), + enable: () => registeredResource.update({ enabled: true }), + remove: () => registeredResource.update({ uri: null }), + update: updates => { + if (typeof updates.uri !== 'undefined' && updates.uri !== uri) { + delete this._registeredResources[uri]; + if (updates.uri) + this._registeredResources[updates.uri] = registeredResource; + } + if (typeof updates.name !== 'undefined') + registeredResource.name = updates.name; + if (typeof updates.title !== 'undefined') + registeredResource.title = updates.title; + if (typeof updates.metadata !== 'undefined') + registeredResource.metadata = updates.metadata; + if (typeof updates.callback !== 'undefined') + registeredResource.readCallback = updates.callback; + if (typeof updates.enabled !== 'undefined') + registeredResource.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResources[uri] = registeredResource; + return registeredResource; + } + _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { + const registeredResourceTemplate = { + resourceTemplate: template, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResourceTemplate.update({ enabled: false }), + enable: () => registeredResourceTemplate.update({ enabled: true }), + remove: () => registeredResourceTemplate.update({ name: null }), + update: updates => { + if (typeof updates.name !== 'undefined' && updates.name !== name) { + delete this._registeredResourceTemplates[name]; + if (updates.name) + this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; + } + if (typeof updates.title !== 'undefined') + registeredResourceTemplate.title = updates.title; + if (typeof updates.template !== 'undefined') + registeredResourceTemplate.resourceTemplate = updates.template; + if (typeof updates.metadata !== 'undefined') + registeredResourceTemplate.metadata = updates.metadata; + if (typeof updates.callback !== 'undefined') + registeredResourceTemplate.readCallback = updates.callback; + if (typeof updates.enabled !== 'undefined') + registeredResourceTemplate.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResourceTemplates[name] = registeredResourceTemplate; + return registeredResourceTemplate; + } + _createRegisteredPrompt(name, title, description, argsSchema, callback) { + const registeredPrompt = { + title, + description, + argsSchema: argsSchema === undefined ? undefined : objectFromShape(argsSchema), + callback, + enabled: true, + disable: () => registeredPrompt.update({ enabled: false }), + enable: () => registeredPrompt.update({ enabled: true }), + remove: () => registeredPrompt.update({ name: null }), + update: updates => { + if (typeof updates.name !== 'undefined' && updates.name !== name) { + delete this._registeredPrompts[name]; + if (updates.name) + this._registeredPrompts[updates.name] = registeredPrompt; + } + if (typeof updates.title !== 'undefined') + registeredPrompt.title = updates.title; + if (typeof updates.description !== 'undefined') + registeredPrompt.description = updates.description; + if (typeof updates.argsSchema !== 'undefined') + registeredPrompt.argsSchema = objectFromShape(updates.argsSchema); + if (typeof updates.callback !== 'undefined') + registeredPrompt.callback = updates.callback; + if (typeof updates.enabled !== 'undefined') + registeredPrompt.enabled = updates.enabled; + this.sendPromptListChanged(); + } + }; + this._registeredPrompts[name] = registeredPrompt; + return registeredPrompt; + } + _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, securitySchemes, _meta, callback) { + // Validate tool name according to SEP specification + validateAndWarnToolName(name); + const registeredTool = { + title, + description, + inputSchema: getZodSchemaObject(inputSchema), + outputSchema: getZodSchemaObject(outputSchema), + annotations, + securitySchemes, + _meta, + callback, + enabled: true, + disable: () => registeredTool.update({ enabled: false }), + enable: () => registeredTool.update({ enabled: true }), + remove: () => registeredTool.update({ name: null }), + update: updates => { + if (typeof updates.name !== 'undefined' && updates.name !== name) { + if (typeof updates.name === 'string') { + validateAndWarnToolName(updates.name); + } + delete this._registeredTools[name]; + if (updates.name) + this._registeredTools[updates.name] = registeredTool; + } + if (typeof updates.title !== 'undefined') + registeredTool.title = updates.title; + if (typeof updates.description !== 'undefined') + registeredTool.description = updates.description; + if (typeof updates.paramsSchema !== 'undefined') + registeredTool.inputSchema = objectFromShape(updates.paramsSchema); + if (typeof updates.callback !== 'undefined') + registeredTool.callback = updates.callback; + if (typeof updates.annotations !== 'undefined') + registeredTool.annotations = updates.annotations; + if (typeof updates.securitySchemes !== 'undefined') + registeredTool.securitySchemes = updates.securitySchemes; + if (typeof updates._meta !== 'undefined') + registeredTool._meta = updates._meta; + if (typeof updates.enabled !== 'undefined') + registeredTool.enabled = updates.enabled; + this.sendToolListChanged(); + } + }; + this._registeredTools[name] = registeredTool; + this.setToolRequestHandlers(); + this.sendToolListChanged(); + return registeredTool; + } + /** + * tool() implementation. Parses arguments passed to overrides defined above. + */ + tool(name, ...rest) { + if (this._registeredTools[name]) { + throw new Error(`Tool ${name} is already registered`); + } + let description; + let inputSchema; + let outputSchema; + let annotations; + // Tool properties are passed as separate arguments, with omissions allowed. + // Support for this style is frozen as of protocol version 2025-03-26. Future additions + // to tool definition should *NOT* be added. + if (typeof rest[0] === 'string') { + description = rest.shift(); + } + // Handle the different overload combinations + if (rest.length > 1) { + // We have at least one more arg before the callback + const firstArg = rest[0]; + if (isZodRawShape(firstArg)) { + // We have a params schema as the first arg + inputSchema = rest.shift(); + // Check if the next arg is potentially annotations + if (rest.length > 1 && typeof rest[0] === 'object' && rest[0] !== null && !isZodRawShape(rest[0])) { + // Case: tool(name, paramsSchema, annotations, cb) + // Or: tool(name, description, paramsSchema, annotations, cb) + annotations = rest.shift(); + } + } + else if (typeof firstArg === 'object' && firstArg !== null) { + // Not a ZodRawShape, so must be annotations in this position + // Case: tool(name, annotations, cb) + // Or: tool(name, description, annotations, cb) + annotations = rest.shift(); + } + } + const callback = rest[0]; + return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, undefined, undefined, callback); + } + /** + * Registers a tool with a config object and callback. + */ + registerTool(name, config, cb) { + if (this._registeredTools[name]) { + throw new Error(`Tool ${name} is already registered`); + } + console.log('registerTool'); + const { title, description, inputSchema, outputSchema, annotations, securitySchemes, _meta } = config; + return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, securitySchemes, _meta, cb); + } + prompt(name, ...rest) { + if (this._registeredPrompts[name]) { + throw new Error(`Prompt ${name} is already registered`); + } + let description; + if (typeof rest[0] === 'string') { + description = rest.shift(); + } + let argsSchema; + if (rest.length > 1) { + argsSchema = rest.shift(); + } + const cb = rest[0]; + const registeredPrompt = this._createRegisteredPrompt(name, undefined, description, argsSchema, cb); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } + /** + * Registers a prompt with a config object and callback. + */ + registerPrompt(name, config, cb) { + if (this._registeredPrompts[name]) { + throw new Error(`Prompt ${name} is already registered`); + } + const { title, description, argsSchema } = config; + const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } + /** + * Checks if the server is connected to a transport. + * @returns True if the server is connected + */ + isConnected() { + return this.server.transport !== undefined; + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON RPC message + * @see LoggingMessageNotification + * @param params + * @param sessionId optional for stateless and backward compatibility + */ + async sendLoggingMessage(params, sessionId) { + return this.server.sendLoggingMessage(params, sessionId); + } + /** + * Sends a resource list changed event to the client, if connected. + */ + sendResourceListChanged() { + if (this.isConnected()) { + this.server.sendResourceListChanged(); + } + } + /** + * Sends a tool list changed event to the client, if connected. + */ + sendToolListChanged() { + if (this.isConnected()) { + this.server.sendToolListChanged(); + } + } + /** + * Sends a prompt list changed event to the client, if connected. + */ + sendPromptListChanged() { + if (this.isConnected()) { + this.server.sendPromptListChanged(); + } + } +} +/** + * A resource template combines a URI pattern with optional functionality to enumerate + * all resources matching that pattern. + */ +export class ResourceTemplate { + constructor(uriTemplate, _callbacks) { + this._callbacks = _callbacks; + this._uriTemplate = typeof uriTemplate === 'string' ? new UriTemplate(uriTemplate) : uriTemplate; + } + /** + * Gets the URI template pattern. + */ + get uriTemplate() { + return this._uriTemplate; + } + /** + * Gets the list callback, if one was provided. + */ + get listCallback() { + return this._callbacks.list; + } + /** + * Gets the callback for completing a specific URI template variable, if one was provided. + */ + completeCallback(variable) { + var _a; + return (_a = this._callbacks.complete) === null || _a === void 0 ? void 0 : _a[variable]; + } +} +const EMPTY_OBJECT_JSON_SCHEMA = { + type: 'object', + properties: {} +}; +// Helper to check if an object is a Zod schema (ZodRawShapeCompat) +function isZodRawShape(obj) { + if (typeof obj !== 'object' || obj === null) + return false; + const isEmptyObject = Object.keys(obj).length === 0; + // Check if object is empty or at least one property is a ZodType instance + // Note: use heuristic check to avoid instanceof failure across different Zod versions + return isEmptyObject || Object.values(obj).some(isZodTypeLike); +} +function isZodTypeLike(value) { + return (value !== null && + typeof value === 'object' && + 'parse' in value && + typeof value.parse === 'function' && + 'safeParse' in value && + typeof value.safeParse === 'function'); +} +/** + * Converts a provided Zod schema to a Zod object if it is a ZodRawShape, + * otherwise returns the schema as is. + */ +function getZodSchemaObject(schema) { + if (!schema) { + return undefined; + } + if (isZodRawShape(schema)) { + return objectFromShape(schema); + } + return schema; +} +function promptArgumentsFromSchema(schema) { + const shape = getObjectShape(schema); + if (!shape) + return []; + return Object.entries(shape).map(([name, field]) => { + // Get description - works for both v3 and v4 + const description = getSchemaDescription(field); + // Check if optional - works for both v3 and v4 + const isOptional = isSchemaOptional(field); + return { + name, + description, + required: !isOptional + }; + }); +} +function getMethodValue(schema) { + const shape = getObjectShape(schema); + const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + // Extract literal value - works for both v3 and v4 + const value = getLiteralValue(methodSchema); + if (typeof value === 'string') { + return value; + } + throw new Error('Schema method literal must be a string'); +} +function createCompletionResult(suggestions) { + return { + completion: { + values: suggestions.slice(0, 100), + total: suggestions.length, + hasMore: suggestions.length > 100 + } + }; +} +const EMPTY_COMPLETION_RESULT = { + completion: { + values: [], + hasMore: false + } +}; +//# sourceMappingURL=mcp.js.map \ No newline at end of file diff --git a/dist/esm/server/mcp.js.map b/dist/esm/server/mcp.js.map new file mode 100644 index 0000000000..65a19268f4 --- /dev/null +++ b/dist/esm/server/mcp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mcp.js","sourceRoot":"","sources":["../../../src/server/mcp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAiB,MAAM,YAAY,CAAC;AACnD,OAAO,EAMH,qBAAqB,EACrB,cAAc,EACd,cAAc,EACd,eAAe,EACf,oBAAoB,EACpB,oBAAoB,EACpB,gBAAgB,EAChB,eAAe,EAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAKH,QAAQ,EACR,SAAS,EAOT,kCAAkC,EAClC,yBAAyB,EACzB,sBAAsB,EACtB,qBAAqB,EACrB,0BAA0B,EAC1B,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EAarB,2BAA2B,EAC3B,qCAAqC,EACxC,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAa,MAAM,0BAA0B,CAAC;AAGlE,OAAO,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAE1E;;;;GAIG;AACH,MAAM,OAAO,SAAS;IAalB,YAAY,UAA0B,EAAE,O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AI;YACJ,WAAW;YACX,QAAQ,EAAE,CAAC,UAAU;SACxB,CAAC;IACN,CAAC,CAAC,CAAC;AACP,CAAC;AAED,SAAS,cAAc,CAAC,MAAuB;IAC3C,MAAM,KAAK,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC;IACrC,MAAM,YAAY,GAAG,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,MAA+B,CAAC;IAC5D,IAAI,CAAC,YAAY,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;IAC1D,CAAC;IAED,mDAAmD;IACnD,MAAM,KAAK,GAAG,eAAe,CAAC,YAAY,CAAC,CAAC;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC5B,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC9D,CAAC;AAED,SAAS,sBAAsB,CAAC,WAAqB;IACjD,OAAO;QACH,UAAU,EAAE;YACR,MAAM,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC;YACjC,KAAK,EAAE,WAAW,CAAC,MAAM;YACzB,OAAO,EAAE,WAAW,CAAC,MAAM,GAAG,GAAG;SACpC;KACJ,CAAC;AACN,CAAC;AAED,MAAM,uBAAuB,GAAmB;IAC5C,UAAU,EAAE;QACR,MAAM,EAAE,EAAE;QACV,OAAO,EAAE,KAAK;KACjB;CACJ,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/sse.d.ts b/dist/esm/server/sse.d.ts new file mode 100644 index 0000000000..aba8d51209 --- /dev/null +++ b/dist/esm/server/sse.d.ts @@ -0,0 +1,76 @@ +import { IncomingMessage, ServerResponse } from 'node:http'; +import { Transport } from '../shared/transport.js'; +import { JSONRPCMessage, MessageExtraInfo } from '../types.js'; +import { AuthInfo } from './auth/types.js'; +/** + * Configuration options for SSEServerTransport. + */ +export interface SSEServerTransportOptions { + /** + * List of allowed host header values for DNS rebinding protection. + * If not specified, host validation is disabled. + */ + allowedHosts?: string[]; + /** + * List of allowed origin header values for DNS rebinding protection. + * If not specified, origin validation is disabled. + */ + allowedOrigins?: string[]; + /** + * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). + * Default is false for backwards compatibility. + */ + enableDnsRebindingProtection?: boolean; +} +/** + * Server transport for SSE: this will send messages over an SSE connection and receive messages from HTTP POST requests. + * + * This transport is only available in Node.js environments. + * @deprecated SSEServerTransport is deprecated. Use StreamableHTTPServerTransport instead. + */ +export declare class SSEServerTransport implements Transport { + private _endpoint; + private res; + private _sseResponse?; + private _sessionId; + private _options; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; + /** + * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. + */ + constructor(_endpoint: string, res: ServerResponse, options?: SSEServerTransportOptions); + /** + * Validates request headers for DNS rebinding protection. + * @returns Error message if validation fails, undefined if validation passes. + */ + private validateRequestHeaders; + /** + * Handles the initial SSE connection request. + * + * This should be called when a GET request is made to establish the SSE stream. + */ + start(): Promise; + /** + * Handles incoming POST messages. + * + * This should be called when a POST request is made to send a message to the server. + */ + handlePostMessage(req: IncomingMessage & { + auth?: AuthInfo; + }, res: ServerResponse, parsedBody?: unknown): Promise; + /** + * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. + */ + handleMessage(message: unknown, extra?: MessageExtraInfo): Promise; + close(): Promise; + send(message: JSONRPCMessage): Promise; + /** + * Returns the session ID for this transport. + * + * This can be used to route incoming POST requests. + */ + get sessionId(): string; +} +//# sourceMappingURL=sse.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/sse.d.ts.map b/dist/esm/server/sse.d.ts.map new file mode 100644 index 0000000000..c3c267cd8f --- /dev/null +++ b/dist/esm/server/sse.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"sse.d.ts","sourceR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,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IA+C7H;;OAEG;IACG,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;IAYxE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAMtB,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAQlD;;;;OAIG;IACH,IAAI,SAAS,IAAI,MAAM,CAEtB;CACJ"} \ No newline at end of file diff --git a/dist/esm/server/sse.js b/dist/esm/server/sse.js new file mode 100644 index 0000000000..3bf3c51952 --- /dev/null +++ b/dist/esm/server/sse.js @@ -0,0 +1,161 @@ +import { randomUUID } from 'node:crypto'; +import { JSONRPCMessageSchema } from '../types.js'; +import getRawBody from 'raw-body'; +import contentType from 'content-type'; +import { URL } from 'url'; +const MAXIMUM_MESSAGE_SIZE = '4mb'; +/** + * Server transport for SSE: this will send messages over an SSE connection and receive messages from HTTP POST requests. + * + * This transport is only available in Node.js environments. + * @deprecated SSEServerTransport is deprecated. Use StreamableHTTPServerTransport instead. + */ +export class SSEServerTransport { + /** + * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. + */ + constructor(_endpoint, res, options) { + this._endpoint = _endpoint; + this.res = res; + this._sessionId = randomUUID(); + this._options = options || { enableDnsRebindingProtection: false }; + } + /** + * Validates request headers for DNS rebinding protection. + * @returns Error message if validation fails, undefined if validation passes. + */ + validateRequestHeaders(req) { + // Skip validation if protection is not enabled + if (!this._options.enableDnsRebindingProtection) { + return undefined; + } + // Validate Host header if allowedHosts is configured + if (this._options.allowedHosts && this._options.allowedHosts.length > 0) { + const hostHeader = req.headers.host; + if (!hostHeader || !this._options.allowedHosts.includes(hostHeader)) { + return `Invalid Host header: ${hostHeader}`; + } + } + // Validate Origin header if allowedOrigins is configured + if (this._options.allowedOrigins && this._options.allowedOrigins.length > 0) { + const originHeader = req.headers.origin; + if (!originHeader || !this._options.allowedOrigins.includes(originHeader)) { + return `Invalid Origin header: ${originHeader}`; + } + } + return undefined; + } + /** + * Handles the initial SSE connection request. + * + * This should be called when a GET request is made to establish the SSE stream. + */ + async start() { + if (this._sseResponse) { + throw new Error('SSEServerTransport already started! If using Server class, note that connect() calls start() automatically.'); + } + this.res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive' + }); + // Send the endpoint event + // Use a dummy base URL because this._endpoint is relative. + // This allows using URL/URLSearchParams for robust parameter handling. + const dummyBase = 'http://localhost'; // Any valid base works + const endpointUrl = new URL(this._endpoint, dummyBase); + endpointUrl.searchParams.set('sessionId', this._sessionId); + // Reconstruct the relative URL string (pathname + search + hash) + const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash; + this.res.write(`event: endpoint\ndata: ${relativeUrlWithSession}\n\n`); + this._sseResponse = this.res; + this.res.on('close', () => { + var _a; + this._sseResponse = undefined; + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + }); + } + /** + * Handles incoming POST messages. + * + * This should be called when a POST request is made to send a message to the server. + */ + async handlePostMessage(req, res, parsedBody) { + var _a, _b, _c, _d; + if (!this._sseResponse) { + const message = 'SSE connection not established'; + res.writeHead(500).end(message); + throw new Error(message); + } + // Validate request headers for DNS rebinding protection + const validationError = this.validateRequestHeaders(req); + if (validationError) { + res.writeHead(403).end(validationError); + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(validationError)); + return; + } + const authInfo = req.auth; + const requestInfo = { headers: req.headers }; + let body; + try { + const ct = contentType.parse((_b = req.headers['content-type']) !== null && _b !== void 0 ? _b : ''); + if (ct.type !== 'application/json') { + throw new Error(`Unsupported content-type: ${ct.type}`); + } + body = + parsedBody !== null && parsedBody !== void 0 ? parsedBody : (await getRawBody(req, { + limit: MAXIMUM_MESSAGE_SIZE, + encoding: (_c = ct.parameters.charset) !== null && _c !== void 0 ? _c : 'utf-8' + })); + } + catch (error) { + res.writeHead(400).end(String(error)); + (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error); + return; + } + try { + await this.handleMessage(typeof body === 'string' ? JSON.parse(body) : body, { requestInfo, authInfo }); + } + catch (_e) { + res.writeHead(400).end(`Invalid message: ${body}`); + return; + } + res.writeHead(202).end('Accepted'); + } + /** + * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. + */ + async handleMessage(message, extra) { + var _a, _b; + let parsedMessage; + try { + parsedMessage = JSONRPCMessageSchema.parse(message); + } + catch (error) { + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + throw error; + } + (_b = this.onmessage) === null || _b === void 0 ? void 0 : _b.call(this, parsedMessage, extra); + } + async close() { + var _a, _b; + (_a = this._sseResponse) === null || _a === void 0 ? void 0 : _a.end(); + this._sseResponse = undefined; + (_b = this.onclose) === null || _b === void 0 ? void 0 : _b.call(this); + } + async send(message) { + if (!this._sseResponse) { + throw new Error('Not connected'); + } + this._sseResponse.write(`event: message\ndata: ${JSON.stringify(message)}\n\n`); + } + /** + * Returns the session ID for this transport. + * + * This can be used to route incoming POST requests. + */ + get sessionId() { + return this._sessionId; + } +} +//# sourceMappingURL=sse.js.map \ No newline at end of file diff --git a/dist/esm/server/sse.js.map b/dist/esm/server/sse.js.map new file mode 100644 index 0000000000..af4dc36a1b --- /dev/null +++ b/dist/esm/server/sse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sse.js","sourceRoot":"","sources":["../../../src/server/sse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAAkB,oBAAoB,EAAiC,MAAM,aAAa,CAAC;AAClG,OAAO,UAAU,MAAM,UAAU,CAAC;AAClC,OAAO,WAAW,MAAM,cAAc,CAAC;AAEvC,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAE1B,MAAM,oBAAoB,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,CAAC,MAAM,CAAC,CAAC;IACpF,CAAC;IAED;;;;OAIG;IACH,IAAI,SAAS;QACT,OAAO,IAAI,CAAC,UAAU,CAAC;IAC3B,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/server/stdio.d.ts b/dist/esm/server/stdio.d.ts new file mode 100644 index 0000000000..df3029d0da --- /dev/null +++ b/dist/esm/server/stdio.d.ts @@ -0,0 +1,28 @@ +import { Readable, Writable } from 'node:stream'; +import { JSONRPCMessage } from '../types.js'; +import { Transport } from '../shared/transport.js'; +/** + * Server transport for stdio: this communicates with a MCP client by reading from the current process' stdin and writing to stdout. + * + * This transport is only available in Node.js environments. + */ +export declare class StdioServerTransport implements Transport { + private _stdin; + private _stdout; + private _readBuffer; + private _started; + constructor(_stdin?: Readable, _stdout?: Writable); + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage) => void; + _ondata: (chunk: Buffer) => void; + _onerror: (error: Error) => void; + /** + * Starts listening for messages on stdin. + */ + start(): Promise; + private processReadBuffer; + close(): Promise; + send(message: JSONRPCMessage): Promise; +} +//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/stdio.d.ts.map b/dist/esm/server/stdio.d.ts.map new file mode 100644 index 0000000000..fdd2dfe48e --- /dev/null +++ b/dist/esm/server/stdio.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/server/stdio.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;;;GAIG;AACH,qBAAa,oBAAqB,YAAW,SAAS;IAK9C,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,OAAO;IALnB,OAAO,CAAC,WAAW,CAAgC;IACnD,OAAO,CAAC,QAAQ,CAAS;gBAGb,MAAM,GAAE,QAAwB,EAChC,OAAO,GAAE,QAAyB;IAG9C,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;IAG9C,OAAO,UAAW,MAAM,UAGtB;IACF,QAAQ,UAAW,KAAK,UAEtB;IAEF;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAY5B,OAAO,CAAC,iBAAiB;IAenB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAkB5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAU/C"} \ No newline at end of file diff --git a/dist/esm/server/stdio.js b/dist/esm/server/stdio.js new file mode 100644 index 0000000000..98a3467ed2 --- /dev/null +++ b/dist/esm/server/stdio.js @@ -0,0 +1,78 @@ +import process from 'node:process'; +import { ReadBuffer, serializeMessage } from '../shared/stdio.js'; +/** + * Server transport for stdio: this communicates with a MCP client by reading from the current process' stdin and writing to stdout. + * + * This transport is only available in Node.js environments. + */ +export class StdioServerTransport { + constructor(_stdin = process.stdin, _stdout = process.stdout) { + this._stdin = _stdin; + this._stdout = _stdout; + this._readBuffer = new ReadBuffer(); + this._started = false; + // Arrow functions to bind `this` properly, while maintaining function identity. + this._ondata = (chunk) => { + this._readBuffer.append(chunk); + this.processReadBuffer(); + }; + this._onerror = (error) => { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }; + } + /** + * Starts listening for messages on stdin. + */ + async start() { + if (this._started) { + throw new Error('StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.'); + } + this._started = true; + this._stdin.on('data', this._ondata); + this._stdin.on('error', this._onerror); + } + processReadBuffer() { + var _a, _b; + while (true) { + try { + const message = this._readBuffer.readMessage(); + if (message === null) { + break; + } + (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message); + } + catch (error) { + (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); + } + } + } + async close() { + var _a; + // Remove our event listeners first + this._stdin.off('data', this._ondata); + this._stdin.off('error', this._onerror); + // Check if we were the only data listener + const remainingDataListeners = this._stdin.listenerCount('data'); + if (remainingDataListeners === 0) { + // Only pause stdin if we were the only listener + // This prevents interfering with other parts of the application that might be using stdin + this._stdin.pause(); + } + // Clear the buffer and notify closure + this._readBuffer.clear(); + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + } + send(message) { + return new Promise(resolve => { + const json = serializeMessage(message); + if (this._stdout.write(json)) { + resolve(); + } + else { + this._stdout.once('drain', resolve); + } + }); + } +} +//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/dist/esm/server/stdio.js.map b/dist/esm/server/stdio.js.map new file mode 100644 index 0000000000..f2d202de70 --- /dev/null +++ b/dist/esm/server/stdio.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/server/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,cAAc,CAAC;AAEnC,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAIlE;;;;GAIG;AACH,MAAM,OAAO,oBAAoB;IAI7B,YACY,SAAmB,OAAO,CAAC,KAAK,EAChC,UAAoB,OAAO,CAAC,MAAM;QADlC,WAAM,GAAN,MAAM,CAA0B;QAChC,YAAO,GAAP,OAAO,CAA2B;QALtC,gBAAW,GAAe,IAAI,UAAU,EAAE,CAAC;QAC3C,aAAQ,GAAG,KAAK,CAAC;QAWzB,gFAAgF;QAChF,YAAO,GAAG,CAAC,KAAa,EAAE,EAAE;YACxB,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC/B,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAC7B,CAAC,CAAC;Q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B,gDAAgD;YAChD,0FAA0F;YAC1F,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QACxB,CAAC;QAED,sCAAsC;QACtC,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;QACzB,MAAA,IAAI,CAAC,OAAO,oDAAI,CAAC;IACrB,CAAC;IAED,IAAI,CAAC,OAAuB;QACxB,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE;YACzB,MAAM,IAAI,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;YACvC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC3B,OAAO,EAAE,CAAC;YACd,CAAC;iBAAM,CAAC;gBACJ,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/server/streamableHttp.d.ts b/dist/esm/server/streamableHttp.d.ts new file mode 100644 index 0000000000..cdad6d6593 --- /dev/null +++ b/dist/esm/server/streamableHttp.d.ts @@ -0,0 +1,185 @@ +import { IncomingMessage, ServerResponse } from 'node:http'; +import { Transport } from '../shared/transport.js'; +import { MessageExtraInfo, JSONRPCMessage, RequestId } from '../types.js'; +import { AuthInfo } from './auth/types.js'; +export type StreamId = string; +export type EventId = string; +/** + * Interface for resumability support via event storage + */ +export interface EventStore { + /** + * Stores an event for later retrieval + * @param streamId ID of the stream the event belongs to + * @param message The JSON-RPC message to store + * @returns The generated event ID for the stored event + */ + storeEvent(streamId: StreamId, message: JSONRPCMessage): Promise; + replayEventsAfter(lastEventId: EventId, { send }: { + send: (eventId: EventId, message: JSONRPCMessage) => Promise; + }): Promise; +} +/** + * Configuration options for StreamableHTTPServerTransport + */ +export interface StreamableHTTPServerTransportOptions { + /** + * Function that generates a session ID for the transport. + * The session ID SHOULD be globally unique and cryptographically secure (e.g., a securely generated UUID, a JWT, or a cryptographic hash) + * + * Return undefined to disable session management. + */ + sessionIdGenerator: (() => string) | undefined; + /** + * A callback for session initialization events + * This is called when the server initializes a new session. + * Useful in cases when you need to register multiple mcp sessions + * and need to keep track of them. + * @param sessionId The generated session ID + */ + onsessioninitialized?: (sessionId: string) => void | Promise; + /** + * A callback for session close events + * This is called when the server closes a session due to a DELETE request. + * Useful in cases when you need to clean up resources associated with the session. + * Note that this is different from the transport closing, if you are handling + * HTTP requests from multiple nodes you might want to close each + * StreamableHTTPServerTransport after a request is completed while still keeping the + * session open/running. + * @param sessionId The session ID that was closed + */ + onsessionclosed?: (sessionId: string) => void | Promise; + /** + * If true, the server will return JSON responses instead of starting an SSE stream. + * This can be useful for simple request/response scenarios without streaming. + * Default is false (SSE streams are preferred). + */ + enableJsonResponse?: boolean; + /** + * Event store for resumability support + * If provided, resumability will be enabled, allowing clients to reconnect and resume messages + */ + eventStore?: EventStore; + /** + * List of allowed host header values for DNS rebinding protection. + * If not specified, host validation is disabled. + */ + allowedHosts?: string[]; + /** + * List of allowed origin header values for DNS rebinding protection. + * If not specified, origin validation is disabled. + */ + allowedOrigins?: string[]; + /** + * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). + * Default is false for backwards compatibility. + */ + enableDnsRebindingProtection?: boolean; +} +/** + * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It supports both SSE streaming and direct HTTP responses. + * + * Usage example: + * + * ```typescript + * // Stateful mode - server sets the session ID + * const statefulTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: () => randomUUID(), + * }); + * + * // Stateless mode - explicitly set session ID to undefined + * const statelessTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: undefined, + * }); + * + * // Using with pre-parsed request body + * app.post('/mcp', (req, res) => { + * transport.handleRequest(req, res, req.body); + * }); + * ``` + * + * In stateful mode: + * - Session ID is generated and included in response headers + * - Session ID is always included in initialization responses + * - Requests with invalid session IDs are rejected with 404 Not Found + * - Non-initialization requests without a session ID are rejected with 400 Bad Request + * - State is maintained in-memory (connections, message history) + * + * In stateless mode: + * - No Session ID is included in any responses + * - No session validation is performed + */ +export declare class StreamableHTTPServerTransport implements Transport { + private sessionIdGenerator; + private _started; + private _streamMapping; + private _requestToStreamMapping; + private _requestResponseMap; + private _initialized; + private _enableJsonResponse; + private _standaloneSseStreamId; + private _eventStore?; + private _onsessioninitialized?; + private _onsessionclosed?; + private _allowedHosts?; + private _allowedOrigins?; + private _enableDnsRebindingProtection; + sessionId?: string; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; + constructor(options: StreamableHTTPServerTransportOptions); + /** + * Starts the transport. This is required by the Transport interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + start(): Promise; + /** + * Validates request headers for DNS rebinding protection. + * @returns Error message if validation fails, undefined if validation passes. + */ + private validateRequestHeaders; + /** + * Handles an incoming HTTP request, whether GET or POST + */ + handleRequest(req: IncomingMessage & { + auth?: AuthInfo; + }, res: ServerResponse, parsedBody?: unknown): Promise; + /** + * Handles GET requests for SSE stream + */ + private handleGetRequest; + /** + * Replays events that would have been sent after the specified event ID + * Only used when resumability is enabled + */ + private replayEvents; + /** + * Writes an event to the SSE stream with proper formatting + */ + private writeSSEEvent; + /** + * Handles unsupported requests (PUT, PATCH, etc.) + */ + private handleUnsupportedRequest; + /** + * Handles POST requests containing JSON-RPC messages + */ + private handlePostRequest; + /** + * Handles DELETE requests to terminate sessions + */ + private handleDeleteRequest; + /** + * Validates session ID for non-initialization requests + * Returns true if the session is valid, false otherwise + */ + private validateSession; + private validateProtocolVersion; + close(): Promise; + send(message: JSONRPCMessage, options?: { + relatedRequestId?: RequestId; + }): Promise; +} +//# sourceMappingURL=streamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/streamableHttp.d.ts.map b/dist/esm/server/streamableHttp.d.ts.map new file mode 100644 index 0000000000..b0b33e921d --- /dev/null +++ b/dist/esm/server/streamableHttp.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.d.ts","sourceRoot":"","sources":["../../../src/server/streamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EACH,gBAAgB,EAMhB,cAAc,EAEd,SAAS,EAGZ,MAAM,aAAa,CAAC;AAIrB,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAI3C,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAC;AAC9B,MAAM,MAAM,OAAO,GAAG,MAAM,CAAC;AAE7B;;GAEG;AACH,MAAM,WAAW,UAAU;IACvB;;;;;OAKG;IACH,UAAU,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAE1E,iBAAiB,CACb,WAAW,EAAE,OAAO,EACpB,EACI,IAAI,EACP,EAAE;QACC,IAAI,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;KACtE,GACF,OAAO,CAAC,QAAQ,CAAC,CAAC;CACxB;AAED;;GAEG;AACH,MAAM,WAAW,oCAAoC;IACjD;;;;;OAKG;IACH,kBAAkB,EAAE,CAAC,MAAM,MAAM,CAAC,GAAG,SAAS,CAAC;IAE/C;;;;;;OAMG;IACH,oBAAoB,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEnE;;;;;;;;;OASG;IACH,eAAe,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAE9D;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAE7B;;;O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QAAQ,CAAA;KAAE,EAAE,GAAG,EAAE,cAAc,EAAE,UAAU,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IA6BzH;;OAEG;YACW,gBAAgB;IAiF9B;;;OAGG;YACW,YAAY;IAmC1B;;OAEG;IACH,OAAO,CAAC,aAAa;IAWrB;;OAEG;YACW,wBAAwB;IAetC;;OAEG;YACW,iBAAiB;IAuL/B;;OAEG;YACW,mBAAmB;IAYjC;;;OAGG;IACH,OAAO,CAAC,eAAe;IAkEvB,OAAO,CAAC,uBAAuB;IAsBzB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAYtB,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,SAAS,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CA+FjG"} \ No newline at end of file diff --git a/dist/esm/server/streamableHttp.js b/dist/esm/server/streamableHttp.js new file mode 100644 index 0000000000..c528954670 --- /dev/null +++ b/dist/esm/server/streamableHttp.js @@ -0,0 +1,624 @@ +import { isInitializeRequest, isJSONRPCError, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessageSchema, SUPPORTED_PROTOCOL_VERSIONS, DEFAULT_NEGOTIATED_PROTOCOL_VERSION } from '../types.js'; +import getRawBody from 'raw-body'; +import contentType from 'content-type'; +import { randomUUID } from 'node:crypto'; +const MAXIMUM_MESSAGE_SIZE = '4mb'; +/** + * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It supports both SSE streaming and direct HTTP responses. + * + * Usage example: + * + * ```typescript + * // Stateful mode - server sets the session ID + * const statefulTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: () => randomUUID(), + * }); + * + * // Stateless mode - explicitly set session ID to undefined + * const statelessTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: undefined, + * }); + * + * // Using with pre-parsed request body + * app.post('/mcp', (req, res) => { + * transport.handleRequest(req, res, req.body); + * }); + * ``` + * + * In stateful mode: + * - Session ID is generated and included in response headers + * - Session ID is always included in initialization responses + * - Requests with invalid session IDs are rejected with 404 Not Found + * - Non-initialization requests without a session ID are rejected with 400 Bad Request + * - State is maintained in-memory (connections, message history) + * + * In stateless mode: + * - No Session ID is included in any responses + * - No session validation is performed + */ +export class StreamableHTTPServerTransport { + constructor(options) { + var _a, _b; + this._started = false; + this._streamMapping = new Map(); + this._requestToStreamMapping = new Map(); + this._requestResponseMap = new Map(); + this._initialized = false; + this._enableJsonResponse = false; + this._standaloneSseStreamId = '_GET_stream'; + this.sessionIdGenerator = options.sessionIdGenerator; + this._enableJsonResponse = (_a = options.enableJsonResponse) !== null && _a !== void 0 ? _a : false; + this._eventStore = options.eventStore; + this._onsessioninitialized = options.onsessioninitialized; + this._onsessionclosed = options.onsessionclosed; + this._allowedHosts = options.allowedHosts; + this._allowedOrigins = options.allowedOrigins; + this._enableDnsRebindingProtection = (_b = options.enableDnsRebindingProtection) !== null && _b !== void 0 ? _b : false; + } + /** + * Starts the transport. This is required by the Transport interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + async start() { + if (this._started) { + throw new Error('Transport already started'); + } + this._started = true; + } + /** + * Validates request headers for DNS rebinding protection. + * @returns Error message if validation fails, undefined if validation passes. + */ + validateRequestHeaders(req) { + // Skip validation if protection is not enabled + if (!this._enableDnsRebindingProtection) { + return undefined; + } + // Validate Host header if allowedHosts is configured + if (this._allowedHosts && this._allowedHosts.length > 0) { + const hostHeader = req.headers.host; + if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { + return `Invalid Host header: ${hostHeader}`; + } + } + // Validate Origin header if allowedOrigins is configured + if (this._allowedOrigins && this._allowedOrigins.length > 0) { + const originHeader = req.headers.origin; + if (!originHeader || !this._allowedOrigins.includes(originHeader)) { + return `Invalid Origin header: ${originHeader}`; + } + } + return undefined; + } + /** + * Handles an incoming HTTP request, whether GET or POST + */ + async handleRequest(req, res, parsedBody) { + var _a; + // Validate request headers for DNS rebinding protection + const validationError = this.validateRequestHeaders(req); + if (validationError) { + res.writeHead(403).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: validationError + }, + id: null + })); + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(validationError)); + return; + } + if (req.method === 'POST') { + await this.handlePostRequest(req, res, parsedBody); + } + else if (req.method === 'GET') { + await this.handleGetRequest(req, res); + } + else if (req.method === 'DELETE') { + await this.handleDeleteRequest(req, res); + } + else { + await this.handleUnsupportedRequest(res); + } + } + /** + * Handles GET requests for SSE stream + */ + async handleGetRequest(req, res) { + // The client MUST include an Accept header, listing text/event-stream as a supported content type. + const acceptHeader = req.headers.accept; + if (!(acceptHeader === null || acceptHeader === void 0 ? void 0 : acceptHeader.includes('text/event-stream'))) { + res.writeHead(406).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Not Acceptable: Client must accept text/event-stream' + }, + id: null + })); + return; + } + // If an Mcp-Session-Id is returned by the server during initialization, + // clients using the Streamable HTTP transport MUST include it + // in the Mcp-Session-Id header on all of their subsequent HTTP requests. + if (!this.validateSession(req, res)) { + return; + } + if (!this.validateProtocolVersion(req, res)) { + return; + } + // Handle resumability: check for Last-Event-ID header + if (this._eventStore) { + const lastEventId = req.headers['last-event-id']; + if (lastEventId) { + await this.replayEvents(lastEventId, res); + return; + } + } + // The server MUST either return Content-Type: text/event-stream in response to this HTTP GET, + // or else return HTTP 405 Method Not Allowed + const headers = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive' + }; + // After initialization, always include the session ID if we have one + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + // Check if there's already an active standalone SSE stream for this session + if (this._streamMapping.get(this._standaloneSseStreamId) !== undefined) { + // Only one GET SSE stream is allowed per session + res.writeHead(409).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Conflict: Only one SSE stream is allowed per session' + }, + id: null + })); + return; + } + // We need to send headers immediately as messages will arrive much later, + // otherwise the client will just wait for the first message + res.writeHead(200, headers).flushHeaders(); + // Assign the response to the standalone SSE stream + this._streamMapping.set(this._standaloneSseStreamId, res); + // Set up close handler for client disconnects + res.on('close', () => { + this._streamMapping.delete(this._standaloneSseStreamId); + }); + // Add error handler for standalone SSE stream + res.on('error', error => { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }); + } + /** + * Replays events that would have been sent after the specified event ID + * Only used when resumability is enabled + */ + async replayEvents(lastEventId, res) { + var _a, _b; + if (!this._eventStore) { + return; + } + try { + const headers = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive' + }; + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + res.writeHead(200, headers).flushHeaders(); + const streamId = await ((_a = this._eventStore) === null || _a === void 0 ? void 0 : _a.replayEventsAfter(lastEventId, { + send: async (eventId, message) => { + var _a; + if (!this.writeSSEEvent(res, message, eventId)) { + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error('Failed replay events')); + res.end(); + } + } + })); + this._streamMapping.set(streamId, res); + // Add error handler for replay stream + res.on('error', error => { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }); + } + catch (error) { + (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); + } + } + /** + * Writes an event to the SSE stream with proper formatting + */ + writeSSEEvent(res, message, eventId) { + let eventData = `event: message\n`; + // Include event ID if provided - this is important for resumability + if (eventId) { + eventData += `id: ${eventId}\n`; + } + eventData += `data: ${JSON.stringify(message)}\n\n`; + return res.write(eventData); + } + /** + * Handles unsupported requests (PUT, PATCH, etc.) + */ + async handleUnsupportedRequest(res) { + res.writeHead(405, { + Allow: 'GET, POST, DELETE' + }).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Method not allowed.' + }, + id: null + })); + } + /** + * Handles POST requests containing JSON-RPC messages + */ + async handlePostRequest(req, res, parsedBody) { + var _a, _b, _c, _d, _e; + try { + // Validate the Accept header + const acceptHeader = req.headers.accept; + // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types. + if (!(acceptHeader === null || acceptHeader === void 0 ? void 0 : acceptHeader.includes('application/json')) || !acceptHeader.includes('text/event-stream')) { + res.writeHead(406).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Not Acceptable: Client must accept both application/json and text/event-stream' + }, + id: null + })); + return; + } + const ct = req.headers['content-type']; + if (!ct || !ct.includes('application/json')) { + res.writeHead(415).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Unsupported Media Type: Content-Type must be application/json' + }, + id: null + })); + return; + } + const authInfo = req.auth; + const requestInfo = { headers: req.headers }; + let rawMessage; + if (parsedBody !== undefined) { + rawMessage = parsedBody; + } + else { + const parsedCt = contentType.parse(ct); + const body = await getRawBody(req, { + limit: MAXIMUM_MESSAGE_SIZE, + encoding: (_a = parsedCt.parameters.charset) !== null && _a !== void 0 ? _a : 'utf-8' + }); + rawMessage = JSON.parse(body.toString()); + } + let messages; + // handle batch and single messages + if (Array.isArray(rawMessage)) { + messages = rawMessage.map(msg => JSONRPCMessageSchema.parse(msg)); + } + else { + messages = [JSONRPCMessageSchema.parse(rawMessage)]; + } + // Check if this is an initialization request + // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/ + const isInitializationRequest = messages.some(isInitializeRequest); + if (isInitializationRequest) { + // If it's a server with session management and the session ID is already set we should reject the request + // to avoid re-initialization. + if (this._initialized && this.sessionId !== undefined) { + res.writeHead(400).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32600, + message: 'Invalid Request: Server already initialized' + }, + id: null + })); + return; + } + if (messages.length > 1) { + res.writeHead(400).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32600, + message: 'Invalid Request: Only one initialization request is allowed' + }, + id: null + })); + return; + } + this.sessionId = (_b = this.sessionIdGenerator) === null || _b === void 0 ? void 0 : _b.call(this); + this._initialized = true; + // If we have a session ID and an onsessioninitialized handler, call it immediately + // This is needed in cases where the server needs to keep track of multiple sessions + if (this.sessionId && this._onsessioninitialized) { + await Promise.resolve(this._onsessioninitialized(this.sessionId)); + } + } + if (!isInitializationRequest) { + // If an Mcp-Session-Id is returned by the server during initialization, + // clients using the Streamable HTTP transport MUST include it + // in the Mcp-Session-Id header on all of their subsequent HTTP requests. + if (!this.validateSession(req, res)) { + return; + } + // Mcp-Protocol-Version header is required for all requests after initialization. + if (!this.validateProtocolVersion(req, res)) { + return; + } + } + // check if it contains requests + const hasRequests = messages.some(isJSONRPCRequest); + if (!hasRequests) { + // if it only contains notifications or responses, return 202 + res.writeHead(202).end(); + // handle each message + for (const message of messages) { + (_c = this.onmessage) === null || _c === void 0 ? void 0 : _c.call(this, message, { authInfo, requestInfo }); + } + } + else if (hasRequests) { + // The default behavior is to use SSE streaming + // but in some cases server will return JSON responses + const streamId = randomUUID(); + if (!this._enableJsonResponse) { + const headers = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive' + }; + // After initialization, always include the session ID if we have one + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + res.writeHead(200, headers); + } + // Store the response for this request to send messages back through this connection + // We need to track by request ID to maintain the connection + for (const message of messages) { + if (isJSONRPCRequest(message)) { + this._streamMapping.set(streamId, res); + this._requestToStreamMapping.set(message.id, streamId); + } + } + // Set up close handler for client disconnects + res.on('close', () => { + this._streamMapping.delete(streamId); + }); + // Add error handler for stream write errors + res.on('error', error => { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + }); + // handle each message + for (const message of messages) { + (_d = this.onmessage) === null || _d === void 0 ? void 0 : _d.call(this, message, { authInfo, requestInfo }); + } + // The server SHOULD NOT close the SSE stream before sending all JSON-RPC responses + // This will be handled by the send() method when responses are ready + } + } + catch (error) { + // return JSON-RPC formatted error + res.writeHead(400).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32700, + message: 'Parse error', + data: String(error) + }, + id: null + })); + (_e = this.onerror) === null || _e === void 0 ? void 0 : _e.call(this, error); + } + } + /** + * Handles DELETE requests to terminate sessions + */ + async handleDeleteRequest(req, res) { + var _a; + if (!this.validateSession(req, res)) { + return; + } + if (!this.validateProtocolVersion(req, res)) { + return; + } + await Promise.resolve((_a = this._onsessionclosed) === null || _a === void 0 ? void 0 : _a.call(this, this.sessionId)); + await this.close(); + res.writeHead(200).end(); + } + /** + * Validates session ID for non-initialization requests + * Returns true if the session is valid, false otherwise + */ + validateSession(req, res) { + if (this.sessionIdGenerator === undefined) { + // If the sessionIdGenerator ID is not set, the session management is disabled + // and we don't need to validate the session ID + return true; + } + if (!this._initialized) { + // If the server has not been initialized yet, reject all requests + res.writeHead(400).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Server not initialized' + }, + id: null + })); + return false; + } + const sessionId = req.headers['mcp-session-id']; + if (!sessionId) { + // Non-initialization requests without a session ID should return 400 Bad Request + res.writeHead(400).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Mcp-Session-Id header is required' + }, + id: null + })); + return false; + } + else if (Array.isArray(sessionId)) { + res.writeHead(400).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Mcp-Session-Id header must be a single value' + }, + id: null + })); + return false; + } + else if (sessionId !== this.sessionId) { + // Reject requests with invalid session ID with 404 Not Found + res.writeHead(404).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32001, + message: 'Session not found' + }, + id: null + })); + return false; + } + return true; + } + validateProtocolVersion(req, res) { + var _a; + let protocolVersion = (_a = req.headers['mcp-protocol-version']) !== null && _a !== void 0 ? _a : DEFAULT_NEGOTIATED_PROTOCOL_VERSION; + if (Array.isArray(protocolVersion)) { + protocolVersion = protocolVersion[protocolVersion.length - 1]; + } + if (!SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) { + res.writeHead(400).end(JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: `Bad Request: Unsupported protocol version (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(', ')})` + }, + id: null + })); + return false; + } + return true; + } + async close() { + var _a; + // Close all SSE connections + this._streamMapping.forEach(response => { + response.end(); + }); + this._streamMapping.clear(); + // Clear any pending responses + this._requestResponseMap.clear(); + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + } + async send(message, options) { + let requestId = options === null || options === void 0 ? void 0 : options.relatedRequestId; + if (isJSONRPCResponse(message) || isJSONRPCError(message)) { + // If the message is a response, use the request ID from the message + requestId = message.id; + } + // Check if this message should be sent on the standalone SSE stream (no request ID) + // Ignore notifications from tools (which have relatedRequestId set) + // Those will be sent via dedicated response SSE streams + if (requestId === undefined) { + // For standalone SSE streams, we can only send requests and notifications + if (isJSONRPCResponse(message) || isJSONRPCError(message)) { + throw new Error('Cannot send a response on a standalone SSE stream unless resuming a previous client request'); + } + const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); + if (standaloneSse === undefined) { + // The spec says the server MAY send messages on the stream, so it's ok to discard if no stream + return; + } + // Generate and store event ID if event store is provided + let eventId; + if (this._eventStore) { + // Stores the event and gets the generated event ID + eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); + } + // Send the message to the standalone SSE stream + this.writeSSEEvent(standaloneSse, message, eventId); + return; + } + // Get the response for this request + const streamId = this._requestToStreamMapping.get(requestId); + const response = this._streamMapping.get(streamId); + if (!streamId) { + throw new Error(`No connection established for request ID: ${String(requestId)}`); + } + if (!this._enableJsonResponse) { + // For SSE responses, generate event ID if event store is provided + let eventId; + if (this._eventStore) { + eventId = await this._eventStore.storeEvent(streamId, message); + } + if (response) { + // Write the event to the response stream + this.writeSSEEvent(response, message, eventId); + } + } + if (isJSONRPCResponse(message) || isJSONRPCError(message)) { + this._requestResponseMap.set(requestId, message); + const relatedIds = Array.from(this._requestToStreamMapping.entries()) + .filter(([_, streamId]) => this._streamMapping.get(streamId) === response) + .map(([id]) => id); + // Check if we have responses for all requests using this connection + const allResponsesReady = relatedIds.every(id => this._requestResponseMap.has(id)); + if (allResponsesReady) { + if (!response) { + throw new Error(`No connection established for request ID: ${String(requestId)}`); + } + if (this._enableJsonResponse) { + // All responses ready, send as JSON + const headers = { + 'Content-Type': 'application/json' + }; + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + const responses = relatedIds.map(id => this._requestResponseMap.get(id)); + response.writeHead(200, headers); + if (responses.length === 1) { + response.end(JSON.stringify(responses[0])); + } + else { + response.end(JSON.stringify(responses)); + } + } + else { + // End the SSE stream + response.end(); + } + // Clean up + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + } + } + } +} +//# sourceMappingURL=streamableHttp.js.map \ No newline at end of file diff --git a/dist/esm/server/streamableHttp.js.map b/dist/esm/server/streamableHttp.js.map new file mode 100644 index 0000000000..34df3a2173 --- /dev/null +++ b/dist/esm/server/streamableHttp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"streamableHttp.js","sourceRoot":"","sources":["../../../src/server/streamableHttp.ts"],"names":[],"mappings":"AAEA,OAAO,EAGH,mBAAmB,EACnB,cAAc,EACd,gBAAgB,EAChB,iBAAiB,EAEjB,oBAAoB,EAEpB,2BAA2B,EAC3B,mCAAmC,EACtC,MAAM,aAAa,CAAC;AACrB,OAAO,UAAU,MAAM,UAAU,CAAC;AAClC,OAAO,WAAW,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,MAAM,oBAAoB,GAAG,KAAK,CAAC;AA4FnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAM,OAAO,6BAA6B;IAsBtC,YAAY,OAA6C;;QAnBjD,aAAQ,GAAY,KAAK,CAA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AM,SAAS,GAAG,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,mBAAmB,CAAC,GAAG,CAAC,EAAE,CAAE,CAAC,CAAC;oBAE1E,QAAQ,CAAC,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;oBACjC,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;wBACzB,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;oBAC/C,CAAC;yBAAM,CAAC;wBACJ,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC;oBAC5C,CAAC;gBACL,CAAC;qBAAM,CAAC;oBACJ,qBAAqB;oBACrB,QAAQ,CAAC,GAAG,EAAE,CAAC;gBACnB,CAAC;gBACD,WAAW;gBACX,KAAK,MAAM,EAAE,IAAI,UAAU,EAAE,CAAC;oBAC1B,IAAI,CAAC,mBAAmB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;oBACpC,IAAI,CAAC,uBAAuB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBAC5C,CAAC;YACL,CAAC;QACL,CAAC;IACL,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/server/zod-compat.d.ts b/dist/esm/server/zod-compat.d.ts new file mode 100644 index 0000000000..13fb9723c5 --- /dev/null +++ b/dist/esm/server/zod-compat.d.ts @@ -0,0 +1,82 @@ +import type * as z3 from 'zod/v3'; +import type * as z4 from 'zod/v4/core'; +export type AnySchema = z3.ZodTypeAny | z4.$ZodType; +export type AnyObjectSchema = z3.AnyZodObject | z4.$ZodObject | AnySchema; +export type ZodRawShapeCompat = Record; +export interface ZodV3Internal { + _def?: { + typeName?: string; + value?: unknown; + values?: unknown[]; + shape?: Record | (() => Record); + description?: string; + }; + shape?: Record | (() => Record); + value?: unknown; +} +export interface ZodV4Internal { + _zod?: { + def?: { + typeName?: string; + value?: unknown; + values?: unknown[]; + shape?: Record | (() => Record); + description?: string; + }; + }; + value?: unknown; +} +export type SchemaOutput = S extends z3.ZodTypeAny ? z3.infer : S extends z4.$ZodType ? z4.output : never; +export type SchemaInput = S extends z3.ZodTypeAny ? z3.input : S extends z4.$ZodType ? z4.input : never; +/** + * Infers the output type from a ZodRawShapeCompat (raw shape object). + * Maps over each key in the shape and infers the output type from each schema. + */ +export type ShapeOutput = { + [K in keyof Shape]: SchemaOutput; +}; +export declare function isZ4Schema(s: AnySchema): s is z4.$ZodType; +export declare function objectFromShape(shape: ZodRawShapeCompat): AnyObjectSchema; +export declare function safeParse(schema: S, data: unknown): { + success: true; + data: SchemaOutput; +} | { + success: false; + error: unknown; +}; +export declare function safeParseAsync(schema: S, data: unknown): Promise<{ + success: true; + data: SchemaOutput; +} | { + success: false; + error: unknown; +}>; +export declare function getObjectShape(schema: AnyObjectSchema | undefined): Record | undefined; +/** + * Normalizes a schema to an object schema. Handles both: + * - Already-constructed object schemas (v3 or v4) + * - Raw shapes that need to be wrapped into object schemas + */ +export declare function normalizeObjectSchema(schema: AnySchema | ZodRawShapeCompat | undefined): AnyObjectSchema | undefined; +/** + * Safely extracts an error message from a parse result error. + * Zod errors can have different structures, so we handle various cases. + */ +export declare function getParseErrorMessage(error: unknown): string; +/** + * Gets the description from a schema, if available. + * Works with both Zod v3 and v4. + */ +export declare function getSchemaDescription(schema: AnySchema): string | undefined; +/** + * Checks if a schema is optional. + * Works with both Zod v3 and v4. + */ +export declare function isSchemaOptional(schema: AnySchema): boolean; +/** + * Gets the literal value from a schema, if it's a literal schema. + * Works with both Zod v3 and v4. + * Returns undefined if the schema is not a literal or the value cannot be determined. + */ +export declare function getLiteralValue(schema: AnySchema): unknown; +//# sourceMappingURL=zod-compat.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/zod-compat.d.ts.map b/dist/esm/server/zod-compat.d.ts.map new file mode 100644 index 0000000000..608ca930c3 --- /dev/null +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EAAE,OAAO,GACd,OAAO,CAAC;IAAE,OAAO,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC,CAAA;CAAE,GAAG;IAAE,OAAO,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC,CASxF;AAGD,wBAAgB,cAAc,CAAC,MAAM,EAAE,eAAe,GAAG,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,SAAS,CAyBzG;AAGD;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,SAAS,GAAG,iBAAiB,GAAG,SAAS,GAAG,eAAe,GAAG,SAAS,CAiDpH;AAGD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAoB3D;AAGD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,SAAS,GAAG,MAAM,GAAG,SAAS,CAQ1E;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAW3D;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAwB1D"} \ No newline at end of file diff --git a/dist/esm/server/zod-compat.js b/dist/esm/server/zod-compat.js new file mode 100644 index 0000000000..0ff17cc10e --- /dev/null +++ b/dist/esm/server/zod-compat.js @@ -0,0 +1,217 @@ +// zod-compat.ts +// ---------------------------------------------------- +// Unified types + helpers to accept Zod v3 and v4 (Mini) +// ---------------------------------------------------- +import * as z3rt from 'zod/v3'; +import * as z4mini from 'zod/v4-mini'; +// --- Runtime detection --- +export function isZ4Schema(s) { + // Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3 + const schema = s; + return !!schema._zod; +} +// --- Schema construction --- +export function objectFromShape(shape) { + const values = Object.values(shape); + if (values.length === 0) + return z4mini.object({}); // default to v4 Mini + const allV4 = values.every(isZ4Schema); + const allV3 = values.every(s => !isZ4Schema(s)); + if (allV4) + return z4mini.object(shape); + if (allV3) + return z3rt.object(shape); + throw new Error('Mixed Zod versions detected in object shape.'); +} +// --- Unified parsing --- +export function safeParse(schema, data) { + if (isZ4Schema(schema)) { + // Mini exposes top-level safeParse + const result = z4mini.safeParse(schema, data); + return result; + } + const v3Schema = schema; + const result = v3Schema.safeParse(data); + return result; +} +export async function safeParseAsync(schema, data) { + if (isZ4Schema(schema)) { + // Mini exposes top-level safeParseAsync + const result = await z4mini.safeParseAsync(schema, data); + return result; + } + const v3Schema = schema; + const result = await v3Schema.safeParseAsync(data); + return result; +} +// --- Shape extraction --- +export function getObjectShape(schema) { + var _a, _b; + if (!schema) + return undefined; + // Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape` + let rawShape; + if (isZ4Schema(schema)) { + const v4Schema = schema; + rawShape = (_b = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def) === null || _b === void 0 ? void 0 : _b.shape; + } + else { + const v3Schema = schema; + rawShape = v3Schema.shape; + } + if (!rawShape) + return undefined; + if (typeof rawShape === 'function') { + try { + return rawShape(); + } + catch (_c) { + return undefined; + } + } + return rawShape; +} +// --- Schema normalization --- +/** + * Normalizes a schema to an object schema. Handles both: + * - Already-constructed object schemas (v3 or v4) + * - Raw shapes that need to be wrapped into object schemas + */ +export function normalizeObjectSchema(schema) { + var _a; + if (!schema) + return undefined; + // First check if it's a raw shape (Record) + // Raw shapes don't have _def or _zod properties and aren't schemas themselves + if (typeof schema === 'object') { + // Check if it's actually a ZodRawShapeCompat (not a schema instance) + // by checking if it lacks schema-like internal properties + const asV3 = schema; + const asV4 = schema; + // If it's not a schema instance (no _def or _zod), it might be a raw shape + if (!asV3._def && !asV4._zod) { + // Check if all values are schemas (heuristic to confirm it's a raw shape) + const values = Object.values(schema); + if (values.length > 0 && + values.every(v => typeof v === 'object' && + v !== null && + (v._def !== undefined || + v._zod !== undefined || + typeof v.parse === 'function'))) { + return objectFromShape(schema); + } + } + } + // If we get here, it should be an AnySchema (not a raw shape) + // Check if it's already an object schema + if (isZ4Schema(schema)) { + // Check if it's a v4 object + const v4Schema = schema; + const def = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def; + if (def && (def.typeName === 'object' || def.shape !== undefined)) { + return schema; + } + } + else { + // Check if it's a v3 object + const v3Schema = schema; + if (v3Schema.shape !== undefined) { + return schema; + } + } + return undefined; +} +// --- Error message extraction --- +/** + * Safely extracts an error message from a parse result error. + * Zod errors can have different structures, so we handle various cases. + */ +export function getParseErrorMessage(error) { + if (error && typeof error === 'object') { + // Try common error structures + if ('message' in error && typeof error.message === 'string') { + return error.message; + } + if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) { + const firstIssue = error.issues[0]; + if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) { + return String(firstIssue.message); + } + } + // Fallback: try to stringify the error + try { + return JSON.stringify(error); + } + catch (_a) { + return String(error); + } + } + return String(error); +} +// --- Schema metadata access --- +/** + * Gets the description from a schema, if available. + * Works with both Zod v3 and v4. + */ +export function getSchemaDescription(schema) { + var _a, _b, _c, _d; + if (isZ4Schema(schema)) { + const v4Schema = schema; + return (_b = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def) === null || _b === void 0 ? void 0 : _b.description; + } + const v3Schema = schema; + // v3 may have description on the schema itself or in _def + return (_c = schema.description) !== null && _c !== void 0 ? _c : (_d = v3Schema._def) === null || _d === void 0 ? void 0 : _d.description; +} +/** + * Checks if a schema is optional. + * Works with both Zod v3 and v4. + */ +export function isSchemaOptional(schema) { + var _a, _b, _c; + if (isZ4Schema(schema)) { + const v4Schema = schema; + return ((_b = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def) === null || _b === void 0 ? void 0 : _b.typeName) === 'ZodOptional'; + } + const v3Schema = schema; + // v3 has isOptional() method + if (typeof schema.isOptional === 'function') { + return schema.isOptional(); + } + return ((_c = v3Schema._def) === null || _c === void 0 ? void 0 : _c.typeName) === 'ZodOptional'; +} +/** + * Gets the literal value from a schema, if it's a literal schema. + * Works with both Zod v3 and v4. + * Returns undefined if the schema is not a literal or the value cannot be determined. + */ +export function getLiteralValue(schema) { + var _a; + if (isZ4Schema(schema)) { + const v4Schema = schema; + const def = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def; + if (def) { + // Try various ways to get the literal value + if (def.value !== undefined) + return def.value; + if (Array.isArray(def.values) && def.values.length > 0) { + return def.values[0]; + } + } + } + const v3Schema = schema; + const def = v3Schema._def; + if (def) { + if (def.value !== undefined) + return def.value; + if (Array.isArray(def.values) && def.values.length > 0) { + return def.values[0]; + } + } + // Fallback: check for direct value property (some Zod versions) + const directValue = schema.value; + if (directValue !== undefined) + return directValue; + return undefined; +} +//# sourceMappingURL=zod-compat.js.map \ No newline at end of file diff --git a/dist/esm/server/zod-compat.js.map b/dist/esm/server/zod-compat.js.map new file mode 100644 index 0000000000..df880a39d4 --- /dev/null +++ b/dist/esm/server/zod-compat.js.map @@ -0,0 +1 @@ +{"version":3,"file":"zod-compat.js","sourceRoot":"","sources":["../../../src/server/zod-compat.ts"],"names":[],"mappings":"AAAA,gBAAgB;AAChB,uDAAuD;AACvD,yDAAyD;AACzD,uDAAuD;AAKvD,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAC;AAC/B,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AA+CtC,4BAA4B;AAC5B,MAAM,UAAU,UAAU,CAAC,CAAY;IACnC,6DAA6D;IAC7D,MAAM,MAAM,GAAG,CAA6B,CAAC;IAC7C,OAAO,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC;AACzB,CAAC;AAED,8BAA8B;AAC9B,MAAM,UAAU,eAAe,CAAC,KAAwB;IACpD,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACpC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE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;IAClD,OAAO,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/zod-json-schema-compat.d.ts b/dist/esm/server/zod-json-schema-compat.d.ts new file mode 100644 index 0000000000..3a04452b47 --- /dev/null +++ b/dist/esm/server/zod-json-schema-compat.d.ts @@ -0,0 +1,12 @@ +import { AnySchema, AnyObjectSchema } from './zod-compat.js'; +type JsonSchema = Record; +type CommonOpts = { + strictUnions?: boolean; + pipeStrategy?: 'input' | 'output'; + target?: 'jsonSchema7' | 'draft-7' | 'jsonSchema2019-09' | 'draft-2020-12'; +}; +export declare function toJsonSchemaCompat(schema: AnyObjectSchema, opts?: CommonOpts): JsonSchema; +export declare function getMethodLiteral(schema: AnyObjectSchema): string; +export declare function parseWithCompat(schema: AnySchema, data: unknown): unknown; +export {}; +//# sourceMappingURL=zod-json-schema-compat.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/zod-json-schema-compat.d.ts.map b/dist/esm/server/zod-json-schema-compat.d.ts.map new file mode 100644 index 0000000000..0b851bf50e --- /dev/null +++ b/dist/esm/server/zod-json-schema-compat.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"zod-json-schema-compat.d.ts","sourceRoot":"","sources":["../../../src/server/zod-json-schema-compat.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,SAAS,EAAE,eAAe,EAA0D,MAAM,iBAAiB,CAAC;AAGrH,KAAK,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAG1C,KAAK,UAAU,GAAG;IACd,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;IAClC,MAAM,CAAC,EAAE,aAAa,GAAG,SAAS,GAAG,mBAAmB,GAAG,eAAe,CAAC;CAC9E,CAAC;AASF,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,eAAe,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,UAAU,CAczF;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,eAAe,GAAG,MAAM,CAahE;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,GAAG,OAAO,CAMzE"} \ No newline at end of file diff --git a/dist/esm/server/zod-json-schema-compat.js b/dist/esm/server/zod-json-schema-compat.js new file mode 100644 index 0000000000..bd2a25f20a --- /dev/null +++ b/dist/esm/server/zod-json-schema-compat.js @@ -0,0 +1,52 @@ +// zod-json-schema-compat.ts +// ---------------------------------------------------- +// JSON Schema conversion for both Zod v3 and Zod v4 (Mini) +// v3 uses your vendored converter; v4 uses Mini's toJSONSchema +// ---------------------------------------------------- +import * as z4mini from 'zod/v4-mini'; +import { getObjectShape, safeParse, isZ4Schema, getLiteralValue } from './zod-compat.js'; +import { zodToJsonSchema } from 'zod-to-json-schema'; +function mapMiniTarget(t) { + if (!t) + return 'draft-7'; + if (t === 'jsonSchema7' || t === 'draft-7') + return 'draft-7'; + if (t === 'jsonSchema2019-09' || t === 'draft-2020-12') + return 'draft-2020-12'; + return 'draft-7'; // fallback +} +export function toJsonSchemaCompat(schema, opts) { + var _a, _b, _c; + if (isZ4Schema(schema)) { + // v4 branch — use Mini's built-in toJSONSchema + return z4mini.toJSONSchema(schema, { + target: mapMiniTarget(opts === null || opts === void 0 ? void 0 : opts.target), + io: (_a = opts === null || opts === void 0 ? void 0 : opts.pipeStrategy) !== null && _a !== void 0 ? _a : 'input' + }); + } + // v3 branch — use vendored converter + return zodToJsonSchema(schema, { + strictUnions: (_b = opts === null || opts === void 0 ? void 0 : opts.strictUnions) !== null && _b !== void 0 ? _b : true, + pipeStrategy: (_c = opts === null || opts === void 0 ? void 0 : opts.pipeStrategy) !== null && _c !== void 0 ? _c : 'input' + }); +} +export function getMethodLiteral(schema) { + const shape = getObjectShape(schema); + const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method; + if (!methodSchema) { + throw new Error('Schema is missing a method literal'); + } + const value = getLiteralValue(methodSchema); + if (typeof value !== 'string') { + throw new Error('Schema method literal must be a string'); + } + return value; +} +export function parseWithCompat(schema, data) { + const result = safeParse(schema, data); + if (!result.success) { + throw result.error; + } + return result.data; +} +//# sourceMappingURL=zod-json-schema-compat.js.map \ No newline at end of file diff --git a/dist/esm/server/zod-json-schema-compat.js.map b/dist/esm/server/zod-json-schema-compat.js.map new file mode 100644 index 0000000000..d6973cb1c9 --- /dev/null +++ b/dist/esm/server/zod-json-schema-compat.js.map @@ -0,0 +1 @@ +{"version":3,"file":"zod-json-schema-compat.js","sourceRoot":"","sources":["../../../src/server/zod-json-schema-compat.ts"],"names":[],"mappings":"AAAA,4BAA4B;AAC5B,uDAAuD;AACvD,2DAA2D;AAC3D,+DAA+D;AAC/D,uDAAuD;AAKvD,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AAEtC,OAAO,EAA8B,cAAc,EAAE,SAAS,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACrH,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAWrD,SAAS,aAAa,CAAC,CAAmC;IACtD,IAAI,CAAC,CAAC;QAAE,OAAO,SAAS,CAAC;IACzB,IAAI,CAAC,KAAK,aAAa,IAAI,CAAC,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC7D,IAAI,CAAC,KAAK,mBAAmB,IAAI,CAAC,KAAK,eAAe;QAAE,OAAO,eAAe,CAAC;IAC/E,OAAO,SAAS,CAAC,CAAC,WAAW;AACjC,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,MAAuB,EAAE,IAAiB;;IACzE,IAAI,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC;QACrB,+CAA+C;QAC/C,OAAO,MAAM,CAAC,YAAY,CAAC,MAAsB,EAAE;YAC/C,MAAM,EAAE,aAAa,CAAC,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,CAAC;YACnC,EAAE,EAAE,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,YAAY,mCAAI,OAAO;SACpC,CAAe,CAAC;IACrB,CAAC;IAED,qCAAqC;IACrC,OAAO,eAAe,CAAC,MAAuB,EAAE;QAC5C,YAAY,EAAE,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,YAAY,mCAAI,IAAI;QACxC,YAAY,EAAE,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,YAAY,mCAAI,OAAO;KAC9C,CAAe,CAAC;AACrB,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,MAAuB;IACpD,MAAM,KAAK,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC;IACrC,MAAM,YAAY,GAAG,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,MAA+B,CAAC;IAC5D,IAAI,CAAC,YAAY,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;IAC1D,CAAC;IAED,MAAM,KAAK,GAAG,eAAe,CAAC,YAAY,CAAC,CAAC;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;IAC9D,CAAC;IAED,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,MAAiB,EAAE,IAAa;IAC5D,MAAM,MAAM,GAAG,SAAS,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACvC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QAClB,MAAM,MAAM,CAAC,KAAK,CAAC;IACvB,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC;AACvB,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/auth-utils.d.ts b/dist/esm/shared/auth-utils.d.ts new file mode 100644 index 0000000000..c966e30e74 --- /dev/null +++ b/dist/esm/shared/auth-utils.d.ts @@ -0,0 +1,23 @@ +/** + * Utilities for handling OAuth resource URIs. + */ +/** + * Converts a server URL to a resource URL by removing the fragment. + * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". + * Keeps everything else unchanged (scheme, domain, port, path, query). + */ +export declare function resourceUrlFromServerUrl(url: URL | string): URL; +/** + * Checks if a requested resource URL matches a configured resource URL. + * A requested resource matches if it has the same scheme, domain, port, + * and its path starts with the configured resource's path. + * + * @param requestedResource The resource URL being requested + * @param configuredResource The resource URL that has been configured + * @returns true if the requested resource matches the configured resource, false otherwise + */ +export declare function checkResourceAllowed({ requestedResource, configuredResource }: { + requestedResource: URL | string; + configuredResource: URL | string; +}): boolean; +//# sourceMappingURL=auth-utils.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/auth-utils.d.ts.map b/dist/esm/shared/auth-utils.d.ts.map new file mode 100644 index 0000000000..30873de552 --- /dev/null +++ b/dist/esm/shared/auth-utils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auth-utils.d.ts","sourceRoot":"","sources":["../../../src/shared/auth-utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,GAAG,GAAG,CAI/D;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,EACjC,iBAAiB,EACjB,kBAAkB,EACrB,EAAE;IACC,iBAAiB,EAAE,GAAG,GAAG,MAAM,CAAC;IAChC,kBAAkB,EAAE,GAAG,GAAG,MAAM,CAAC;CACpC,GAAG,OAAO,CAwBV"} \ No newline at end of file diff --git a/dist/esm/shared/auth-utils.js b/dist/esm/shared/auth-utils.js new file mode 100644 index 0000000000..1883885e40 --- /dev/null +++ b/dist/esm/shared/auth-utils.js @@ -0,0 +1,44 @@ +/** + * Utilities for handling OAuth resource URIs. + */ +/** + * Converts a server URL to a resource URL by removing the fragment. + * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". + * Keeps everything else unchanged (scheme, domain, port, path, query). + */ +export function resourceUrlFromServerUrl(url) { + const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href); + resourceURL.hash = ''; // Remove fragment + return resourceURL; +} +/** + * Checks if a requested resource URL matches a configured resource URL. + * A requested resource matches if it has the same scheme, domain, port, + * and its path starts with the configured resource's path. + * + * @param requestedResource The resource URL being requested + * @param configuredResource The resource URL that has been configured + * @returns true if the requested resource matches the configured resource, false otherwise + */ +export function checkResourceAllowed({ requestedResource, configuredResource }) { + const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href); + const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href); + // Compare the origin (scheme, domain, and port) + if (requested.origin !== configured.origin) { + return false; + } + // Handle cases like requested=/foo and configured=/foo/ + if (requested.pathname.length < configured.pathname.length) { + return false; + } + // Check if the requested path starts with the configured path + // Ensure both paths end with / for proper comparison + // This ensures that if we have paths like "/api" and "/api/users", + // we properly detect that "/api/users" is a subpath of "/api" + // By adding a trailing slash if missing, we avoid false positives + // where paths like "/api123" would incorrectly match "/api" + const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/'; + const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/'; + return requestedPath.startsWith(configuredPath); +} +//# sourceMappingURL=auth-utils.js.map \ No newline at end of file diff --git a/dist/esm/shared/auth-utils.js.map b/dist/esm/shared/auth-utils.js.map new file mode 100644 index 0000000000..3ced5af407 --- /dev/null +++ b/dist/esm/shared/auth-utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth-utils.js","sourceRoot":"","sources":["../../../src/shared/auth-utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;GAIG;AACH,MAAM,UAAU,wBAAwB,CAAC,GAAiB;IACtD,MAAM,WAAW,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC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AAU,CAAC,cAAc,CAAC,CAAC;AACpD,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/auth.d.ts b/dist/esm/shared/auth.d.ts new file mode 100644 index 0000000000..c9e723a002 --- /dev/null +++ b/dist/esm/shared/auth.d.ts @@ -0,0 +1,240 @@ +import * as z from 'zod/v4'; +/** + * Reusable URL validation that disallows javascript: scheme + */ +export declare const SafeUrlSchema: z.ZodURL; +/** + * RFC 9728 OAuth Protected Resource Metadata + */ +export declare const OAuthProtectedResourceMetadataSchema: z.ZodObject<{ + resource: z.ZodString; + authorization_servers: z.ZodOptional>; + jwks_uri: z.ZodOptional; + scopes_supported: z.ZodOptional>; + bearer_methods_supported: z.ZodOptional>; + resource_signing_alg_values_supported: z.ZodOptional>; + resource_name: z.ZodOptional; + resource_documentation: z.ZodOptional; + resource_policy_uri: z.ZodOptional; + resource_tos_uri: z.ZodOptional; + tls_client_certificate_bound_access_tokens: z.ZodOptional; + authorization_details_types_supported: z.ZodOptional>; + dpop_signing_alg_values_supported: z.ZodOptional>; + dpop_bound_access_tokens_required: z.ZodOptional; +}, z.core.$loose>; +/** + * RFC 8414 OAuth 2.0 Authorization Server Metadata + */ +export declare const OAuthMetadataSchema: z.ZodObject<{ + issuer: z.ZodString; + authorization_endpoint: z.ZodURL; + token_endpoint: z.ZodURL; + registration_endpoint: z.ZodOptional; + scopes_supported: z.ZodOptional>; + response_types_supported: z.ZodArray; + response_modes_supported: z.ZodOptional>; + grant_types_supported: z.ZodOptional>; + token_endpoint_auth_methods_supported: z.ZodOptional>; + token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + service_documentation: z.ZodOptional; + revocation_endpoint: z.ZodOptional; + revocation_endpoint_auth_methods_supported: z.ZodOptional>; + revocation_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + introspection_endpoint: z.ZodOptional; + introspection_endpoint_auth_methods_supported: z.ZodOptional>; + introspection_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + code_challenge_methods_supported: z.ZodOptional>; + client_id_metadata_document_supported: z.ZodOptional; +}, z.core.$loose>; +/** + * OpenID Connect Discovery 1.0 Provider Metadata + * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata + */ +export declare const OpenIdProviderMetadataSchema: z.ZodObject<{ + issuer: z.ZodString; + authorization_endpoint: z.ZodURL; + token_endpoint: z.ZodURL; + userinfo_endpoint: z.ZodOptional; + jwks_uri: z.ZodURL; + registration_endpoint: z.ZodOptional; + scopes_supported: z.ZodOptional>; + response_types_supported: z.ZodArray; + response_modes_supported: z.ZodOptional>; + grant_types_supported: z.ZodOptional>; + acr_values_supported: z.ZodOptional>; + subject_types_supported: z.ZodArray; + id_token_signing_alg_values_supported: z.ZodArray; + id_token_encryption_alg_values_supported: z.ZodOptional>; + id_token_encryption_enc_values_supported: z.ZodOptional>; + userinfo_signing_alg_values_supported: z.ZodOptional>; + userinfo_encryption_alg_values_supported: z.ZodOptional>; + userinfo_encryption_enc_values_supported: z.ZodOptional>; + request_object_signing_alg_values_supported: z.ZodOptional>; + request_object_encryption_alg_values_supported: z.ZodOptional>; + request_object_encryption_enc_values_supported: z.ZodOptional>; + token_endpoint_auth_methods_supported: z.ZodOptional>; + token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + display_values_supported: z.ZodOptional>; + claim_types_supported: z.ZodOptional>; + claims_supported: z.ZodOptional>; + service_documentation: z.ZodOptional; + claims_locales_supported: z.ZodOptional>; + ui_locales_supported: z.ZodOptional>; + claims_parameter_supported: z.ZodOptional; + request_parameter_supported: z.ZodOptional; + request_uri_parameter_supported: z.ZodOptional; + require_request_uri_registration: z.ZodOptional; + op_policy_uri: z.ZodOptional; + op_tos_uri: z.ZodOptional; + client_id_metadata_document_supported: z.ZodOptional; +}, z.core.$loose>; +/** + * OpenID Connect Discovery metadata that may include OAuth 2.0 fields + * This schema represents the real-world scenario where OIDC providers + * return a mix of OpenID Connect and OAuth 2.0 metadata fields + */ +export declare const OpenIdProviderDiscoveryMetadataSchema: z.ZodObject<{ + code_challenge_methods_supported: z.ZodOptional>; + issuer: z.ZodString; + authorization_endpoint: z.ZodURL; + token_endpoint: z.ZodURL; + userinfo_endpoint: z.ZodOptional; + jwks_uri: z.ZodURL; + registration_endpoint: z.ZodOptional; + scopes_supported: z.ZodOptional>; + response_types_supported: z.ZodArray; + response_modes_supported: z.ZodOptional>; + grant_types_supported: z.ZodOptional>; + acr_values_supported: z.ZodOptional>; + subject_types_supported: z.ZodArray; + id_token_signing_alg_values_supported: z.ZodArray; + id_token_encryption_alg_values_supported: z.ZodOptional>; + id_token_encryption_enc_values_supported: z.ZodOptional>; + userinfo_signing_alg_values_supported: z.ZodOptional>; + userinfo_encryption_alg_values_supported: z.ZodOptional>; + userinfo_encryption_enc_values_supported: z.ZodOptional>; + request_object_signing_alg_values_supported: z.ZodOptional>; + request_object_encryption_alg_values_supported: z.ZodOptional>; + request_object_encryption_enc_values_supported: z.ZodOptional>; + token_endpoint_auth_methods_supported: z.ZodOptional>; + token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; + display_values_supported: z.ZodOptional>; + claim_types_supported: z.ZodOptional>; + claims_supported: z.ZodOptional>; + service_documentation: z.ZodOptional; + claims_locales_supported: z.ZodOptional>; + ui_locales_supported: z.ZodOptional>; + claims_parameter_supported: z.ZodOptional; + request_parameter_supported: z.ZodOptional; + request_uri_parameter_supported: z.ZodOptional; + require_request_uri_registration: z.ZodOptional; + op_policy_uri: z.ZodOptional; + op_tos_uri: z.ZodOptional; + client_id_metadata_document_supported: z.ZodOptional; +}, z.core.$strip>; +/** + * OAuth 2.1 token response + */ +export declare const OAuthTokensSchema: z.ZodObject<{ + access_token: z.ZodString; + id_token: z.ZodOptional; + token_type: z.ZodString; + expires_in: z.ZodOptional; + scope: z.ZodOptional; + refresh_token: z.ZodOptional; +}, z.core.$strip>; +/** + * OAuth 2.1 error response + */ +export declare const OAuthErrorResponseSchema: z.ZodObject<{ + error: z.ZodString; + error_description: z.ZodOptional; + error_uri: z.ZodOptional; +}, z.core.$strip>; +/** + * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri + */ +export declare const OptionalSafeUrlSchema: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata + */ +export declare const OAuthClientMetadataSchema: z.ZodObject<{ + redirect_uris: z.ZodArray; + token_endpoint_auth_method: z.ZodOptional; + grant_types: z.ZodOptional>; + response_types: z.ZodOptional>; + client_name: z.ZodOptional; + client_uri: z.ZodOptional; + logo_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + scope: z.ZodOptional; + contacts: z.ZodOptional>; + tos_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + policy_uri: z.ZodOptional; + jwks_uri: z.ZodOptional; + jwks: z.ZodOptional; + software_id: z.ZodOptional; + software_version: z.ZodOptional; + software_statement: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration client information + */ +export declare const OAuthClientInformationSchema: z.ZodObject<{ + client_id: z.ZodString; + client_secret: z.ZodOptional; + client_id_issued_at: z.ZodOptional; + client_secret_expires_at: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) + */ +export declare const OAuthClientInformationFullSchema: z.ZodObject<{ + redirect_uris: z.ZodArray; + token_endpoint_auth_method: z.ZodOptional; + grant_types: z.ZodOptional>; + response_types: z.ZodOptional>; + client_name: z.ZodOptional; + client_uri: z.ZodOptional; + logo_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + scope: z.ZodOptional; + contacts: z.ZodOptional>; + tos_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; + policy_uri: z.ZodOptional; + jwks_uri: z.ZodOptional; + jwks: z.ZodOptional; + software_id: z.ZodOptional; + software_version: z.ZodOptional; + software_statement: z.ZodOptional; + client_id: z.ZodString; + client_secret: z.ZodOptional; + client_id_issued_at: z.ZodOptional; + client_secret_expires_at: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration error response + */ +export declare const OAuthClientRegistrationErrorSchema: z.ZodObject<{ + error: z.ZodString; + error_description: z.ZodOptional; +}, z.core.$strip>; +/** + * RFC 7009 OAuth 2.0 Token Revocation request + */ +export declare const OAuthTokenRevocationRequestSchema: z.ZodObject<{ + token: z.ZodString; + token_type_hint: z.ZodOptional; +}, z.core.$strip>; +export type OAuthMetadata = z.infer; +export type OpenIdProviderMetadata = z.infer; +export type OpenIdProviderDiscoveryMetadata = z.infer; +export type OAuthTokens = z.infer; +export type OAuthErrorResponse = z.infer; +export type OAuthClientMetadata = z.infer; +export type OAuthClientInformation = z.infer; +export type OAuthClientInformationFull = z.infer; +export type OAuthClientInformationMixed = OAuthClientInformation | OAuthClientInformationFull; +export type OAuthClientRegistrationError = z.infer; +export type OAuthTokenRevocationRequest = z.infer; +export type OAuthProtectedResourceMetadata = z.infer; +export type AuthorizationServerMetadata = OAuthMetadata | OpenIdProviderDiscoveryMetadata; +//# sourceMappingURL=auth.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/auth.d.ts.map b/dist/esm/shared/auth.d.ts.map new file mode 100644 index 0000000000..031a88fb92 --- /dev/null +++ b/dist/esm/shared/auth.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/shared/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B;;GAEG;AACH,eAAO,MAAM,aAAa,UAmBrB,CAAC;AAEN;;GAEG;AACH,eAAO,MAAM,oCAAoC;;;;;;;;;;;;;;;iBAe/C,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;iBAoB9B,CAAC;AAEH;;;GAGG;AACH,e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4B,CAAC,CAAC;AAClF,MAAM,MAAM,0BAA0B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,gCAAgC,CAAC,CAAC;AAC1F,MAAM,MAAM,2BAA2B,GAAG,sBAAsB,GAAG,0BAA0B,CAAC;AAC9F,MAAM,MAAM,4BAA4B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kCAAkC,CAAC,CAAC;AAC9F,MAAM,MAAM,2BAA2B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iCAAiC,CAAC,CAAC;AAC5F,MAAM,MAAM,8BAA8B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oCAAoC,CAAC,CAAC;AAGlG,MAAM,MAAM,2BAA2B,GAAG,aAAa,GAAG,+BAA+B,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/auth.js b/dist/esm/shared/auth.js new file mode 100644 index 0000000000..1d54e5855c --- /dev/null +++ b/dist/esm/shared/auth.js @@ -0,0 +1,198 @@ +import * as z from 'zod/v4'; +/** + * Reusable URL validation that disallows javascript: scheme + */ +export const SafeUrlSchema = z + .url() + .superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: 'URL must be parseable', + fatal: true + }); + return z.NEVER; + } +}) + .refine(url => { + const u = new URL(url); + return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:'; +}, { message: 'URL cannot use javascript:, data:, or vbscript: scheme' }); +/** + * RFC 9728 OAuth Protected Resource Metadata + */ +export const OAuthProtectedResourceMetadataSchema = z.looseObject({ + resource: z.string().url(), + authorization_servers: z.array(SafeUrlSchema).optional(), + jwks_uri: z.string().url().optional(), + scopes_supported: z.array(z.string()).optional(), + bearer_methods_supported: z.array(z.string()).optional(), + resource_signing_alg_values_supported: z.array(z.string()).optional(), + resource_name: z.string().optional(), + resource_documentation: z.string().optional(), + resource_policy_uri: z.string().url().optional(), + resource_tos_uri: z.string().url().optional(), + tls_client_certificate_bound_access_tokens: z.boolean().optional(), + authorization_details_types_supported: z.array(z.string()).optional(), + dpop_signing_alg_values_supported: z.array(z.string()).optional(), + dpop_bound_access_tokens_required: z.boolean().optional() +}); +/** + * RFC 8414 OAuth 2.0 Authorization Server Metadata + */ +export const OAuthMetadataSchema = z.looseObject({ + issuer: z.string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: z.array(z.string()).optional(), + response_types_supported: z.array(z.string()), + response_modes_supported: z.array(z.string()).optional(), + grant_types_supported: z.array(z.string()).optional(), + token_endpoint_auth_methods_supported: z.array(z.string()).optional(), + token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + service_documentation: SafeUrlSchema.optional(), + revocation_endpoint: SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + introspection_endpoint: z.string().optional(), + introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + code_challenge_methods_supported: z.array(z.string()).optional(), + client_id_metadata_document_supported: z.boolean().optional() +}); +/** + * OpenID Connect Discovery 1.0 Provider Metadata + * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata + */ +export const OpenIdProviderMetadataSchema = z.looseObject({ + issuer: z.string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + userinfo_endpoint: SafeUrlSchema.optional(), + jwks_uri: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: z.array(z.string()).optional(), + response_types_supported: z.array(z.string()), + response_modes_supported: z.array(z.string()).optional(), + grant_types_supported: z.array(z.string()).optional(), + acr_values_supported: z.array(z.string()).optional(), + subject_types_supported: z.array(z.string()), + id_token_signing_alg_values_supported: z.array(z.string()), + id_token_encryption_alg_values_supported: z.array(z.string()).optional(), + id_token_encryption_enc_values_supported: z.array(z.string()).optional(), + userinfo_signing_alg_values_supported: z.array(z.string()).optional(), + userinfo_encryption_alg_values_supported: z.array(z.string()).optional(), + userinfo_encryption_enc_values_supported: z.array(z.string()).optional(), + request_object_signing_alg_values_supported: z.array(z.string()).optional(), + request_object_encryption_alg_values_supported: z.array(z.string()).optional(), + request_object_encryption_enc_values_supported: z.array(z.string()).optional(), + token_endpoint_auth_methods_supported: z.array(z.string()).optional(), + token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), + display_values_supported: z.array(z.string()).optional(), + claim_types_supported: z.array(z.string()).optional(), + claims_supported: z.array(z.string()).optional(), + service_documentation: z.string().optional(), + claims_locales_supported: z.array(z.string()).optional(), + ui_locales_supported: z.array(z.string()).optional(), + claims_parameter_supported: z.boolean().optional(), + request_parameter_supported: z.boolean().optional(), + request_uri_parameter_supported: z.boolean().optional(), + require_request_uri_registration: z.boolean().optional(), + op_policy_uri: SafeUrlSchema.optional(), + op_tos_uri: SafeUrlSchema.optional(), + client_id_metadata_document_supported: z.boolean().optional() +}); +/** + * OpenID Connect Discovery metadata that may include OAuth 2.0 fields + * This schema represents the real-world scenario where OIDC providers + * return a mix of OpenID Connect and OAuth 2.0 metadata fields + */ +export const OpenIdProviderDiscoveryMetadataSchema = z.object({ + ...OpenIdProviderMetadataSchema.shape, + ...OAuthMetadataSchema.pick({ + code_challenge_methods_supported: true + }).shape +}); +/** + * OAuth 2.1 token response + */ +export const OAuthTokensSchema = z + .object({ + access_token: z.string(), + id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect + token_type: z.string(), + expires_in: z.number().optional(), + scope: z.string().optional(), + refresh_token: z.string().optional() +}) + .strip(); +/** + * OAuth 2.1 error response + */ +export const OAuthErrorResponseSchema = z.object({ + error: z.string(), + error_description: z.string().optional(), + error_uri: z.string().optional() +}); +/** + * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri + */ +export const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined)); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata + */ +export const OAuthClientMetadataSchema = z + .object({ + redirect_uris: z.array(SafeUrlSchema), + token_endpoint_auth_method: z.string().optional(), + grant_types: z.array(z.string()).optional(), + response_types: z.array(z.string()).optional(), + client_name: z.string().optional(), + client_uri: SafeUrlSchema.optional(), + logo_uri: OptionalSafeUrlSchema, + scope: z.string().optional(), + contacts: z.array(z.string()).optional(), + tos_uri: OptionalSafeUrlSchema, + policy_uri: z.string().optional(), + jwks_uri: SafeUrlSchema.optional(), + jwks: z.any().optional(), + software_id: z.string().optional(), + software_version: z.string().optional(), + software_statement: z.string().optional() +}) + .strip(); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration client information + */ +export const OAuthClientInformationSchema = z + .object({ + client_id: z.string(), + client_secret: z.string().optional(), + client_id_issued_at: z.number().optional(), + client_secret_expires_at: z.number().optional() +}) + .strip(); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) + */ +export const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); +/** + * RFC 7591 OAuth 2.0 Dynamic Client Registration error response + */ +export const OAuthClientRegistrationErrorSchema = z + .object({ + error: z.string(), + error_description: z.string().optional() +}) + .strip(); +/** + * RFC 7009 OAuth 2.0 Token Revocation request + */ +export const OAuthTokenRevocationRequestSchema = z + .object({ + token: z.string(), + token_type_hint: z.string().optional() +}) + .strip(); +//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/dist/esm/shared/auth.js.map b/dist/esm/shared/auth.js.map new file mode 100644 index 0000000000..ee296c28b9 --- /dev/null +++ b/dist/esm/shared/auth.js.map @@ -0,0 +1 @@ +{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/shared/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B;;GAEG;AACH,MAAM,CAAC,MAAM,aAAa,GA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;CAClD,CAAC;KACD,KAAK,EAAE,CAAC;AAEb;;GAEG;AACH,MAAM,CAAC,MAAM,gCAAgC,GAAG,yBAAyB,CAAC,KAAK,CAAC,4BAA4B,CAAC,CAAC;AAE9G;;GAEG;AACH,MAAM,CAAC,MAAM,kCAAkC,GAAG,CAAC;KAC9C,MAAM,CAAC;IACJ,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE;IACjB,iBAAiB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CAC3C,CAAC;KACD,KAAK,EAAE,CAAC;AAEb;;GAEG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAG,CAAC;KAC7C,MAAM,CAAC;IACJ,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE;IACjB,eAAe,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACzC,CAAC;KACD,KAAK,EAAE,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/metadataUtils.d.ts b/dist/esm/shared/metadataUtils.d.ts new file mode 100644 index 0000000000..c0e738bab0 --- /dev/null +++ b/dist/esm/shared/metadataUtils.d.ts @@ -0,0 +1,16 @@ +import { BaseMetadata } from '../types.js'; +/** + * Utilities for working with BaseMetadata objects. + */ +/** + * Gets the display name for an object with BaseMetadata. + * For tools, the precedence is: title → annotations.title → name + * For other objects: title → name + * This implements the spec requirement: "if no title is provided, name should be used for display purposes" + */ +export declare function getDisplayName(metadata: BaseMetadata & { + annotations?: { + title?: string; + }; +}): string; +//# sourceMappingURL=metadataUtils.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/metadataUtils.d.ts.map b/dist/esm/shared/metadataUtils.d.ts.map new file mode 100644 index 0000000000..596805eb34 --- /dev/null +++ b/dist/esm/shared/metadataUtils.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"metadataUtils.d.ts","sourceRoot":"","sources":["../../../src/shared/metadataUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C;;GAEG;AAEH;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,YAAY,GAAG;IAAE,WAAW,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,GAAG,MAAM,CAapG"} \ No newline at end of file diff --git a/dist/esm/shared/metadataUtils.js b/dist/esm/shared/metadataUtils.js new file mode 100644 index 0000000000..61b37d9d8f --- /dev/null +++ b/dist/esm/shared/metadataUtils.js @@ -0,0 +1,23 @@ +/** + * Utilities for working with BaseMetadata objects. + */ +/** + * Gets the display name for an object with BaseMetadata. + * For tools, the precedence is: title → annotations.title → name + * For other objects: title → name + * This implements the spec requirement: "if no title is provided, name should be used for display purposes" + */ +export function getDisplayName(metadata) { + var _a; + // First check for title (not undefined and not empty string) + if (metadata.title !== undefined && metadata.title !== '') { + return metadata.title; + } + // Then check for annotations.title (only present in Tool objects) + if ((_a = metadata.annotations) === null || _a === void 0 ? void 0 : _a.title) { + return metadata.annotations.title; + } + // Finally fall back to name + return metadata.name; +} +//# sourceMappingURL=metadataUtils.js.map \ No newline at end of file diff --git a/dist/esm/shared/metadataUtils.js.map b/dist/esm/shared/metadataUtils.js.map new file mode 100644 index 0000000000..a206833d99 --- /dev/null +++ b/dist/esm/shared/metadataUtils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metadataUtils.js","sourceRoot":"","sources":["../../../src/shared/metadataUtils.ts"],"names":[],"mappings":"AAEA;;GAEG;AAEH;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,QAA6D;;IACxF,6DAA6D;IAC7D,IAAI,QAAQ,CAAC,KAAK,KAAK,SAAS,IAAI,QAAQ,CAAC,KAAK,KAAK,EAAE,EAAE,CAAC;QACxD,OAAO,QAAQ,CAAC,KAAK,CAAC;IAC1B,CAAC;IAED,kEAAkE;IAClE,IAAI,MAAA,QAAQ,CAAC,WAAW,0CAAE,KAAK,EAAE,CAAC;QAC9B,OAAO,QAAQ,CAAC,WAAW,CAAC,KAAK,CAAC;IACtC,CAAC;IAED,4BAA4B;IAC5B,OAAO,QAAQ,CAAC,IAAI,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/protocol.d.ts b/dist/esm/shared/protocol.d.ts new file mode 100644 index 0000000000..fb23686184 --- /dev/null +++ b/dist/esm/shared/protocol.d.ts @@ -0,0 +1,226 @@ +import { AnySchema, AnyObjectSchema, SchemaOutput } from '../server/zod-compat.js'; +import { ClientCapabilities, JSONRPCRequest, Notification, Progress, Request, RequestId, Result, ServerCapabilities, RequestMeta, RequestInfo } from '../types.js'; +import { Transport, TransportSendOptions } from './transport.js'; +import { AuthInfo } from '../server/auth/types.js'; +/** + * Callback for progress notifications. + */ +export type ProgressCallback = (progress: Progress) => void; +/** + * Additional initialization options. + */ +export type ProtocolOptions = { + /** + * Whether to restrict emitted requests to only those that the remote side has indicated that they can handle, through their advertised capabilities. + * + * Note that this DOES NOT affect checking of _local_ side capabilities, as it is considered a logic error to mis-specify those. + * + * Currently this defaults to false, for backwards compatibility with SDK versions that did not advertise capabilities correctly. In future, this will default to true. + */ + enforceStrictCapabilities?: boolean; + /** + * An array of notification method names that should be automatically debounced. + * Any notifications with a method in this list will be coalesced if they + * occur in the same tick of the event loop. + * e.g., ['notifications/tools/list_changed'] + */ + debouncedNotificationMethods?: string[]; +}; +/** + * The default request timeout, in miliseconds. + */ +export declare const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; +/** + * Options that can be given per request. + */ +export type RequestOptions = { + /** + * If set, requests progress notifications from the remote end (if supported). When progress notifications are received, this callback will be invoked. + */ + onprogress?: ProgressCallback; + /** + * Can be used to cancel an in-flight request. This will cause an AbortError to be raised from request(). + */ + signal?: AbortSignal; + /** + * A timeout (in milliseconds) for this request. If exceeded, an McpError with code `RequestTimeout` will be raised from request(). + * + * If not specified, `DEFAULT_REQUEST_TIMEOUT_MSEC` will be used as the timeout. + */ + timeout?: number; + /** + * If true, receiving a progress notification will reset the request timeout. + * This is useful for long-running operations that send periodic progress updates. + * Default: false + */ + resetTimeoutOnProgress?: boolean; + /** + * Maximum total time (in milliseconds) to wait for a response. + * If exceeded, an McpError with code `RequestTimeout` will be raised, regardless of progress notifications. + * If not specified, there is no maximum total timeout. + */ + maxTotalTimeout?: number; +} & TransportSendOptions; +/** + * Options that can be given per notification. + */ +export type NotificationOptions = { + /** + * May be used to indicate to the transport which incoming request to associate this outgoing notification with. + */ + relatedRequestId?: RequestId; +}; +/** + * Extra data given to request handlers. + */ +export type RequestHandlerExtra = { + /** + * An abort signal used to communicate if the request was cancelled from the sender's side. + */ + signal: AbortSignal; + /** + * Information about a validated access token, provided to request handlers. + */ + authInfo?: AuthInfo; + /** + * The session ID from the transport, if available. + */ + sessionId?: string; + /** + * Metadata from the original request. + */ + _meta?: RequestMeta; + /** + * The JSON-RPC ID of the request being handled. + * This can be useful for tracking or logging purposes. + */ + requestId: RequestId; + /** + * The original HTTP request. + */ + requestInfo?: RequestInfo; + /** + * Sends a notification that relates to the current request being handled. + * + * This is used by certain transports to correctly associate related messages. + */ + sendNotification: (notification: SendNotificationT) => Promise; + /** + * Sends a request that relates to the current request being handled. + * + * This is used by certain transports to correctly associate related messages. + */ + sendRequest: (request: SendRequestT, resultSchema: U, options?: RequestOptions) => Promise>; +}; +/** + * Implements MCP protocol framing on top of a pluggable transport, including + * features like request/response linking, notifications, and progress. + */ +export declare abstract class Protocol { + private _options?; + private _transport?; + private _requestMessageId; + private _requestHandlers; + private _requestHandlerAbortControllers; + private _notificationHandlers; + private _responseHandlers; + private _progressHandlers; + private _timeoutInfo; + private _pendingDebouncedNotifications; + /** + * Callback for when the connection is closed for any reason. + * + * This is invoked when close() is called as well. + */ + onclose?: () => void; + /** + * Callback for when an error occurs. + * + * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. + */ + onerror?: (error: Error) => void; + /** + * A handler to invoke for any request types that do not have their own handler installed. + */ + fallbackRequestHandler?: (request: JSONRPCRequest, extra: RequestHandlerExtra) => Promise; + /** + * A handler to invoke for any notification types that do not have their own handler installed. + */ + fallbackNotificationHandler?: (notification: Notification) => Promise; + constructor(_options?: ProtocolOptions | undefined); + private _setupTimeout; + private _resetTimeout; + private _cleanupTimeout; + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + connect(transport: Transport): Promise; + private _onclose; + private _onerror; + private _onnotification; + private _onrequest; + private _onprogress; + private _onresponse; + get transport(): Transport | undefined; + /** + * Closes the connection. + */ + close(): Promise; + /** + * A method to check if a capability is supported by the remote side, for the given method to be called. + * + * This should be implemented by subclasses. + */ + protected abstract assertCapabilityForMethod(method: SendRequestT['method']): void; + /** + * A method to check if a notification is supported by the local side, for the given method to be sent. + * + * This should be implemented by subclasses. + */ + protected abstract assertNotificationCapability(method: SendNotificationT['method']): void; + /** + * A method to check if a request handler is supported by the local side, for the given method to be handled. + * + * This should be implemented by subclasses. + */ + protected abstract assertRequestHandlerCapability(method: string): void; + /** + * Sends a request and wait for a response. + * + * Do not use this method to emit notifications! Use notification() instead. + */ + request(request: SendRequestT, resultSchema: T, options?: RequestOptions): Promise>; + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + notification(notification: SendNotificationT, options?: NotificationOptions): Promise; + /** + * Registers a handler to invoke when this protocol object receives a request with the given method. + * + * Note that this will replace any previous request handler for the same method. + */ + setRequestHandler(requestSchema: T, handler: (request: SchemaOutput, extra: RequestHandlerExtra) => SendResultT | Promise): void; + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method: string): void; + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method: string): void; + /** + * Registers a handler to invoke when this protocol object receives a notification with the given method. + * + * Note that this will replace any previous notification handler for the same method. + */ + setNotificationHandler(notificationSchema: T, handler: (notification: SchemaOutput) => void | Promise): void; + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method: string): void; +} +export declare function mergeCapabilities(base: ServerCapabilities, additional: Partial): ServerCapabilities; +export declare function mergeCapabilities(base: ClientCapabilities, additional: Partial): ClientCapabilities; +//# sourceMappingURL=protocol.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/protocol.d.ts.map b/dist/esm/shared/protocol.d.ts.map new file mode 100644 index 0000000000..4aa2bd57cb --- /dev/null +++ b/dist/esm/shared/protocol.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../../../src/shared/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,YAAY,EAAa,MAAM,yBAAyB,CAAC;AAC9F,OAAO,EAEH,kBAAkB,EAQlB,cAAc,EAGd,YAAY,EAEZ,QAAQ,EAGR,OAAO,EACP,SAAS,EACT,MAAM,EACN,kBAAkB,EAClB,WAAW,EAEX,WAAW,EACd,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AAGnD;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,QAAQ,EAAE,QAAQ,KAAK,IAAI,CAAC;AAE5D;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG;IAC1B;;;;;;OAMG;IACH,yBAAyB,CAAC,EAAE,OAAO,CAAC;IACpC;;;;;OAKG;IACH,4BAA4B,CAAC,EAAE,MAAM,EAAE,CAAC;CAC3C,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,4BAA4B,QAAQ,CAAC;AAElD;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IACzB;;OAEG;IACH,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAE9B;;OAEG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;IAErB;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,C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,kBAAkB,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/protocol.js b/dist/esm/shared/protocol.js new file mode 100644 index 0000000000..504119c82c --- /dev/null +++ b/dist/esm/shared/protocol.js @@ -0,0 +1,437 @@ +import { safeParse } from '../server/zod-compat.js'; +import { CancelledNotificationSchema, ErrorCode, isJSONRPCError, isJSONRPCRequest, isJSONRPCResponse, isJSONRPCNotification, McpError, PingRequestSchema, ProgressNotificationSchema } from '../types.js'; +import { getMethodLiteral, parseWithCompat } from '../server/zod-json-schema-compat.js'; +/** + * The default request timeout, in miliseconds. + */ +export const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; +/** + * Implements MCP protocol framing on top of a pluggable transport, including + * features like request/response linking, notifications, and progress. + */ +export class Protocol { + constructor(_options) { + this._options = _options; + this._requestMessageId = 0; + this._requestHandlers = new Map(); + this._requestHandlerAbortControllers = new Map(); + this._notificationHandlers = new Map(); + this._responseHandlers = new Map(); + this._progressHandlers = new Map(); + this._timeoutInfo = new Map(); + this._pendingDebouncedNotifications = new Set(); + this.setNotificationHandler(CancelledNotificationSchema, notification => { + const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); + controller === null || controller === void 0 ? void 0 : controller.abort(notification.params.reason); + }); + this.setNotificationHandler(ProgressNotificationSchema, notification => { + this._onprogress(notification); + }); + this.setRequestHandler(PingRequestSchema, + // Automatic pong by default. + _request => ({})); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) + return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw McpError.fromError(ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; + } + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. + */ + async connect(transport) { + var _a, _b, _c; + this._transport = transport; + const _onclose = (_a = this.transport) === null || _a === void 0 ? void 0 : _a.onclose; + this._transport.onclose = () => { + _onclose === null || _onclose === void 0 ? void 0 : _onclose(); + this._onclose(); + }; + const _onerror = (_b = this.transport) === null || _b === void 0 ? void 0 : _b.onerror; + this._transport.onerror = (error) => { + _onerror === null || _onerror === void 0 ? void 0 : _onerror(error); + this._onerror(error); + }; + const _onmessage = (_c = this._transport) === null || _c === void 0 ? void 0 : _c.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage === null || _onmessage === void 0 ? void 0 : _onmessage(message, extra); + if (isJSONRPCResponse(message) || isJSONRPCError(message)) { + this._onresponse(message); + } + else if (isJSONRPCRequest(message)) { + this._onrequest(message, extra); + } + else if (isJSONRPCNotification(message)) { + this._onnotification(message); + } + else { + this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); + } + }; + await this._transport.start(); + } + _onclose() { + var _a; + const responseHandlers = this._responseHandlers; + this._responseHandlers = new Map(); + this._progressHandlers.clear(); + this._pendingDebouncedNotifications.clear(); + this._transport = undefined; + (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); + const error = McpError.fromError(ErrorCode.ConnectionClosed, 'Connection closed'); + for (const handler of responseHandlers.values()) { + handler(error); + } + } + _onerror(error) { + var _a; + (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); + } + _onnotification(notification) { + var _a; + const handler = (_a = this._notificationHandlers.get(notification.method)) !== null && _a !== void 0 ? _a : this.fallbackNotificationHandler; + // Ignore notifications not being subscribed to. + if (handler === undefined) { + return; + } + // Starting with Promise.resolve() puts any synchronous errors into the monad as well. + Promise.resolve() + .then(() => handler(notification)) + .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`))); + } + _onrequest(request, extra) { + var _a, _b; + const handler = (_a = this._requestHandlers.get(request.method)) !== null && _a !== void 0 ? _a : this.fallbackRequestHandler; + // Capture the current transport at request time to ensure responses go to the correct client + const capturedTransport = this._transport; + if (handler === undefined) { + capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({ + jsonrpc: '2.0', + id: request.id, + error: { + code: ErrorCode.MethodNotFound, + message: 'Method not found' + } + }).catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`))); + return; + } + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const fullExtra = { + signal: abortController.signal, + sessionId: capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId, + _meta: (_b = request.params) === null || _b === void 0 ? void 0 : _b._meta, + sendNotification: notification => this.notification(notification, { relatedRequestId: request.id }), + sendRequest: (r, resultSchema, options) => this.request(r, resultSchema, { ...options, relatedRequestId: request.id }), + authInfo: extra === null || extra === void 0 ? void 0 : extra.authInfo, + requestId: request.id, + requestInfo: extra === null || extra === void 0 ? void 0 : extra.requestInfo + }; + // Starting with Promise.resolve() puts any synchronous errors into the monad as well. + Promise.resolve() + .then(() => handler(request, fullExtra)) + .then(result => { + if (abortController.signal.aborted) { + return; + } + return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({ + result, + jsonrpc: '2.0', + id: request.id + }); + }, error => { + var _a; + if (abortController.signal.aborted) { + return; + } + return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({ + jsonrpc: '2.0', + id: request.id, + error: { + code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode.InternalError, + message: (_a = error.message) !== null && _a !== void 0 ? _a : 'Internal error', + ...(error['data'] !== undefined && { data: error['data'] }) + } + }); + }) + .catch(error => this._onerror(new Error(`Failed to send response: ${error}`))) + .finally(() => { + this._requestHandlerAbortControllers.delete(request.id); + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { + try { + this._resetTimeout(messageId); + } + catch (error) { + responseHandler(error); + return; + } + } + handler(params); + } + _onresponse(response) { + const messageId = Number(response.id); + const handler = this._responseHandlers.get(messageId); + if (handler === undefined) { + this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + if (isJSONRPCResponse(response)) { + handler(response); + } + else { + const error = McpError.fromError(response.error.code, response.error.message, response.error.data); + handler(error); + } + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + var _a; + await ((_a = this._transport) === null || _a === void 0 ? void 0 : _a.close()); + } + /** + * Sends a request and wait for a response. + * + * Do not use this method to emit notifications! Use notification() instead. + */ + request(request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken } = options !== null && options !== void 0 ? options : {}; + return new Promise((resolve, reject) => { + var _a, _b, _c, _d, _e, _f; + if (!this._transport) { + reject(new Error('Not connected')); + return; + } + if (((_a = this._options) === null || _a === void 0 ? void 0 : _a.enforceStrictCapabilities) === true) { + this.assertCapabilityForMethod(request.method); + } + (_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.throwIfAborted(); + const messageId = this._requestMessageId++; + const jsonrpcRequest = { + ...request, + jsonrpc: '2.0', + id: messageId + }; + if (options === null || options === void 0 ? void 0 : options.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...(((_c = request.params) === null || _c === void 0 ? void 0 : _c._meta) || {}), + progressToken: messageId + } + }; + } + const cancel = (reason) => { + var _a; + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + (_a = this._transport) === null || _a === void 0 ? void 0 : _a.send({ + jsonrpc: '2.0', + method: 'notifications/cancelled', + params: { + requestId: messageId, + reason: String(reason) + } + }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`))); + reject(reason); + }; + this._responseHandlers.set(messageId, response => { + var _a; + if ((_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.aborted) { + return; + } + if (response instanceof Error) { + return reject(response); + } + try { + const parseResult = safeParse(resultSchema, response.result); + if (!parseResult.success) { + // Type guard: if success is false, error is guaranteed to exist + reject(parseResult.error); + } + else { + resolve(parseResult.data); + } + } + catch (error) { + reject(error); + } + }); + (_d = options === null || options === void 0 ? void 0 : options.signal) === null || _d === void 0 ? void 0 : _d.addEventListener('abort', () => { + var _a; + cancel((_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.reason); + }); + const timeout = (_e = options === null || options === void 0 ? void 0 : options.timeout) !== null && _e !== void 0 ? _e : DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, 'Request timed out', { timeout })); + this._setupTimeout(messageId, timeout, options === null || options === void 0 ? void 0 : options.maxTotalTimeout, timeoutHandler, (_f = options === null || options === void 0 ? void 0 : options.resetTimeoutOnProgress) !== null && _f !== void 0 ? _f : false); + this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => { + this._cleanupTimeout(messageId); + reject(error); + }); + }); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + var _a, _b; + if (!this._transport) { + throw new Error('Not connected'); + } + this.assertNotificationCapability(notification.method); + const debouncedMethods = (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.debouncedNotificationMethods) !== null && _b !== void 0 ? _b : []; + // A notification can only be debounced if it's in the list AND it's "simple" + // (i.e., has no parameters and no related request ID that could be lost). + const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !(options === null || options === void 0 ? void 0 : options.relatedRequestId); + if (canDebounce) { + // If a notification of this type is already scheduled, do nothing. + if (this._pendingDebouncedNotifications.has(notification.method)) { + return; + } + // Mark this notification type as pending. + this._pendingDebouncedNotifications.add(notification.method); + // Schedule the actual send to happen in the next microtask. + // This allows all synchronous calls in the current event loop tick to be coalesced. + Promise.resolve().then(() => { + var _a; + // Un-mark the notification so the next one can be scheduled. + this._pendingDebouncedNotifications.delete(notification.method); + // SAFETY CHECK: If the connection was closed while this was pending, abort. + if (!this._transport) { + return; + } + const jsonrpcNotification = { + ...notification, + jsonrpc: '2.0' + }; + // Send the notification, but don't await it here to avoid blocking. + // Handle potential errors with a .catch(). + (_a = this._transport) === null || _a === void 0 ? void 0 : _a.send(jsonrpcNotification, options).catch(error => this._onerror(error)); + }); + // Return immediately. + return; + } + const jsonrpcNotification = { + ...notification, + jsonrpc: '2.0' + }; + await this._transport.send(jsonrpcNotification, options); + } + /** + * Registers a handler to invoke when this protocol object receives a request with the given method. + * + * Note that this will replace any previous request handler for the same method. + */ + setRequestHandler(requestSchema, handler) { + const method = getMethodLiteral(requestSchema); + this.assertRequestHandlerCapability(method); + this._requestHandlers.set(method, (request, extra) => { + const parsed = parseWithCompat(requestSchema, request); + return Promise.resolve(handler(parsed, extra)); + }); + } + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) { + throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + } + /** + * Registers a handler to invoke when this protocol object receives a notification with the given method. + * + * Note that this will replace any previous notification handler for the same method. + */ + setNotificationHandler(notificationSchema, handler) { + const method = getMethodLiteral(notificationSchema); + this._notificationHandlers.set(method, notification => { + const parsed = parseWithCompat(notificationSchema, notification); + return Promise.resolve(handler(parsed)); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } +} +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} +export function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === undefined) + continue; + const baseValue = result[k]; + if (isPlainObject(baseValue) && isPlainObject(addValue)) { + result[k] = { ...baseValue, ...addValue }; + } + else { + result[k] = addValue; + } + } + return result; +} +//# sourceMappingURL=protocol.js.map \ No newline at end of file diff --git a/dist/esm/shared/protocol.js.map b/dist/esm/shared/protocol.js.map new file mode 100644 index 0000000000..79583f349f --- /dev/null +++ b/dist/esm/shared/protocol.js.map @@ -0,0 +1 @@ +{"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../../src/shared/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4C,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAC9F,OAAO,EACH,2BAA2B,EAE3B,SAAS,EACT,cAAc,EACd,gBAAgB,EAChB,iBAAiB,EACjB,qBAAqB,EAKrB,QAAQ,EAER,iBAAiB,EAGjB,0BAA0B,EAQ7B,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AA4BxF;;GAEG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,KAAK,CAAC;AA8GlD;;;GAGG;AACH,MAAM,OAAgB,QAAQ;IAsC1B,YAAoB,QAA0B;QAA1B,aAAQ,GAAR,QAAQ,CAAkB;QApCtC,sBAAiB,GAAG,CAAC,CAAC;QACtB,qBAAg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C;QAC3B,MAAM,CAAC,GAAG,GAAc,CAAC;QACzB,MAAM,QAAQ,GAAG,UAAU,CAAC,CAAC,CAAC,CAAC;QAC/B,IAAI,QAAQ,KAAK,SAAS;YAAE,SAAS;QACrC,MAAM,SAAS,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;QAC5B,IAAI,aAAa,CAAC,SAAS,CAAC,IAAI,aAAa,CAAC,QAAQ,CAAC,EAAE,CAAC;YACtD,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,GAAI,SAAqC,EAAE,GAAI,QAAoC,EAAiB,CAAC;QACvH,CAAC;aAAM,CAAC;YACJ,MAAM,CAAC,CAAC,CAAC,GAAG,QAAuB,CAAC;QACxC,CAAC;IACL,CAAC;IACD,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/stdio.d.ts b/dist/esm/shared/stdio.d.ts new file mode 100644 index 0000000000..0830a48bc7 --- /dev/null +++ b/dist/esm/shared/stdio.d.ts @@ -0,0 +1,13 @@ +import { JSONRPCMessage } from '../types.js'; +/** + * Buffers a continuous stdio stream into discrete JSON-RPC messages. + */ +export declare class ReadBuffer { + private _buffer?; + append(chunk: Buffer): void; + readMessage(): JSONRPCMessage | null; + clear(): void; +} +export declare function deserializeMessage(line: string): JSONRPCMessage; +export declare function serializeMessage(message: JSONRPCMessage): string; +//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/stdio.d.ts.map b/dist/esm/shared/stdio.d.ts.map new file mode 100644 index 0000000000..8f97f2ab10 --- /dev/null +++ b/dist/esm/shared/stdio.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/shared/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AAEnE;;GAEG;AACH,qBAAa,UAAU;IACnB,OAAO,CAAC,OAAO,CAAC,CAAS;IAEzB,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAI3B,WAAW,IAAI,cAAc,GAAG,IAAI;IAepC,KAAK,IAAI,IAAI;CAGhB;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,CAE/D;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,GAAG,MAAM,CAEhE"} \ No newline at end of file diff --git a/dist/esm/shared/stdio.js b/dist/esm/shared/stdio.js new file mode 100644 index 0000000000..30f299f5a7 --- /dev/null +++ b/dist/esm/shared/stdio.js @@ -0,0 +1,31 @@ +import { JSONRPCMessageSchema } from '../types.js'; +/** + * Buffers a continuous stdio stream into discrete JSON-RPC messages. + */ +export class ReadBuffer { + append(chunk) { + this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; + } + readMessage() { + if (!this._buffer) { + return null; + } + const index = this._buffer.indexOf('\n'); + if (index === -1) { + return null; + } + const line = this._buffer.toString('utf8', 0, index).replace(/\r$/, ''); + this._buffer = this._buffer.subarray(index + 1); + return deserializeMessage(line); + } + clear() { + this._buffer = undefined; + } +} +export function deserializeMessage(line) { + return JSONRPCMessageSchema.parse(JSON.parse(line)); +} +export function serializeMessage(message) { + return JSON.stringify(message) + '\n'; +} +//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/dist/esm/shared/stdio.js.map b/dist/esm/shared/stdio.js.map new file mode 100644 index 0000000000..19fdf08d83 --- /dev/null +++ b/dist/esm/shared/stdio.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/shared/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnE;;GAEG;AACH,MAAM,OAAO,UAAU;IAGnB,MAAM,CAAC,KAAa;QAChB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAC/E,CAAC;IAED,WAAW;QACP,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAChB,OAAO,IAAI,CAAC;QAChB,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACzC,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE,CAAC;YACf,OAAO,IAAI,CAAC;QAChB,CAAC;QAED,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACxE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QAChD,OAAO,kBAAkB,CAAC,IAAI,CAAC,CAAC;IACpC,CAAC;IAED,KAAK;QACD,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;IAC7B,CAAC;CACJ;AAED,MAAM,UAAU,kBAAkB,CAAC,IAAY;IAC3C,OAAO,oBAAoB,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;AACxD,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,OAAuB;IACpD,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;AAC1C,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/toolNameValidation.d.ts b/dist/esm/shared/toolNameValidation.d.ts new file mode 100644 index 0000000000..3cf94bf78e --- /dev/null +++ b/dist/esm/shared/toolNameValidation.d.ts @@ -0,0 +1,31 @@ +/** + * Tool name validation utilities according to SEP: Specify Format for Tool Names + * + * Tool names SHOULD be between 1 and 128 characters in length (inclusive). + * Tool names are case-sensitive. + * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits + * (0-9), underscore (_), dash (-), and dot (.). + * Tool names SHOULD NOT contain spaces, commas, or other special characters. + */ +/** + * Validates a tool name according to the SEP specification + * @param name - The tool name to validate + * @returns An object containing validation result and any warnings + */ +export declare function validateToolName(name: string): { + isValid: boolean; + warnings: string[]; +}; +/** + * Issues warnings for non-conforming tool names + * @param name - The tool name that triggered the warnings + * @param warnings - Array of warning messages + */ +export declare function issueToolNameWarning(name: string, warnings: string[]): void; +/** + * Validates a tool name and issues warnings for non-conforming names + * @param name - The tool name to validate + * @returns true if the name is valid, false otherwise + */ +export declare function validateAndWarnToolName(name: string): boolean; +//# sourceMappingURL=toolNameValidation.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/toolNameValidation.d.ts.map b/dist/esm/shared/toolNameValidation.d.ts.map new file mode 100644 index 0000000000..d81f0156e6 --- /dev/null +++ b/dist/esm/shared/toolNameValidation.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"toolNameValidation.d.ts","sourceRoot":"","sources":["../../../src/shared/toolNameValidation.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAOH;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG;IAC5C,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,MAAM,EAAE,CAAC;CACtB,CA0DA;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,CAY3E;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAO7D"} \ No newline at end of file diff --git a/dist/esm/shared/toolNameValidation.js b/dist/esm/shared/toolNameValidation.js new file mode 100644 index 0000000000..34b6d19c56 --- /dev/null +++ b/dist/esm/shared/toolNameValidation.js @@ -0,0 +1,92 @@ +/** + * Tool name validation utilities according to SEP: Specify Format for Tool Names + * + * Tool names SHOULD be between 1 and 128 characters in length (inclusive). + * Tool names are case-sensitive. + * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits + * (0-9), underscore (_), dash (-), and dot (.). + * Tool names SHOULD NOT contain spaces, commas, or other special characters. + */ +/** + * Regular expression for valid tool names according to SEP-986 specification + */ +const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; +/** + * Validates a tool name according to the SEP specification + * @param name - The tool name to validate + * @returns An object containing validation result and any warnings + */ +export function validateToolName(name) { + const warnings = []; + // Check length + if (name.length === 0) { + return { + isValid: false, + warnings: ['Tool name cannot be empty'] + }; + } + if (name.length > 128) { + return { + isValid: false, + warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] + }; + } + // Check for specific problematic patterns (these are warnings, not validation failures) + if (name.includes(' ')) { + warnings.push('Tool name contains spaces, which may cause parsing issues'); + } + if (name.includes(',')) { + warnings.push('Tool name contains commas, which may cause parsing issues'); + } + // Check for potentially confusing patterns (leading/trailing dashes, dots, slashes) + if (name.startsWith('-') || name.endsWith('-')) { + warnings.push('Tool name starts or ends with a dash, which may cause parsing issues in some contexts'); + } + if (name.startsWith('.') || name.endsWith('.')) { + warnings.push('Tool name starts or ends with a dot, which may cause parsing issues in some contexts'); + } + // Check for invalid characters + if (!TOOL_NAME_REGEX.test(name)) { + const invalidChars = name + .split('') + .filter(char => !/[A-Za-z0-9._-]/.test(char)) + .filter((char, index, arr) => arr.indexOf(char) === index); // Remove duplicates + warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c => `"${c}"`).join(', ')}`, 'Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)'); + return { + isValid: false, + warnings + }; + } + return { + isValid: true, + warnings + }; +} +/** + * Issues warnings for non-conforming tool names + * @param name - The tool name that triggered the warnings + * @param warnings - Array of warning messages + */ +export function issueToolNameWarning(name, warnings) { + if (warnings.length > 0) { + console.warn(`Tool name validation warning for "${name}":`); + for (const warning of warnings) { + console.warn(` - ${warning}`); + } + console.warn('Tool registration will proceed, but this may cause compatibility issues.'); + console.warn('Consider updating the tool name to conform to the MCP tool naming standard.'); + console.warn('See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.'); + } +} +/** + * Validates a tool name and issues warnings for non-conforming names + * @param name - The tool name to validate + * @returns true if the name is valid, false otherwise + */ +export function validateAndWarnToolName(name) { + const result = validateToolName(name); + // Always issue warnings for any validation issues (both invalid names and warnings) + issueToolNameWarning(name, result.warnings); + return result.isValid; +} +//# sourceMappingURL=toolNameValidation.js.map \ No newline at end of file diff --git a/dist/esm/shared/toolNameValidation.js.map b/dist/esm/shared/toolNameValidation.js.map new file mode 100644 index 0000000000..9fdfcea843 --- /dev/null +++ b/dist/esm/shared/toolNameValidation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"toolNameValidation.js","sourceRoot":"","sources":["../../../src/shared/toolNameValidation.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;GAEG;AACH,MAAM,eAAe,GAAG,yBAAyB,CAAC;AAElD;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAAC,IAAY;IAIzC,MAAM,QAAQ,GAAa,EAAE,CAAC;IAE9B,eAAe;IACf,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACpB,OAAO;YACH,OAAO,EAAE,KAAK;YACd,QAAQ,EAAE,CAAC,2BAA2B,CAAC;SAC1C,CAAC;IACN,CAAC;IAED,IAAI,IAAI,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC;QACpB,OAAO;YACH,OAAO,EAAE,KAAK;YACd,QAAQ,EAAE,CAAC,gEAAgE,IAAI,CAAC,MAAM,GAAG,CAAC;SAC7F,CAAC;IACN,CAAC;IAED,wFAAwF;IACxF,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACrB,QAAQ,CAAC,IAAI,CAAC,2DAA2D,CAAC,CAAC;IAC/E,CAAC;IAED,IAAI,IAAI,CA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,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACtB,OAAO,CAAC,IAAI,CAAC,qCAAqC,IAAI,IAAI,CAAC,CAAC;QAC5D,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;YAC7B,OAAO,CAAC,IAAI,CAAC,OAAO,OAAO,EAAE,CAAC,CAAC;QACnC,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,0EAA0E,CAAC,CAAC;QACzF,OAAO,CAAC,IAAI,CAAC,6EAA6E,CAAC,CAAC;QAC5F,OAAO,CAAC,IAAI,CACR,oIAAoI,CACvI,CAAC;IACN,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CAAC,IAAY;IAChD,MAAM,MAAM,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAEtC,oFAAoF;IACpF,oBAAoB,CAAC,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;IAE5C,OAAO,MAAM,CAAC,OAAO,CAAC;AAC1B,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/transport.d.ts b/dist/esm/shared/transport.d.ts new file mode 100644 index 0000000000..7fb5efab77 --- /dev/null +++ b/dist/esm/shared/transport.d.ts @@ -0,0 +1,89 @@ +import { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types.js'; +export type FetchLike = (url: string | URL, init?: RequestInit) => Promise; +/** + * Normalizes HeadersInit to a plain Record for manipulation. + * Handles Headers objects, arrays of tuples, and plain objects. + */ +export declare function normalizeHeaders(headers: HeadersInit | undefined): Record; +/** + * Creates a fetch function that includes base RequestInit options. + * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. + * + * @param baseFetch - The base fetch function to wrap (defaults to global fetch) + * @param baseInit - The base RequestInit to merge with each request + * @returns A wrapped fetch function that merges base options with call-specific options + */ +export declare function createFetchWithInit(baseFetch?: FetchLike, baseInit?: RequestInit): FetchLike; +/** + * Options for sending a JSON-RPC message. + */ +export type TransportSendOptions = { + /** + * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with. + */ + relatedRequestId?: RequestId; + /** + * The resumption token used to continue long-running requests that were interrupted. + * + * This allows clients to reconnect and continue from where they left off, if supported by the transport. + */ + resumptionToken?: string; + /** + * A callback that is invoked when the resumption token changes, if supported by the transport. + * + * This allows clients to persist the latest token for potential reconnection. + */ + onresumptiontoken?: (token: string) => void; +}; +/** + * Describes the minimal contract for a MCP transport that a client or server can communicate over. + */ +export interface Transport { + /** + * Starts processing messages on the transport, including any connection steps that might need to be taken. + * + * This method should only be called after callbacks are installed, or else messages may be lost. + * + * NOTE: This method should not be called explicitly when using Client, Server, or Protocol classes, as they will implicitly call start(). + */ + start(): Promise; + /** + * Sends a JSON-RPC message (request or response). + * + * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with. + */ + send(message: JSONRPCMessage, options?: TransportSendOptions): Promise; + /** + * Closes the connection. + */ + close(): Promise; + /** + * Callback for when the connection is closed for any reason. + * + * This should be invoked when close() is called as well. + */ + onclose?: () => void; + /** + * Callback for when an error occurs. + * + * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. + */ + onerror?: (error: Error) => void; + /** + * Callback for when a message (request or response) is received over the connection. + * + * Includes the requestInfo and authInfo if the transport is authenticated. + * + * The requestInfo can be used to get the original request information (headers, etc.) + */ + onmessage?: (message: T, extra?: MessageExtraInfo) => void; + /** + * The session ID generated for this connection. + */ + sessionId?: string; + /** + * Sets the protocol version used for the connection (called when the initialize response is received). + */ + setProtocolVersion?: (version: string) => void; +} +//# sourceMappingURL=transport.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/transport.d.ts.map b/dist/esm/shared/transport.d.ts.map new file mode 100644 index 0000000000..7a3d837df8 --- /dev/null +++ b/dist/esm/shared/transport.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../../src/shared/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAA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EG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,kBAAkB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CAClD"} \ No newline at end of file diff --git a/dist/esm/shared/transport.js b/dist/esm/shared/transport.js new file mode 100644 index 0000000000..486c840dd1 --- /dev/null +++ b/dist/esm/shared/transport.js @@ -0,0 +1,39 @@ +/** + * Normalizes HeadersInit to a plain Record for manipulation. + * Handles Headers objects, arrays of tuples, and plain objects. + */ +export function normalizeHeaders(headers) { + if (!headers) + return {}; + if (headers instanceof Headers) { + return Object.fromEntries(headers.entries()); + } + if (Array.isArray(headers)) { + return Object.fromEntries(headers); + } + return { ...headers }; +} +/** + * Creates a fetch function that includes base RequestInit options. + * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. + * + * @param baseFetch - The base fetch function to wrap (defaults to global fetch) + * @param baseInit - The base RequestInit to merge with each request + * @returns A wrapped fetch function that merges base options with call-specific options + */ +export function createFetchWithInit(baseFetch = fetch, baseInit) { + if (!baseInit) { + return baseFetch; + } + // Return a wrapped fetch that merges base RequestInit with call-specific init + return async (url, init) => { + const mergedInit = { + ...baseInit, + ...init, + // Headers need special handling - merge instead of replace + headers: (init === null || init === void 0 ? void 0 : init.headers) ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers + }; + return baseFetch(url, mergedInit); + }; +} +//# sourceMappingURL=transport.js.map \ No newline at end of file diff --git a/dist/esm/shared/transport.js.map b/dist/esm/shared/transport.js.map new file mode 100644 index 0000000000..026dddb82e --- /dev/null +++ b/dist/esm/shared/transport.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../src/shared/transport.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAgC;IAC7D,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,CAAC;IAExB,IAAI,OAAO,YAAY,OAAO,EAAE,CAAC;QAC7B,OAAO,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IACjD,CAAC;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACzB,OAAO,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,EAAE,GAAI,OAAkC,EAAE,CAAC;AACtD,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,mBAAmB,CAAC,YAAuB,KAAK,EAAE,QAAsB;IACpF,IAAI,CAAC,QAAQ,EAAE,CAAC;QACZ,OAAO,SAAS,CAAC;IACrB,CAAC;IAED,8EAA8E;IAC9E,OAAO,KAAK,EAAE,GAAiB,EAAE,IAAkB,EAAqB,EAAE;QACtE,MAAM,UAAU,GAAgB;YAC5B,GAAG,QAAQ;YACX,GAAG,IAAI;YACP,2DAA2D;YAC3D,OAAO,EAAE,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,EAAC,CAAC,CAAC,EAAE,GAAG,gBAAgB,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,GAAG,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO;SAC3H,CAAC;QACF,OAAO,SAAS,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC;IACtC,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/uriTemplate.d.ts b/dist/esm/shared/uriTemplate.d.ts new file mode 100644 index 0000000000..175e329b66 --- /dev/null +++ b/dist/esm/shared/uriTemplate.d.ts @@ -0,0 +1,25 @@ +export type Variables = Record; +export declare class UriTemplate { + /** + * Returns true if the given string contains any URI template expressions. + * A template expression is a sequence of characters enclosed in curly braces, + * like {foo} or {?bar}. + */ + static isTemplate(str: string): boolean; + private static validateLength; + private readonly template; + private readonly parts; + get variableNames(): string[]; + constructor(template: string); + toString(): string; + private parse; + private getOperator; + private getNames; + private encodeValue; + private expandPart; + expand(variables: Variables): string; + private escapeRegExp; + private partToRegExp; + match(uri: string): Variables | null; +} +//# sourceMappingURL=uriTemplate.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/uriTemplate.d.ts.map b/dist/esm/shared/uriTemplate.d.ts.map new file mode 100644 index 0000000000..052e91851e --- /dev/null +++ b/dist/esm/shared/uriTemplate.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"uriTemplate.d.ts","sourceRoot":"","sources":["../../../src/shared/uriTemplate.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC;AAO1D,qBAAa,WAAW;IACpB;;;;OAIG;IACH,MAAM,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAMvC,OAAO,CAAC,MAAM,CAAC,cAAc;IAK7B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAyF;IAE/G,IAAI,aAAa,IAAI,MAAM,EAAE,CAE5B;gBAEW,QAAQ,EAAE,MAAM;IAM5B,QAAQ,IAAI,MAAM;IAIlB,OAAO,CAAC,KAAK;IA8Cb,OAAO,CAAC,WAAW;IAKnB,OAAO,CAAC,QAAQ;IAShB,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,UAAU;IAsDlB,MAAM,CAAC,SAAS,EAAE,SAAS,GAAG,MAAM;IA4BpC,OAAO,CAAC,YAAY;IAIpB,OAAO,CAAC,YAAY;IAkDpB,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;CAuCvC"} \ No newline at end of file diff --git a/dist/esm/shared/uriTemplate.js b/dist/esm/shared/uriTemplate.js new file mode 100644 index 0000000000..2837ba826d --- /dev/null +++ b/dist/esm/shared/uriTemplate.js @@ -0,0 +1,239 @@ +// Claude-authored implementation of RFC 6570 URI Templates +const MAX_TEMPLATE_LENGTH = 1000000; // 1MB +const MAX_VARIABLE_LENGTH = 1000000; // 1MB +const MAX_TEMPLATE_EXPRESSIONS = 10000; +const MAX_REGEX_LENGTH = 1000000; // 1MB +export class UriTemplate { + /** + * Returns true if the given string contains any URI template expressions. + * A template expression is a sequence of characters enclosed in curly braces, + * like {foo} or {?bar}. + */ + static isTemplate(str) { + // Look for any sequence of characters between curly braces + // that isn't just whitespace + return /\{[^}\s]+\}/.test(str); + } + static validateLength(str, max, context) { + if (str.length > max) { + throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); + } + } + get variableNames() { + return this.parts.flatMap(part => (typeof part === 'string' ? [] : part.names)); + } + constructor(template) { + UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, 'Template'); + this.template = template; + this.parts = this.parse(template); + } + toString() { + return this.template; + } + parse(template) { + const parts = []; + let currentText = ''; + let i = 0; + let expressionCount = 0; + while (i < template.length) { + if (template[i] === '{') { + if (currentText) { + parts.push(currentText); + currentText = ''; + } + const end = template.indexOf('}', i); + if (end === -1) + throw new Error('Unclosed template expression'); + expressionCount++; + if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) { + throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); + } + const expr = template.slice(i + 1, end); + const operator = this.getOperator(expr); + const exploded = expr.includes('*'); + const names = this.getNames(expr); + const name = names[0]; + // Validate variable name length + for (const name of names) { + UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name'); + } + parts.push({ name, operator, names, exploded }); + i = end + 1; + } + else { + currentText += template[i]; + i++; + } + } + if (currentText) { + parts.push(currentText); + } + return parts; + } + getOperator(expr) { + const operators = ['+', '#', '.', '/', '?', '&']; + return operators.find(op => expr.startsWith(op)) || ''; + } + getNames(expr) { + const operator = this.getOperator(expr); + return expr + .slice(operator.length) + .split(',') + .map(name => name.replace('*', '').trim()) + .filter(name => name.length > 0); + } + encodeValue(value, operator) { + UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, 'Variable value'); + if (operator === '+' || operator === '#') { + return encodeURI(value); + } + return encodeURIComponent(value); + } + expandPart(part, variables) { + if (part.operator === '?' || part.operator === '&') { + const pairs = part.names + .map(name => { + const value = variables[name]; + if (value === undefined) + return ''; + const encoded = Array.isArray(value) + ? value.map(v => this.encodeValue(v, part.operator)).join(',') + : this.encodeValue(value.toString(), part.operator); + return `${name}=${encoded}`; + }) + .filter(pair => pair.length > 0); + if (pairs.length === 0) + return ''; + const separator = part.operator === '?' ? '?' : '&'; + return separator + pairs.join('&'); + } + if (part.names.length > 1) { + const values = part.names.map(name => variables[name]).filter(v => v !== undefined); + if (values.length === 0) + return ''; + return values.map(v => (Array.isArray(v) ? v[0] : v)).join(','); + } + const value = variables[part.name]; + if (value === undefined) + return ''; + const values = Array.isArray(value) ? value : [value]; + const encoded = values.map(v => this.encodeValue(v, part.operator)); + switch (part.operator) { + case '': + return encoded.join(','); + case '+': + return encoded.join(','); + case '#': + return '#' + encoded.join(','); + case '.': + return '.' + encoded.join('.'); + case '/': + return '/' + encoded.join('/'); + default: + return encoded.join(','); + } + } + expand(variables) { + let result = ''; + let hasQueryParam = false; + for (const part of this.parts) { + if (typeof part === 'string') { + result += part; + continue; + } + const expanded = this.expandPart(part, variables); + if (!expanded) + continue; + // Convert ? to & if we already have a query parameter + if ((part.operator === '?' || part.operator === '&') && hasQueryParam) { + result += expanded.replace('?', '&'); + } + else { + result += expanded; + } + if (part.operator === '?' || part.operator === '&') { + hasQueryParam = true; + } + } + return result; + } + escapeRegExp(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + } + partToRegExp(part) { + const patterns = []; + // Validate variable name length for matching + for (const name of part.names) { + UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name'); + } + if (part.operator === '?' || part.operator === '&') { + for (let i = 0; i < part.names.length; i++) { + const name = part.names[i]; + const prefix = i === 0 ? '\\' + part.operator : '&'; + patterns.push({ + pattern: prefix + this.escapeRegExp(name) + '=([^&]+)', + name + }); + } + return patterns; + } + let pattern; + const name = part.name; + switch (part.operator) { + case '': + pattern = part.exploded ? '([^/]+(?:,[^/]+)*)' : '([^/,]+)'; + break; + case '+': + case '#': + pattern = '(.+)'; + break; + case '.': + pattern = '\\.([^/,]+)'; + break; + case '/': + pattern = '/' + (part.exploded ? '([^/]+(?:,[^/]+)*)' : '([^/,]+)'); + break; + default: + pattern = '([^/]+)'; + } + patterns.push({ pattern, name }); + return patterns; + } + match(uri) { + UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, 'URI'); + let pattern = '^'; + const names = []; + for (const part of this.parts) { + if (typeof part === 'string') { + pattern += this.escapeRegExp(part); + } + else { + const patterns = this.partToRegExp(part); + for (const { pattern: partPattern, name } of patterns) { + pattern += partPattern; + names.push({ name, exploded: part.exploded }); + } + } + } + pattern += '$'; + UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, 'Generated regex pattern'); + const regex = new RegExp(pattern); + const match = uri.match(regex); + if (!match) + return null; + const result = {}; + for (let i = 0; i < names.length; i++) { + const { name, exploded } = names[i]; + const value = match[i + 1]; + const cleanName = name.replace('*', ''); + if (exploded && value.includes(',')) { + result[cleanName] = value.split(','); + } + else { + result[cleanName] = value; + } + } + return result; + } +} +//# sourceMappingURL=uriTemplate.js.map \ No newline at end of file diff --git a/dist/esm/shared/uriTemplate.js.map b/dist/esm/shared/uriTemplate.js.map new file mode 100644 index 0000000000..2c02e92aee --- /dev/null +++ b/dist/esm/shared/uriTemplate.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uriTemplate.js","sourceRoot":"","sources":["../../../src/shared/uriTemplate.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAI3D,MAAM,mBAAmB,GAAG,OAAO,CAAC,CAAC,MAAM;AAC3C,MAAM,mBAAmB,GAAG,OAAO,CAAC,CAAC,MAAM;AAC3C,MAAM,wBAAwB,GAAG,KAAK,CAAC;AACvC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C;YAExC,IAAI,QAAQ,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;gBAClC,MAAM,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YACzC,CAAC;iBAAM,CAAC;gBACJ,MAAM,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC;YAC9B,CAAC;QACL,CAAC;QAED,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/shared/zodTestMatrix.d.ts b/dist/esm/shared/zodTestMatrix.d.ts new file mode 100644 index 0000000000..7dafd4ce93 --- /dev/null +++ b/dist/esm/shared/zodTestMatrix.d.ts @@ -0,0 +1,16 @@ +import * as z3 from 'zod/v3'; +import * as z4 from 'zod/v4'; +export type ZNamespace = typeof z3 & typeof z4; +export declare const zodTestMatrix: readonly [{ + readonly zodVersionLabel: "Zod v3"; + readonly z: ZNamespace; + readonly isV3: true; + readonly isV4: false; +}, { + readonly zodVersionLabel: "Zod v4"; + readonly z: ZNamespace; + readonly isV3: false; + readonly isV4: true; +}]; +export type ZodMatrixEntry = (typeof zodTestMatrix)[number]; +//# sourceMappingURL=zodTestMatrix.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/zodTestMatrix.d.ts.map b/dist/esm/shared/zodTestMatrix.d.ts.map new file mode 100644 index 0000000000..3842fb1c32 --- /dev/null +++ b/dist/esm/shared/zodTestMatrix.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"zodTestMatrix.d.ts","sourceRoot":"","sources":["../../../src/shared/zodTestMatrix.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC7B,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAG7B,MAAM,MAAM,UAAU,GAAG,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC;AAE/C,eAAO,MAAM,aAAa;;gBAGT,UAAU;;;;;gBAMV,UAAU;;;EAIjB,CAAC;AAEX,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,aAAa,CAAC,CAAC,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/zodTestMatrix.js b/dist/esm/shared/zodTestMatrix.js new file mode 100644 index 0000000000..aafaed4757 --- /dev/null +++ b/dist/esm/shared/zodTestMatrix.js @@ -0,0 +1,17 @@ +import * as z3 from 'zod/v3'; +import * as z4 from 'zod/v4'; +export const zodTestMatrix = [ + { + zodVersionLabel: 'Zod v3', + z: z3, + isV3: true, + isV4: false + }, + { + zodVersionLabel: 'Zod v4', + z: z4, + isV3: false, + isV4: true + } +]; +//# sourceMappingURL=zodTestMatrix.js.map \ No newline at end of file diff --git a/dist/esm/shared/zodTestMatrix.js.map b/dist/esm/shared/zodTestMatrix.js.map new file mode 100644 index 0000000000..581a23a5b7 --- /dev/null +++ b/dist/esm/shared/zodTestMatrix.js.map @@ -0,0 +1 @@ +{"version":3,"file":"zodTestMatrix.js","sourceRoot":"","sources":["../../../src/shared/zodTestMatrix.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC7B,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAK7B,MAAM,CAAC,MAAM,aAAa,GAAG;IACzB;QACI,eAAe,EAAE,QAAQ;QACzB,CAAC,EAAE,EAAgB;QACnB,IAAI,EAAE,IAAa;QACnB,IAAI,EAAE,KAAc;KACvB;IACD;QACI,eAAe,EAAE,QAAQ;QACzB,CAAC,EAAE,EAAgB;QACnB,IAAI,EAAE,KAAc;QACpB,IAAI,EAAE,IAAa;KACtB;CACK,CAAC"} \ No newline at end of file diff --git a/dist/esm/spec.types.d.ts b/dist/esm/spec.types.d.ts new file mode 100644 index 0000000000..bf6a90f80c --- /dev/null +++ b/dist/esm/spec.types.d.ts @@ -0,0 +1,2033 @@ +/** + * This file is automatically generated from the Model Context Protocol specification. + * + * Source: https://github.com/modelcontextprotocol/modelcontextprotocol + * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts + * Last updated from commit: 4528444698f76e6d0337e58d2941d5d3485d779d + * + * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. + * To update this file, run: npm run fetch:spec-types + */ +/** + * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. + * + * @category JSON-RPC + */ +export type JSONRPCMessage = JSONRPCRequest | JSONRPCNotification | JSONRPCResponse | JSONRPCError; +/** @internal */ +export declare const LATEST_PROTOCOL_VERSION = "DRAFT-2025-v3"; +/** @internal */ +export declare const JSONRPC_VERSION = "2.0"; +/** + * A progress token, used to associate progress notifications with the original request. + * + * @category Common Types + */ +export type ProgressToken = string | number; +/** + * An opaque token used to represent a cursor for pagination. + * + * @category Common Types + */ +export type Cursor = string; +/** + * Common params for any request. + * + * @internal + */ +export interface RequestParams { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken?: ProgressToken; + [key: string]: unknown; + }; +} +/** @internal */ +export interface Request { + method: string; + params?: { + [key: string]: any; + }; +} +/** @internal */ +export interface NotificationParams { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** @internal */ +export interface Notification { + method: string; + params?: { + [key: string]: any; + }; +} +/** + * @category Common Types + */ +export interface Result { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; + [key: string]: unknown; +} +/** + * @category Common Types + */ +export interface Error { + /** + * The error type that occurred. + */ + code: number; + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string; + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data?: unknown; +} +/** + * A uniquely identifying ID for a request in JSON-RPC. + * + * @category Common Types + */ +export type RequestId = string | number; +/** + * A request that expects a response. + * + * @category JSON-RPC + */ +export interface JSONRPCRequest extends Request { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; +} +/** + * A notification which does not expect a response. + * + * @category JSON-RPC + */ +export interface JSONRPCNotification extends Notification { + jsonrpc: typeof JSONRPC_VERSION; +} +/** + * A successful (non-error) response to a request. + * + * @category JSON-RPC + */ +export interface JSONRPCResponse { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + result: Result; +} +export declare const PARSE_ERROR = -32700; +export declare const INVALID_REQUEST = -32600; +export declare const METHOD_NOT_FOUND = -32601; +export declare const INVALID_PARAMS = -32602; +export declare const INTERNAL_ERROR = -32603; +/** @internal */ +export declare const URL_ELICITATION_REQUIRED = -32042; +/** + * A response to a request that indicates an error occurred. + * + * @category JSON-RPC + */ +export interface JSONRPCError { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + error: Error; +} +/** + * An error response that indicates that the server requires the client to provide additional information via an elicitation request. + * + * @internal + */ +export interface URLElicitationRequiredError extends Omit { + error: Error & { + code: typeof URL_ELICITATION_REQUIRED; + data: { + elicitations: ElicitRequestURLParams[]; + [key: string]: unknown; + }; + }; +} +/** + * A response that indicates success but carries no data. + * + * @category Common Types + */ +export type EmptyResult = Result; +/** + * Parameters for a `notifications/cancelled` notification. + * + * @category `notifications/cancelled` + */ +export interface CancelledNotificationParams extends NotificationParams { + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestId; + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason?: string; +} +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + * + * @category `notifications/cancelled` + */ +export interface CancelledNotification extends JSONRPCNotification { + method: "notifications/cancelled"; + params: CancelledNotificationParams; +} +/** + * Parameters for an `initialize` request. + * + * @category `initialize` + */ +export interface InitializeRequestParams extends RequestParams { + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string; + capabilities: ClientCapabilities; + clientInfo: Implementation; +} +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + * + * @category `initialize` + */ +export interface InitializeRequest extends JSONRPCRequest { + method: "initialize"; + params: InitializeRequestParams; +} +/** + * After receiving an initialize request from the client, the server sends this response. + * + * @category `initialize` + */ +export interface InitializeResult extends Result { + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: string; + capabilities: ServerCapabilities; + serverInfo: Implementation; + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions?: string; +} +/** + * This notification is sent from the client to the server after initialization has finished. + * + * @category `notifications/initialized` + */ +export interface InitializedNotification extends JSONRPCNotification { + method: "notifications/initialized"; + params?: NotificationParams; +} +/** + * 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. + * + * @category `initialize` + */ +export interface ClientCapabilities { + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental?: { + [key: string]: object; + }; + /** + * Present if the client supports listing roots. + */ + roots?: { + /** + * Whether the client supports notifications for changes to the roots list. + */ + listChanged?: boolean; + }; + /** + * Present if the client supports sampling from an LLM. + */ + sampling?: { + /** + * Whether the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context?: object; + /** + * Whether the client supports tool use via tools and toolChoice parameters. + */ + tools?: object; + }; + /** + * Present if the client supports elicitation from the server. + */ + elicitation?: { + form?: object; + url?: object; + }; +} +/** + * 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. + * + * @category `initialize` + */ +export interface ServerCapabilities { + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental?: { + [key: string]: object; + }; + /** + * Present if the server supports sending log messages to the client. + */ + logging?: object; + /** + * Present if the server supports argument autocompletion suggestions. + */ + completions?: object; + /** + * Present if the server offers any prompt templates. + */ + prompts?: { + /** + * Whether this server supports notifications for changes to the prompt list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any resources to read. + */ + resources?: { + /** + * Whether this server supports subscribing to resource updates. + */ + subscribe?: boolean; + /** + * Whether this server supports notifications for changes to the resource list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any tools to call. + */ + tools?: { + /** + * Whether this server supports notifications for changes to the tool list. + */ + listChanged?: boolean; + }; +} +/** + * An optionally-sized icon that can be displayed in a user interface. + * + * @category Common Types + */ +export interface Icon { + /** + * A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a + * `data:` URI with Base64-encoded image data. + * + * Consumers SHOULD takes steps to ensure URLs serving icons are from the + * same domain as the client/server or a trusted domain. + * + * Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain + * executable JavaScript. + * + * @format uri + */ + src: string; + /** + * Optional MIME type override if the source MIME type is missing or generic. + * For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`. + */ + mimeType?: string; + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes?: string[]; + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme?: "light" | "dark"; +} +/** + * Base interface to add `icons` property. + * + * @internal + */ +export interface Icons { + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons?: Icon[]; +} +/** + * Base interface for metadata with name (identifier) and title (display name) properties. + * + * @internal + */ +export interface BaseMetadata { + /** + * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present). + */ + name: string; + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title?: string; +} +/** + * Describes the MCP implementation. + * + * @category `initialize` + */ +export interface Implementation extends BaseMetadata, Icons { + version: string; + /** + * An optional URL of the website for this implementation. + * + * @format uri + */ + websiteUrl?: string; +} +/** + * 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. + * + * @category `ping` + */ +export interface PingRequest extends JSONRPCRequest { + method: "ping"; + params?: RequestParams; +} +/** + * Parameters for a `notifications/progress` notification. + * + * @category `notifications/progress` + */ +export interface ProgressNotificationParams extends NotificationParams { + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressToken; + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + * + * @TJS-type number + */ + progress: number; + /** + * Total number of items to process (or total progress required), if known. + * + * @TJS-type number + */ + total?: number; + /** + * An optional message describing the current progress. + */ + message?: string; +} +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category `notifications/progress` + */ +export interface ProgressNotification extends JSONRPCNotification { + method: "notifications/progress"; + params: ProgressNotificationParams; +} +/** + * Common parameters for paginated requests. + * + * @internal + */ +export interface PaginatedRequestParams extends RequestParams { + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor?: Cursor; +} +/** @internal */ +export interface PaginatedRequest extends JSONRPCRequest { + params?: PaginatedRequestParams; +} +/** @internal */ +export interface PaginatedResult extends Result { + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor?: Cursor; +} +/** + * Sent from the client to request a list of resources the server has. + * + * @category `resources/list` + */ +export interface ListResourcesRequest extends PaginatedRequest { + method: "resources/list"; +} +/** + * The server's response to a resources/list request from the client. + * + * @category `resources/list` + */ +export interface ListResourcesResult extends PaginatedResult { + resources: Resource[]; +} +/** + * Sent from the client to request a list of resource templates the server has. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesRequest extends PaginatedRequest { + method: "resources/templates/list"; +} +/** + * The server's response to a resources/templates/list request from the client. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesResult extends PaginatedResult { + resourceTemplates: ResourceTemplate[]; +} +/** + * Common parameters when working with resources. + * + * @internal + */ +export interface ResourceRequestParams extends RequestParams { + /** + * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string; +} +/** + * Parameters for a `resources/read` request. + * + * @category `resources/read` + */ +export interface ReadResourceRequestParams extends ResourceRequestParams { +} +/** + * Sent from the client to the server, to read a specific resource URI. + * + * @category `resources/read` + */ +export interface ReadResourceRequest extends JSONRPCRequest { + method: "resources/read"; + params: ReadResourceRequestParams; +} +/** + * The server's response to a resources/read request from the client. + * + * @category `resources/read` + */ +export interface ReadResourceResult extends Result { + contents: (TextResourceContents | BlobResourceContents)[]; +} +/** + * 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. + * + * @category `notifications/resources/list_changed` + */ +export interface ResourceListChangedNotification extends JSONRPCNotification { + method: "notifications/resources/list_changed"; + params?: NotificationParams; +} +/** + * Parameters for a `resources/subscribe` request. + * + * @category `resources/subscribe` + */ +export interface SubscribeRequestParams extends ResourceRequestParams { +} +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + * + * @category `resources/subscribe` + */ +export interface SubscribeRequest extends JSONRPCRequest { + method: "resources/subscribe"; + params: SubscribeRequestParams; +} +/** + * Parameters for a `resources/unsubscribe` request. + * + * @category `resources/unsubscribe` + */ +export interface UnsubscribeRequestParams extends ResourceRequestParams { +} +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + * + * @category `resources/unsubscribe` + */ +export interface UnsubscribeRequest extends JSONRPCRequest { + method: "resources/unsubscribe"; + params: UnsubscribeRequestParams; +} +/** + * Parameters for a `notifications/resources/updated` notification. + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotificationParams extends NotificationParams { + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + * + * @format uri + */ + uri: string; +} +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotification extends JSONRPCNotification { + method: "notifications/resources/updated"; + params: ResourceUpdatedNotificationParams; +} +/** + * A known resource that the server is capable of reading. + * + * @category `resources/list` + */ +export interface Resource extends BaseMetadata, Icons { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size?: number; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * A template description for resources available on the server. + * + * @category `resources/templates/list` + */ +export interface ResourceTemplate extends BaseMetadata, Icons { + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + * + * @format uri-template + */ + uriTemplate: string; + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType?: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * The contents of a specific resource or sub-resource. + * + * @internal + */ +export interface ResourceContents { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * @category Content + */ +export interface TextResourceContents extends ResourceContents { + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string; +} +/** + * @category Content + */ +export interface BlobResourceContents extends ResourceContents { + /** + * A base64-encoded string representing the binary data of the item. + * + * @format byte + */ + blob: string; +} +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + * + * @category `prompts/list` + */ +export interface ListPromptsRequest extends PaginatedRequest { + method: "prompts/list"; +} +/** + * The server's response to a prompts/list request from the client. + * + * @category `prompts/list` + */ +export interface ListPromptsResult extends PaginatedResult { + prompts: Prompt[]; +} +/** + * Parameters for a `prompts/get` request. + * + * @category `prompts/get` + */ +export interface GetPromptRequestParams extends RequestParams { + /** + * The name of the prompt or prompt template. + */ + name: string; + /** + * Arguments to use for templating the prompt. + */ + arguments?: { + [key: string]: string; + }; +} +/** + * Used by the client to get a prompt provided by the server. + * + * @category `prompts/get` + */ +export interface GetPromptRequest extends JSONRPCRequest { + method: "prompts/get"; + params: GetPromptRequestParams; +} +/** + * The server's response to a prompts/get request from the client. + * + * @category `prompts/get` + */ +export interface GetPromptResult extends Result { + /** + * An optional description for the prompt. + */ + description?: string; + messages: PromptMessage[]; +} +/** + * A prompt or prompt template that the server offers. + * + * @category `prompts/list` + */ +export interface Prompt extends BaseMetadata, Icons { + /** + * An optional description of what this prompt provides + */ + description?: string; + /** + * A list of arguments to use for templating the prompt. + */ + arguments?: PromptArgument[]; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * Describes an argument that a prompt can accept. + * + * @category `prompts/list` + */ +export interface PromptArgument extends BaseMetadata { + /** + * A human-readable description of the argument. + */ + description?: string; + /** + * Whether this argument must be provided. + */ + required?: boolean; +} +/** + * The sender or recipient of messages and data in a conversation. + * + * @category Common Types + */ +export type Role = "user" | "assistant"; +/** + * Describes a message returned as part of a prompt. + * + * This is similar to `SamplingMessage`, but also supports the embedding of + * resources from the MCP server. + * + * @category `prompts/get` + */ +export interface PromptMessage { + role: Role; + content: ContentBlock; +} +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + * + * @category Content + */ +export interface ResourceLink extends Resource { + type: "resource_link"; +} +/** + * The contents of a resource, embedded into a prompt or tool call result. + * + * It is up to the client how best to render embedded resources for the benefit + * of the LLM and/or the user. + * + * @category Content + */ +export interface EmbeddedResource { + type: "resource"; + resource: TextResourceContents | BlobResourceContents; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * 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. + * + * @category `notifications/prompts/list_changed` + */ +export interface PromptListChangedNotification extends JSONRPCNotification { + method: "notifications/prompts/list_changed"; + params?: NotificationParams; +} +/** + * Sent from the client to request a list of tools the server has. + * + * @category `tools/list` + */ +export interface ListToolsRequest extends PaginatedRequest { + method: "tools/list"; +} +/** + * The server's response to a tools/list request from the client. + * + * @category `tools/list` + */ +export interface ListToolsResult extends PaginatedResult { + tools: Tool[]; +} +/** + * The server's response to a tool call. + * + * @category `tools/call` + */ +export interface CallToolResult extends Result { + /** + * A list of content objects that represent the unstructured result of the tool call. + */ + content: ContentBlock[]; + /** + * An optional JSON object that represents the structured result of the tool call. + */ + structuredContent?: { + [key: string]: unknown; + }; + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError?: boolean; +} +/** + * Parameters for a `tools/call` request. + * + * @category `tools/call` + */ +export interface CallToolRequestParams extends RequestParams { + /** + * The name of the tool. + */ + name: string; + /** + * Arguments to use for the tool call. + */ + arguments?: { + [key: string]: unknown; + }; +} +/** + * Used by the client to invoke a tool provided by the server. + * + * @category `tools/call` + */ +export interface CallToolRequest extends JSONRPCRequest { + method: "tools/call"; + params: CallToolRequestParams; +} +/** + * 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. + * + * @category `notifications/tools/list_changed` + */ +export interface ToolListChangedNotification extends JSONRPCNotification { + method: "notifications/tools/list_changed"; + params?: NotificationParams; +} +/** + * Security scheme indicating no authentication is required. + * + * @category `tools/list` + */ +export interface NoAuthSecurityScheme { + type: "noauth"; +} +/** + * Security scheme indicating OAuth 2.0 authentication is required. + * + * @category `tools/list` + */ +export interface OAuth2SecurityScheme { + type: "oauth2"; + /** + * Optional list of OAuth 2.0 scopes required for this tool. + */ + scopes?: string[]; +} +/** + * A security scheme that can be used to authenticate tool calls. + * + * @category `tools/list` + */ +export type SecurityScheme = NoAuthSecurityScheme | OAuth2SecurityScheme; +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + * + * @category `tools/list` + */ +export interface ToolAnnotations { + /** + * A human-readable title for the tool. + */ + title?: string; + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint?: boolean; + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint?: boolean; + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint?: boolean; + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint?: boolean; +} +/** + * Definition for a tool the client can call. + * + * @category `tools/list` + */ +export interface Tool extends BaseMetadata, Icons { + /** + * A human-readable description of the tool. + * + * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. + */ + description?: string; + /** + * A JSON Schema object defining the expected parameters for the tool. + */ + inputSchema: { + type: "object"; + properties?: { + [key: string]: object; + }; + required?: string[]; + }; + /** + * An optional JSON Schema object defining the structure of the tool's output returned in + * the structuredContent field of a CallToolResult. + */ + outputSchema?: { + type: "object"; + properties?: { + [key: string]: object; + }; + required?: string[]; + }; + /** + * Optional additional tool information. + * + * Display name precedence order is: title, annotations.title, then name. + */ + annotations?: ToolAnnotations; + /** + * Optional list of security schemes supported by this tool. + * If missing, the tool follows the server's default authentication policy. + * If present, lists the supported authentication schemes (e.g., "noauth", "oauth2"). + */ + securitySchemes?: SecurityScheme[]; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * Parameters for a `logging/setLevel` request. + * + * @category `logging/setLevel` + */ +export interface SetLevelRequestParams extends RequestParams { + /** + * 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/message. + */ + level: LoggingLevel; +} +/** + * A request from the client to the server, to enable or adjust logging. + * + * @category `logging/setLevel` + */ +export interface SetLevelRequest extends JSONRPCRequest { + method: "logging/setLevel"; + params: SetLevelRequestParams; +} +/** + * Parameters for a `notifications/message` notification. + * + * @category `notifications/message` + */ +export interface LoggingMessageNotificationParams extends NotificationParams { + /** + * The severity of this log message. + */ + level: LoggingLevel; + /** + * An optional name of the logger issuing this message. + */ + logger?: string; + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown; +} +/** + * JSONRPCNotification 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. + * + * @category `notifications/message` + */ +export interface LoggingMessageNotification extends JSONRPCNotification { + method: "notifications/message"; + params: LoggingMessageNotificationParams; +} +/** + * The severity of a log message. + * + * These map to syslog message severities, as specified in RFC-5424: + * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 + * + * @category Common Types + */ +export type LoggingLevel = "debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency"; +/** + * Parameters for a `sampling/createMessage` request. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequestParams extends RequestParams { + messages: SamplingMessage[]; + /** + * The server's preferences for which model to select. The client MAY ignore these preferences. + */ + modelPreferences?: ModelPreferences; + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt?: string; + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext?: "none" | "thisServer" | "allServers"; + /** + * @TJS-type number + */ + temperature?: number; + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number; + stopSequences?: string[]; + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata?: object; + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools?: Tool[]; + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice?: ToolChoice; +} +/** + * Controls tool selection behavior for sampling requests. + * + * @category `sampling/createMessage` + */ +export interface ToolChoice { + /** + * Controls the tool use ability of the model: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode?: "auto" | "required" | "none"; +} +/** + * 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. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequest extends JSONRPCRequest { + method: "sampling/createMessage"; + params: CreateMessageRequestParams; +} +/** + * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageResult extends Result, SamplingMessage { + /** + * The name of the model that generated the message. + */ + model: string; + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason?: "endTurn" | "stopSequence" | "maxTokens" | "toolUse" | string; +} +/** + * Describes a message issued to or received from an LLM API. + * + * @category `sampling/createMessage` + */ +export interface SamplingMessage { + role: Role; + content: SamplingMessageContentBlock | SamplingMessageContentBlock[]; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +export type SamplingMessageContentBlock = TextContent | ImageContent | AudioContent | ToolUseContent | ToolResultContent; +/** + * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed + * + * @category Common Types + */ +export interface Annotations { + /** + * Describes who the intended customer of this object or data is. + * + * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). + */ + audience?: Role[]; + /** + * Describes how important this data is for operating the server. + * + * A value of 1 means "most important," and indicates that the data is + * effectively required, while 0 means "least important," and indicates that + * the data is entirely optional. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + priority?: number; + /** + * The moment the resource was last modified, as an ISO 8601 formatted string. + * + * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"). + * + * Examples: last activity timestamp in an open file, timestamp when the resource + * was attached, etc. + */ + lastModified?: string; +} +/** + * @category Content + */ +export type ContentBlock = TextContent | ImageContent | AudioContent | ResourceLink | EmbeddedResource; +/** + * Text provided to or from an LLM. + * + * @category Content + */ +export interface TextContent { + type: "text"; + /** + * The text content of the message. + */ + text: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * An image provided to or from an LLM. + * + * @category Content + */ +export interface ImageContent { + type: "image"; + /** + * The base64-encoded image data. + * + * @format byte + */ + data: string; + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * Audio provided to or from an LLM. + * + * @category Content + */ +export interface AudioContent { + type: "audio"; + /** + * The base64-encoded audio data. + * + * @format byte + */ + data: string; + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string; + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * A request from the assistant to call a tool. + * + * @category `sampling/createMessage` + */ +export interface ToolUseContent { + type: "tool_use"; + /** + * A unique identifier for this tool use. + * + * This ID is used to match tool results to their corresponding tool uses. + */ + id: string; + /** + * The name of the tool to call. + */ + name: string; + /** + * The arguments to pass to the tool, conforming to the tool's input schema. + */ + input: { + [key: string]: unknown; + }; + /** + * Optional metadata about the tool use. Clients SHOULD preserve this field when + * including tool uses in subsequent sampling requests to enable caching optimizations. + * + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * The result of a tool use, provided by the user back to the assistant. + * + * @category `sampling/createMessage` + */ +export interface ToolResultContent { + type: "tool_result"; + /** + * The ID of the tool use this result corresponds to. + * + * This MUST match the ID from a previous ToolUseContent. + */ + toolUseId: string; + /** + * The unstructured result content of the tool use. + * + * This has the same format as CallToolResult.content and can include text, images, + * audio, resource links, and embedded resources. + */ + content: ContentBlock[]; + /** + * An optional structured result object. + * + * If the tool defined an outputSchema, this SHOULD conform to that schema. + */ + structuredContent?: { + [key: string]: unknown; + }; + /** + * Whether the tool use resulted in an error. + * + * If true, the content typically describes the error that occurred. + * Default: false + */ + isError?: boolean; + /** + * Optional metadata about the tool result. Clients SHOULD preserve this field when + * including tool results in subsequent sampling requests to enable caching optimizations. + * + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * The server's preferences for model selection, requested of the client during sampling. + * + * Because LLMs can vary along multiple dimensions, choosing the "best" model is + * rarely straightforward. Different models excel in different areas—some are + * faster but less capable, others are more capable but more expensive, and so + * on. This interface allows servers to express their priorities across multiple + * dimensions to help clients make an appropriate selection for their use case. + * + * These preferences are always advisory. The client MAY ignore them. It is also + * up to the client to decide how to interpret these preferences and how to + * balance them against other considerations. + * + * @category `sampling/createMessage` + */ +export interface ModelPreferences { + /** + * Optional hints to use for model selection. + * + * If multiple hints are specified, the client MUST evaluate them in order + * (such that the first match is taken). + * + * The client SHOULD prioritize these hints over the numeric priorities, but + * MAY still use the priorities to select from ambiguous matches. + */ + hints?: ModelHint[]; + /** + * How much to prioritize cost when selecting a model. A value of 0 means cost + * is not important, while a value of 1 means cost is the most important + * factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + costPriority?: number; + /** + * How much to prioritize sampling speed (latency) when selecting a model. A + * value of 0 means speed is not important, while a value of 1 means speed is + * the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + speedPriority?: number; + /** + * How much to prioritize intelligence and capabilities when selecting a + * model. A value of 0 means intelligence is not important, while a value of 1 + * means intelligence is the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + intelligencePriority?: number; +} +/** + * Hints to use for model selection. + * + * Keys not declared here are currently left unspecified by the spec and are up + * to the client to interpret. + * + * @category `sampling/createMessage` + */ +export interface ModelHint { + /** + * A hint for a model name. + * + * The client SHOULD treat this as a substring of a model name; for example: + * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` + * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. + * - `claude` should match any Claude model + * + * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: + * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` + */ + name?: string; +} +/** + * Parameters for a `completion/complete` request. + * + * @category `completion/complete` + */ +export interface CompleteRequestParams extends RequestParams { + ref: PromptReference | ResourceTemplateReference; + /** + * The argument's information + */ + argument: { + /** + * The name of the argument + */ + name: string; + /** + * The value of the argument to use for completion matching. + */ + value: string; + }; + /** + * Additional, optional context for completions + */ + context?: { + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments?: { + [key: string]: string; + }; + }; +} +/** + * A request from the client to the server, to ask for completion options. + * + * @category `completion/complete` + */ +export interface CompleteRequest extends JSONRPCRequest { + method: "completion/complete"; + params: CompleteRequestParams; +} +/** + * The server's response to a completion/complete request + * + * @category `completion/complete` + */ +export interface CompleteResult extends Result { + completion: { + /** + * An array of completion values. Must not exceed 100 items. + */ + values: string[]; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total?: number; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore?: boolean; + }; +} +/** + * A reference to a resource or resource template definition. + * + * @category `completion/complete` + */ +export interface ResourceTemplateReference { + type: "ref/resource"; + /** + * The URI or URI template of the resource. + * + * @format uri-template + */ + uri: string; +} +/** + * Identifies a prompt. + * + * @category `completion/complete` + */ +export interface PromptReference extends BaseMetadata { + type: "ref/prompt"; +} +/** + * Sent from the server to request a list of root URIs from the client. Roots allow + * servers to ask for specific directories or files to operate on. A common example + * for roots is providing a set of repositories or directories a server should operate + * on. + * + * This request is typically used when the server needs to understand the file system + * structure or access specific locations that the client has permission to read from. + * + * @category `roots/list` + */ +export interface ListRootsRequest extends JSONRPCRequest { + method: "roots/list"; + params?: RequestParams; +} +/** + * The client's response to a roots/list request from the server. + * This result contains an array of Root objects, each representing a root directory + * or file that the server can operate on. + * + * @category `roots/list` + */ +export interface ListRootsResult extends Result { + roots: Root[]; +} +/** + * Represents a root directory or file that the server can operate on. + * + * @category `roots/list` + */ +export interface Root { + /** + * The URI identifying the root. This *must* start with file:// for now. + * This restriction may be relaxed in future versions of the protocol to allow + * other URI schemes. + * + * @format uri + */ + uri: string; + /** + * An optional name for the root. This can be used to provide a human-readable + * identifier for the root, which may be useful for display purposes or for + * referencing the root in other parts of the application. + */ + name?: string; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + [key: string]: unknown; + }; +} +/** + * A notification from the client to the server, informing it that the list of roots has changed. + * This notification should be sent whenever the client adds, removes, or modifies any root. + * The server should then request an updated list of roots using the ListRootsRequest. + * + * @category `notifications/roots/list_changed` + */ +export interface RootsListChangedNotification extends JSONRPCNotification { + method: "notifications/roots/list_changed"; + params?: NotificationParams; +} +/** + * The parameters for a request to elicit non-sensitive information from the user via a form in the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequestFormParams extends RequestParams { + /** + * The elicitation mode. + */ + mode: "form"; + /** + * The message to present to the user describing what information is being requested. + */ + message: string; + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: { + type: "object"; + properties: { + [key: string]: PrimitiveSchemaDefinition; + }; + required?: string[]; + }; +} +/** + * The parameters for a request to elicit information from the user via a URL in the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequestURLParams extends RequestParams { + /** + * The elicitation mode. + */ + mode: "url"; + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: string; + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: string; + /** + * The URL that the user should navigate to. + * + * @format uri + */ + url: string; +} +/** + * The parameters for a request to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export type ElicitRequestParams = ElicitRequestFormParams | ElicitRequestURLParams; +/** + * A request from the server to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequest extends JSONRPCRequest { + method: "elicitation/create"; + params: ElicitRequestParams; +} +/** + * Restricted schema definitions that only allow primitive types + * without nested objects or arrays. + * + * @category `elicitation/create` + */ +export type PrimitiveSchemaDefinition = StringSchema | NumberSchema | BooleanSchema | EnumSchema; +/** + * @category `elicitation/create` + */ +export interface StringSchema { + type: "string"; + title?: string; + description?: string; + minLength?: number; + maxLength?: number; + format?: "email" | "uri" | "date" | "date-time"; + default?: string; +} +/** + * @category `elicitation/create` + */ +export interface NumberSchema { + type: "number" | "integer"; + title?: string; + description?: string; + minimum?: number; + maximum?: number; + default?: number; +} +/** + * @category `elicitation/create` + */ +export interface BooleanSchema { + type: "boolean"; + title?: string; + description?: string; + default?: boolean; +} +/** + * Schema for single-selection enumeration without display titles for options. + * + * @category `elicitation/create` + */ +export interface UntitledSingleSelectEnumSchema { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum values to choose from. + */ + enum: string[]; + /** + * Optional default value. + */ + default?: string; +} +/** + * Schema for single-selection enumeration with display titles for each option. + * + * @category `elicitation/create` + */ +export interface TitledSingleSelectEnumSchema { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum options with values and display labels. + */ + oneOf: Array<{ + /** + * The enum value. + */ + const: string; + /** + * Display label for this option. + */ + title: string; + }>; + /** + * Optional default value. + */ + default?: string; +} +/** + * @category `elicitation/create` + */ +export type SingleSelectEnumSchema = UntitledSingleSelectEnumSchema | TitledSingleSelectEnumSchema; +/** + * Schema for multiple-selection enumeration without display titles for options. + * + * @category `elicitation/create` + */ +export interface UntitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for the array items. + */ + items: { + type: "string"; + /** + * Array of enum values to choose from. + */ + enum: string[]; + }; + /** + * Optional default value. + */ + default?: string[]; +} +/** + * Schema for multiple-selection enumeration with display titles for each option. + * + * @category `elicitation/create` + */ +export interface TitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for array items with enum options and display labels. + */ + items: { + /** + * Array of enum options with values and display labels. + */ + anyOf: Array<{ + /** + * The constant enum value. + */ + const: string; + /** + * Display title for this option. + */ + title: string; + }>; + }; + /** + * Optional default value. + */ + default?: string[]; +} +/** + * @category `elicitation/create` + */ +export type MultiSelectEnumSchema = UntitledMultiSelectEnumSchema | TitledMultiSelectEnumSchema; +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + * + * @category `elicitation/create` + */ +export interface LegacyTitledEnumSchema { + type: "string"; + title?: string; + description?: string; + enum: string[]; + /** + * (Legacy) Display names for enum values. + * Non-standard according to JSON schema 2020-12. + */ + enumNames?: string[]; + default?: string; +} +/** + * @category `elicitation/create` + */ +export type EnumSchema = SingleSelectEnumSchema | MultiSelectEnumSchema | LegacyTitledEnumSchema; +/** + * The client's response to an elicitation request. + * + * @category `elicitation/create` + */ +export interface ElicitResult extends Result { + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: "accept" | "decline" | "cancel"; + /** + * The submitted form data, only present when action is "accept" and mode was "form". + * Contains values matching the requested schema. + * Omitted for out-of-band mode responses. + */ + content?: { + [key: string]: string | number | boolean | string[]; + }; +} +/** + * An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request. + * + * @category `notifications/elicitation/complete` + */ +export interface ElicitationCompleteNotification extends JSONRPCNotification { + method: "notifications/elicitation/complete"; + params: { + /** + * The ID of the elicitation that completed. + */ + elicitationId: string; + }; +} +/** @internal */ +export type ClientRequest = PingRequest | InitializeRequest | CompleteRequest | SetLevelRequest | GetPromptRequest | ListPromptsRequest | ListResourcesRequest | ListResourceTemplatesRequest | ReadResourceRequest | SubscribeRequest | UnsubscribeRequest | CallToolRequest | ListToolsRequest; +/** @internal */ +export type ClientNotification = CancelledNotification | ProgressNotification | InitializedNotification | RootsListChangedNotification; +/** @internal */ +export type ClientResult = EmptyResult | CreateMessageResult | ListRootsResult | ElicitResult; +/** @internal */ +export type ServerRequest = PingRequest | CreateMessageRequest | ListRootsRequest | ElicitRequest; +/** @internal */ +export type ServerNotification = CancelledNotification | ProgressNotification | LoggingMessageNotification | ResourceUpdatedNotification | ResourceListChangedNotification | ToolListChangedNotification | PromptListChangedNotification | ElicitationCompleteNotification; +/** @internal */ +export type ServerResult = EmptyResult | InitializeResult | CompleteResult | GetPromptResult | ListPromptsResult | ListResourceTemplatesResult | ListResourcesResult | ReadResourceResult | CallToolResult | ListToolsResult; +//# sourceMappingURL=spec.types.d.ts.map \ No newline at end of file diff --git a/dist/esm/spec.types.d.ts.map b/dist/esm/spec.types.d.ts.map new file mode 100644 index 0000000000..3e44f68e82 --- /dev/null +++ b/dist/esm/spec.types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"spec.types.d.ts","sourceRoot":"","sources":["../../src/spec.types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH;;;;GAIG;AACH,MAAM,MAAM,cAAc,GACtB,cAAc,GACd,mBAAmB,GACnB,eAAe,GACf,YAAY,CAAC;AAEjB,gBAAgB;AAChB,eAAO,MAAM,uBAAuB,kBAAkB,CAAC;AACvD,gBAAgB;AAChB,eAAO,MAAM,eAAe,QAAQ,CAAC;AAErC;;;;GAIG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,MAAM,CAAC;AAE5C;;;;GAIG;AACH,MAAM,MAAM,MAAM,GAAG,MAAM,CAAC;AAE5B;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B;;OAEG;IACH,KAAK,CAAC,EAAE;QACN;;WAEG;QACH,aAAa,CAAC,EAAE,aAAa,CAAC;QAC9B,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;KACxB,CAAC;CACH;AAED,gBAAgB;AAChB,MAAM,WAAW,OAAO;IACtB,MAAM,EAAE,MAAM,CAAC;IAGf,MAAM,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CAAC;CACjC;AAED,gBAAgB;AAChB,MAAM,WAAW,kBAAkB;IACjC;;OAEG;IACH,KAAK,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,CAAC;CACpC;AAED,gBAAgB;AAChB,MAAM,WAAW,YAAY;IAC3B,MAAM,EAAE,MAAM,CAAC;IAGf,MAAM,CAAC,EAAE;QAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,CAAA;KAAE,CA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BAA4B,CAAC;AAEjC,gBAAgB;AAChB,MAAM,MAAM,YAAY,GACpB,WAAW,GACX,mBAAmB,GACnB,eAAe,GACf,YAAY,CAAC;AAGjB,gBAAgB;AAChB,MAAM,MAAM,aAAa,GACrB,WAAW,GACX,oBAAoB,GACpB,gBAAgB,GAChB,aAAa,CAAC;AAElB,gBAAgB;AAChB,MAAM,MAAM,kBAAkB,GAC1B,qBAAqB,GACrB,oBAAoB,GACpB,0BAA0B,GAC1B,2BAA2B,GAC3B,+BAA+B,GAC/B,2BAA2B,GAC3B,6BAA6B,GAC7B,+BAA+B,CAAC;AAEpC,gBAAgB;AAChB,MAAM,MAAM,YAAY,GACpB,WAAW,GACX,gBAAgB,GAChB,cAAc,GACd,eAAe,GACf,iBAAiB,GACjB,2BAA2B,GAC3B,mBAAmB,GACnB,kBAAkB,GAClB,cAAc,GACd,eAAe,CAAC"} \ No newline at end of file diff --git a/dist/esm/spec.types.js b/dist/esm/spec.types.js new file mode 100644 index 0000000000..720ec03b73 --- /dev/null +++ b/dist/esm/spec.types.js @@ -0,0 +1,24 @@ +/** + * This file is automatically generated from the Model Context Protocol specification. + * + * Source: https://github.com/modelcontextprotocol/modelcontextprotocol + * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts + * Last updated from commit: 4528444698f76e6d0337e58d2941d5d3485d779d + * + * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. + * To update this file, run: npm run fetch:spec-types + */ /* JSON-RPC types */ +/** @internal */ +export const LATEST_PROTOCOL_VERSION = "DRAFT-2025-v3"; +/** @internal */ +export const JSONRPC_VERSION = "2.0"; +// Standard JSON-RPC error codes +export const PARSE_ERROR = -32700; +export const INVALID_REQUEST = -32600; +export const METHOD_NOT_FOUND = -32601; +export const INVALID_PARAMS = -32602; +export const INTERNAL_ERROR = -32603; +// Implementation-specific JSON-RPC error codes [-32000, -32099] +/** @internal */ +export const URL_ELICITATION_REQUIRED = -32042; +//# sourceMappingURL=spec.types.js.map \ No newline at end of file diff --git a/dist/esm/spec.types.js.map b/dist/esm/spec.types.js.map new file mode 100644 index 0000000000..d2c9dd0aa6 --- /dev/null +++ b/dist/esm/spec.types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"spec.types.js","sourceRoot":"","sources":["../../src/spec.types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG,CAAA,oBAAoB;AAavB,gBAAgB;AAChB,MAAM,CAAC,MAAM,uBAAuB,GAAG,eAAe,CAAC;AACvD,gBAAgB;AAChB,MAAM,CAAC,MAAM,eAAe,GAAG,KAAK,CAAC;AA4HrC,gCAAgC;AAChC,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,KAAK,CAAC;AAClC,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,KAAK,CAAC;AACtC,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,KAAK,CAAC;AACvC,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,KAAK,CAAC;AACrC,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,KAAK,CAAC;AAErC,gEAAgE;AAChE,gBAAgB;AAChB,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/dist/esm/types.d.ts b/dist/esm/types.d.ts new file mode 100644 index 0000000000..3864800a99 --- /dev/null +++ b/dist/esm/types.d.ts @@ -0,0 +1,4390 @@ +import * as z from 'zod/v4'; +import { AuthInfo } from './server/auth/types.js'; +export declare const LATEST_PROTOCOL_VERSION = "2025-06-18"; +export declare const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; +export declare const SUPPORTED_PROTOCOL_VERSIONS: string[]; +export declare const JSONRPC_VERSION = "2.0"; +/** + * Utility types + */ +type ExpandRecursively = T extends object ? (T extends infer O ? { + [K in keyof O]: ExpandRecursively; +} : never) : T; +/** + * A progress token, used to associate progress notifications with the original request. + */ +export declare const ProgressTokenSchema: z.ZodUnion; +/** + * An opaque token used to represent a cursor for pagination. + */ +export declare const CursorSchema: z.ZodString; +declare const RequestMetaSchema: z.ZodObject<{ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: z.ZodOptional>; +}, z.core.$loose>; +/** + * Common params for any request. + */ +declare const BaseRequestParamsSchema: z.ZodObject<{ + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta: z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$loose>; +export declare const RequestSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; +}, z.core.$strip>; +declare const NotificationsParamsSchema: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; +}, z.core.$loose>; +export declare const NotificationSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + }, z.core.$loose>>; +}, z.core.$strip>; +export declare const ResultSchema: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; +}, z.core.$loose>; +/** + * A uniquely identifying ID for a request in JSON-RPC. + */ +export declare const RequestIdSchema: z.ZodUnion; +/** + * A request that expects a response. + */ +export declare const JSONRPCRequestSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; +}, z.core.$strict>; +export declare const isJSONRPCRequest: (value: unknown) => value is JSONRPCRequest; +/** + * A notification which does not expect a response. + */ +export declare const JSONRPCNotificationSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; +}, z.core.$strict>; +export declare const isJSONRPCNotification: (value: unknown) => value is JSONRPCNotification; +/** + * A successful (non-error) response to a request. + */ +export declare const JSONRPCResponseSchema: z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; + result: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + }, z.core.$loose>; +}, z.core.$strict>; +export declare const isJSONRPCResponse: (value: unknown) => value is JSONRPCResponse; +/** + * Error codes defined by the JSON-RPC specification. + */ +export declare enum ErrorCode { + ConnectionClosed = -32000, + RequestTimeout = -32001, + ParseError = -32700, + InvalidRequest = -32600, + MethodNotFound = -32601, + InvalidParams = -32602, + InternalError = -32603, + UrlElicitationRequired = -32042 +} +/** + * A response to a request that indicates an error occurred. + */ +export declare const JSONRPCErrorSchema: z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; + error: z.ZodObject<{ + code: z.ZodNumber; + message: z.ZodString; + data: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strict>; +export declare const isJSONRPCError: (value: unknown) => value is JSONRPCError; +export declare const JSONRPCMessageSchema: z.ZodUnion>; + }, z.core.$loose>>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; +}, z.core.$strict>, z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + }, z.core.$loose>>; + jsonrpc: z.ZodLiteral<"2.0">; +}, z.core.$strict>, z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; + result: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; + }, z.core.$loose>; +}, z.core.$strict>, z.ZodObject<{ + jsonrpc: z.ZodLiteral<"2.0">; + id: z.ZodUnion; + error: z.ZodObject<{ + code: z.ZodNumber; + message: z.ZodString; + data: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$strict>]>; +/** + * A response that indicates success but carries no data. + */ +export declare const EmptyResultSchema: z.ZodObject<{ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.ZodOptional>; +}, z.core.$strict>; +export declare const CancelledNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + requestId: z.ZodUnion; + reason: z.ZodOptional; +}, z.core.$loose>; +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + */ +export declare const CancelledNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/cancelled">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + requestId: z.ZodUnion; + reason: z.ZodOptional; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * Icon schema for use in tools, prompts, resources, and implementations. + */ +export declare const IconSchema: z.ZodObject<{ + src: z.ZodString; + mimeType: z.ZodOptional; + sizes: z.ZodOptional>; +}, z.core.$strip>; +/** + * Base schema to add `icons` property. + * + */ +export declare const IconsSchema: z.ZodObject<{ + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; +}, z.core.$strip>; +/** + * Base metadata interface for common properties across resources, tools, prompts, and implementations. + */ +export declare const BaseMetadataSchema: z.ZodObject<{ + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Describes the name and version of an MCP implementation. + */ +export declare const ImplementationSchema: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ +export declare const ClientCapabilitiesSchema: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$strip>; +export declare const InitializeRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; + }, z.core.$strip>; + clientInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; +}, z.core.$loose>; +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ +export declare const InitializeRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"initialize">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; + }, z.core.$strip>; + clientInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + }, z.core.$loose>; +}, z.core.$strip>; +export declare const isInitializeRequest: (value: unknown) => value is InitializeRequest; +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ +export declare const ServerCapabilitiesSchema: z.ZodObject<{ + experimental: z.ZodOptional>>; + logging: z.ZodOptional>; + completions: z.ZodOptional>; + prompts: z.ZodOptional; + }, z.core.$strip>>; + resources: z.ZodOptional; + listChanged: z.ZodOptional; + }, z.core.$strip>>; + tools: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$strip>; +/** + * After receiving an initialize request from the client, the server sends this response. + */ +export declare const InitializeResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + logging: z.ZodOptional>; + completions: z.ZodOptional>; + prompts: z.ZodOptional; + }, z.core.$strip>>; + resources: z.ZodOptional; + listChanged: z.ZodOptional; + }, z.core.$strip>>; + tools: z.ZodOptional; + }, z.core.$strip>>; + }, z.core.$strip>; + serverInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + instructions: z.ZodOptional; +}, z.core.$loose>; +/** + * This notification is sent from the client to the server after initialization has finished. + */ +export declare const InitializedNotificationSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/initialized">; +}, z.core.$strip>; +export declare const isInitializedNotification: (value: unknown) => value is InitializedNotification; +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ +export declare const PingRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + method: z.ZodLiteral<"ping">; +}, z.core.$strip>; +export declare const ProgressSchema: z.ZodObject<{ + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; +}, z.core.$strip>; +export declare const ProgressNotificationParamsSchema: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ +export declare const ProgressNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/progress">; + params: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>; +export declare const PaginatedRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; +}, z.core.$loose>; +export declare const PaginatedRequestSchema: z.ZodObject<{ + method: z.ZodString; + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; +}, z.core.$strip>; +export declare const PaginatedResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; +}, z.core.$loose>; +/** + * The contents of a specific resource or sub-resource. + */ +export declare const ResourceContentsSchema: z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$strip>; +export declare const TextResourceContentsSchema: z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + text: z.ZodString; +}, z.core.$strip>; +export declare const BlobResourceContentsSchema: z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; +}, z.core.$strip>; +/** + * A known resource that the server is capable of reading. + */ +export declare const ResourceSchema: z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * A template description for resources available on the server. + */ +export declare const ResourceTemplateSchema: z.ZodObject<{ + uriTemplate: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Sent from the client to request a list of resources the server has. + */ +export declare const ListResourcesRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"resources/list">; +}, z.core.$strip>; +/** + * The server's response to a resources/list request from the client. + */ +export declare const ListResourcesResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + resources: z.ZodArray; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * Sent from the client to request a list of resource templates the server has. + */ +export declare const ListResourceTemplatesRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"resources/templates/list">; +}, z.core.$strip>; +/** + * The server's response to a resources/templates/list request from the client. + */ +export declare const ListResourceTemplatesResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + resourceTemplates: z.ZodArray; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +export declare const ResourceRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$loose>; +/** + * Parameters for a `resources/read` request. + */ +export declare const ReadResourceRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$loose>; +/** + * Sent from the client to the server, to read a specific resource URI. + */ +export declare const ReadResourceRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"resources/read">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * The server's response to a resources/read request from the client. + */ +export declare const ReadResourceResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + contents: z.ZodArray; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>>; +}, z.core.$loose>; +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ +export declare const ResourceListChangedNotificationSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/resources/list_changed">; +}, z.core.$strip>; +export declare const SubscribeRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$loose>; +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + */ +export declare const SubscribeRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"resources/subscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>; +export declare const UnsubscribeRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; +}, z.core.$loose>; +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + */ +export declare const UnsubscribeRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"resources/unsubscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * Parameters for a `notifications/resources/updated` notification. + */ +export declare const ResourceUpdatedNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + uri: z.ZodString; +}, z.core.$loose>; +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + */ +export declare const ResourceUpdatedNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/resources/updated">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * Describes an argument that a prompt can accept. + */ +export declare const PromptArgumentSchema: z.ZodObject<{ + name: z.ZodString; + description: z.ZodOptional; + required: z.ZodOptional; +}, z.core.$strip>; +/** + * A prompt or prompt template that the server offers. + */ +export declare const PromptSchema: z.ZodObject<{ + description: z.ZodOptional; + arguments: z.ZodOptional; + required: z.ZodOptional; + }, z.core.$strip>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ +export declare const ListPromptsRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"prompts/list">; +}, z.core.$strip>; +/** + * The server's response to a prompts/list request from the client. + */ +export declare const ListPromptsResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + prompts: z.ZodArray; + arguments: z.ZodOptional; + required: z.ZodOptional; + }, z.core.$strip>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * Parameters for a `prompts/get` request. + */ +export declare const GetPromptRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; +}, z.core.$loose>; +/** + * Used by the client to get a prompt provided by the server. + */ +export declare const GetPromptRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"prompts/get">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * Text provided to or from an LLM. + */ +export declare const TextContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"text">; + text: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * An image provided to or from an LLM. + */ +export declare const ImageContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * An Audio provided to or from an LLM. + */ +export declare const AudioContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + */ +export declare const ToolUseContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; +}, z.core.$loose>; +/** + * The contents of a resource, embedded into a prompt or tool call result. + */ +export declare const EmbeddedResourceSchema: z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + */ +export declare const ResourceLinkSchema: z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; +}, z.core.$strip>; +/** + * A content block that can be used in prompts and tool results. + */ +export declare const ContentBlockSchema: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; +}, z.core.$strip>]>; +/** + * Describes a message returned as part of a prompt. + */ +export declare const PromptMessageSchema: z.ZodObject<{ + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; +}, z.core.$strip>; +/** + * The server's response to a prompts/get request from the client. + */ +export declare const GetPromptResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + description: z.ZodOptional; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export declare const PromptListChangedNotificationSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/prompts/list_changed">; +}, z.core.$strip>; +/** + * Security scheme indicating no authentication is required. + */ +export declare const NoAuthSecuritySchemeSchema: z.ZodObject<{ + type: z.ZodLiteral<"noauth">; +}, z.core.$strip>; +/** + * Security scheme indicating OAuth 2.0 authentication is required. + */ +export declare const OAuth2SecuritySchemeSchema: z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; +}, z.core.$strip>; +/** + * A security scheme that can be used to authenticate tool calls. + */ +export declare const SecuritySchemeSchema: z.ZodUnion; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; +}, z.core.$strip>]>; +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + */ +export declare const ToolAnnotationsSchema: z.ZodObject<{ + title: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; +}, z.core.$strip>; +/** + * Definition for a tool the client can call. + */ +export declare const ToolSchema: z.ZodObject<{ + description: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + securitySchemes: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; + }, z.core.$strip>]>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; +}, z.core.$strip>; +/** + * Sent from the client to request a list of tools the server has. + */ +export declare const ListToolsRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"tools/list">; +}, z.core.$strip>; +/** + * The server's response to a tools/list request from the client. + */ +export declare const ListToolsResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + tools: z.ZodArray; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + securitySchemes: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; + }, z.core.$strip>]>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * The server's response to a tool call. + */ +export declare const CallToolResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; +}, z.core.$loose>; +/** + * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. + */ +export declare const CompatibilityCallToolResultSchema: z.ZodUnion<[z.ZodObject<{ + _meta: z.ZodOptional>; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + toolResult: z.ZodUnknown; +}, z.core.$loose>]>; +/** + * Parameters for a `tools/call` request. + */ +export declare const CallToolRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; +}, z.core.$loose>; +/** + * Used by the client to invoke a tool provided by the server. + */ +export declare const CallToolRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"tools/call">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export declare const ToolListChangedNotificationSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/tools/list_changed">; +}, z.core.$strip>; +/** + * The severity of a log message. + */ +export declare const LoggingLevelSchema: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; +}>; +/** + * Parameters for a `logging/setLevel` request. + */ +export declare const SetLevelRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; +}, z.core.$loose>; +/** + * A request from the client to the server, to enable or adjust logging. + */ +export declare const SetLevelRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"logging/setLevel">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * Parameters for a `notifications/message` notification. + */ +export declare const LoggingMessageNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + logger: z.ZodOptional; + data: z.ZodUnknown; +}, z.core.$loose>; +/** + * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + */ +export declare const LoggingMessageNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/message">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + logger: z.ZodOptional; + data: z.ZodUnknown; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * Hints to use for model selection. + */ +export declare const ModelHintSchema: z.ZodObject<{ + name: z.ZodOptional; +}, z.core.$strip>; +/** + * The server's preferences for model selection, requested of the client during sampling. + */ +export declare const ModelPreferencesSchema: z.ZodObject<{ + hints: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; +}, z.core.$strip>; +/** + * Controls tool usage behavior in sampling requests. + */ +export declare const ToolChoiceSchema: z.ZodObject<{ + mode: z.ZodOptional>; +}, z.core.$strip>; +/** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via ToolUseContent. + */ +export declare const ToolResultContentSchema: z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$loose>; +/** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + */ +export declare const SamplingMessageContentBlockSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ + type: z.ZodLiteral<"text">; + text: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; +}, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$loose>]>; +/** + * Describes a message issued to or received from an LLM API. + */ +export declare const SamplingMessageSchema: z.ZodObject<{ + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>, z.ZodArray; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>>]>; + _meta: z.ZodOptional>; +}, z.core.$loose>; +/** + * Parameters for a `sampling/createMessage` request. + */ +export declare const CreateMessageRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>, z.ZodArray; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>>]>; + _meta: z.ZodOptional>; + }, z.core.$loose>>; + modelPreferences: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; + }, z.core.$strip>>; + systemPrompt: z.ZodOptional; + includeContext: z.ZodOptional>; + temperature: z.ZodOptional; + maxTokens: z.ZodNumber; + stopSequences: z.ZodOptional>; + metadata: z.ZodOptional>; + tools: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + securitySchemes: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; + }, z.core.$strip>]>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>>; + toolChoice: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + */ +export declare const CreateMessageRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"sampling/createMessage">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>, z.ZodArray; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>>]>; + _meta: z.ZodOptional>; + }, z.core.$loose>>; + modelPreferences: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; + }, z.core.$strip>>; + systemPrompt: z.ZodOptional; + includeContext: z.ZodOptional>; + temperature: z.ZodOptional; + maxTokens: z.ZodNumber; + stopSequences: z.ZodOptional>; + metadata: z.ZodOptional>; + tools: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + securitySchemes: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; + }, z.core.$strip>]>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>>; + toolChoice: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. + */ +export declare const CreateMessageResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + model: z.ZodString; + stopReason: z.ZodOptional, z.ZodString]>>; + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>, z.ZodArray; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>>]>; +}, z.core.$loose>; +/** + * Primitive schema definition for boolean fields. + */ +export declare const BooleanSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Primitive schema definition for string fields. + */ +export declare const StringSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Primitive schema definition for number fields. + */ +export declare const NumberSchemaSchema: z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Schema for single-selection enumeration without display titles for options. + */ +export declare const UntitledSingleSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Schema for single-selection enumeration with display titles for each option. + */ +export declare const TitledSingleSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>; +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + */ +export declare const LegacyTitledEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>; +export declare const SingleSelectEnumSchemaSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>]>; +/** + * Schema for multiple-selection enumeration without display titles for options. + */ +export declare const UntitledMultiSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>; +/** + * Schema for multiple-selection enumeration with display titles for each option. + */ +export declare const TitledMultiSelectEnumSchemaSchema: z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>; +/** + * Combined schema for multiple-selection enumeration + */ +export declare const MultiSelectEnumSchemaSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>]>; +/** + * Primitive schema definition for enum fields. + */ +export declare const EnumSchemaSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>]>]>; +/** + * Union of all primitive schema definitions. + */ +export declare const PrimitiveSchemaDefinitionSchema: z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; +}, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; +}, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; +}, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; +}, z.core.$strip>]>; +/** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ +export declare const ElicitRequestFormParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"form">; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$loose>; +/** + * Parameters for an `elicitation/create` request for URL-based elicitation. + */ +export declare const ElicitRequestURLParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; +}, z.core.$loose>; +/** + * The parameters for a request to elicit additional information from the user via the client. + */ +export declare const ElicitRequestParamsSchema: z.ZodUnion>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"form">; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; +}, z.core.$loose>]>; +/** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ +export declare const ElicitRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"elicitation/create">; + params: z.ZodUnion>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"form">; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; + }, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; + }, z.core.$loose>]>; +}, z.core.$strip>; +/** + * Parameters for a `notifications/elicitation/complete` notification. + * + * @category notifications/elicitation/complete + */ +export declare const ElicitationCompleteNotificationParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + elicitationId: z.ZodString; +}, z.core.$loose>; +/** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ +export declare const ElicitationCompleteNotificationSchema: z.ZodObject<{ + method: z.ZodLiteral<"notifications/elicitation/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + elicitationId: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>; +/** + * The client's response to an elicitation/create request from the server. + */ +export declare const ElicitResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + action: z.ZodEnum<{ + accept: "accept"; + decline: "decline"; + cancel: "cancel"; + }>; + content: z.ZodOptional]>>>; +}, z.core.$loose>; +/** + * A reference to a resource or resource template definition. + */ +export declare const ResourceTemplateReferenceSchema: z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; +}, z.core.$strip>; +/** + * @deprecated Use ResourceTemplateReferenceSchema instead + */ +export declare const ResourceReferenceSchema: z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; +}, z.core.$strip>; +/** + * Identifies a prompt. + */ +export declare const PromptReferenceSchema: z.ZodObject<{ + type: z.ZodLiteral<"ref/prompt">; + name: z.ZodString; +}, z.core.$strip>; +/** + * Parameters for a `completion/complete` request. + */ +export declare const CompleteRequestParamsSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + ref: z.ZodUnion; + name: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; + }, z.core.$strip>]>; + argument: z.ZodObject<{ + name: z.ZodString; + value: z.ZodString; + }, z.core.$strip>; + context: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * A request from the client to the server, to ask for completion options. + */ +export declare const CompleteRequestSchema: z.ZodObject<{ + method: z.ZodLiteral<"completion/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + ref: z.ZodUnion; + name: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; + }, z.core.$strip>]>; + argument: z.ZodObject<{ + name: z.ZodString; + value: z.ZodString; + }, z.core.$strip>; + context: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$loose>; +}, z.core.$strip>; +export declare function assertCompleteRequestPrompt(request: CompleteRequest): asserts request is CompleteRequestPrompt; +export declare function assertCompleteRequestResourceTemplate(request: CompleteRequest): asserts request is CompleteRequestResourceTemplate; +/** + * The server's response to a completion/complete request + */ +export declare const CompleteResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + completion: z.ZodObject<{ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.ZodArray; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.ZodOptional; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.ZodOptional; + }, z.core.$loose>; +}, z.core.$loose>; +/** + * Represents a root directory or file that the server can operate on. + */ +export declare const RootSchema: z.ZodObject<{ + uri: z.ZodString; + name: z.ZodOptional; + _meta: z.ZodOptional>; +}, z.core.$strip>; +/** + * Sent from the server to request a list of root URIs from the client. + */ +export declare const ListRootsRequestSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + method: z.ZodLiteral<"roots/list">; +}, z.core.$strip>; +/** + * The client's response to a roots/list request from the server. + */ +export declare const ListRootsResultSchema: z.ZodObject<{ + _meta: z.ZodOptional>; + roots: z.ZodArray; + _meta: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$loose>; +/** + * A notification from the client to the server, informing it that the list of roots has changed. + */ +export declare const RootsListChangedNotificationSchema: z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/roots/list_changed">; +}, z.core.$strip>; +export declare const ClientRequestSchema: z.ZodUnion>; + }, z.core.$loose>>; + }, z.core.$loose>>; + method: z.ZodLiteral<"ping">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"initialize">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + sampling: z.ZodOptional>; + tools: z.ZodOptional>; + }, z.core.$strip>>; + elicitation: z.ZodOptional, z.ZodIntersection; + }, z.core.$strip>, z.ZodRecord>>; + url: z.ZodOptional>; + }, z.core.$strip>, z.ZodOptional>>>>; + roots: z.ZodOptional; + }, z.core.$strip>>; + }, z.core.$strip>; + clientInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"completion/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + ref: z.ZodUnion; + name: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"ref/resource">; + uri: z.ZodString; + }, z.core.$strip>]>; + argument: z.ZodObject<{ + name: z.ZodString; + value: z.ZodString; + }, z.core.$strip>; + context: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"logging/setLevel">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"prompts/get">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"prompts/list">; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"resources/list">; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"resources/templates/list">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"resources/read">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"resources/subscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"resources/unsubscribe">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"tools/call">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + name: z.ZodString; + arguments: z.ZodOptional>; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + cursor: z.ZodOptional; + }, z.core.$loose>>; + method: z.ZodLiteral<"tools/list">; +}, z.core.$strip>]>; +export declare const ClientNotificationSchema: z.ZodUnion; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + requestId: z.ZodUnion; + reason: z.ZodOptional; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/progress">; + params: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/initialized">; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/roots/list_changed">; +}, z.core.$strip>]>; +export declare const ClientResultSchema: z.ZodUnion>; +}, z.core.$strict>, z.ZodObject<{ + _meta: z.ZodOptional>; + model: z.ZodString; + stopReason: z.ZodOptional, z.ZodString]>>; + role: z.ZodEnum<{ + user: "user"; + assistant: "assistant"; + }>; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>, z.ZodArray; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>>]>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + action: z.ZodEnum<{ + accept: "accept"; + decline: "decline"; + cancel: "cancel"; + }>; + content: z.ZodOptional]>>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + roots: z.ZodArray; + _meta: z.ZodOptional>; + }, z.core.$strip>>; +}, z.core.$loose>]>; +export declare const ServerRequestSchema: z.ZodUnion>; + }, z.core.$loose>>; + }, z.core.$loose>>; + method: z.ZodLiteral<"ping">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"sampling/createMessage">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>, z.ZodArray; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"tool_use">; + name: z.ZodString; + id: z.ZodString; + input: z.ZodObject<{}, z.core.$loose>; + _meta: z.ZodOptional>; + }, z.core.$loose>, z.ZodObject<{ + type: z.ZodLiteral<"tool_result">; + toolUseId: z.ZodString; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$loose>]>>]>; + _meta: z.ZodOptional>; + }, z.core.$loose>>; + modelPreferences: z.ZodOptional; + }, z.core.$strip>>>; + costPriority: z.ZodOptional; + speedPriority: z.ZodOptional; + intelligencePriority: z.ZodOptional; + }, z.core.$strip>>; + systemPrompt: z.ZodOptional; + includeContext: z.ZodOptional>; + temperature: z.ZodOptional; + maxTokens: z.ZodNumber; + stopSequences: z.ZodOptional>; + metadata: z.ZodOptional>; + tools: z.ZodOptional; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + securitySchemes: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; + }, z.core.$strip>]>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>>; + toolChoice: z.ZodOptional>; + }, z.core.$strip>>; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"elicitation/create">; + params: z.ZodUnion>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"form">; + message: z.ZodString; + requestedSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodRecord; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + enumNames: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + enum: z.ZodArray; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + oneOf: z.ZodArray>; + default: z.ZodOptional; + }, z.core.$strip>]>, z.ZodUnion; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + type: z.ZodLiteral<"string">; + enum: z.ZodArray; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"array">; + title: z.ZodOptional; + description: z.ZodOptional; + minItems: z.ZodOptional; + maxItems: z.ZodOptional; + items: z.ZodObject<{ + anyOf: z.ZodArray>; + }, z.core.$strip>; + default: z.ZodOptional>; + }, z.core.$strip>]>]>, z.ZodObject<{ + type: z.ZodLiteral<"boolean">; + title: z.ZodOptional; + description: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"string">; + title: z.ZodOptional; + description: z.ZodOptional; + minLength: z.ZodOptional; + maxLength: z.ZodOptional; + format: z.ZodOptional>; + default: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodEnum<{ + number: "number"; + integer: "integer"; + }>; + title: z.ZodOptional; + description: z.ZodOptional; + minimum: z.ZodOptional; + maximum: z.ZodOptional; + default: z.ZodOptional; + }, z.core.$strip>]>>; + required: z.ZodOptional>; + }, z.core.$strip>; + }, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + }, z.core.$loose>>; + mode: z.ZodLiteral<"url">; + message: z.ZodString; + elicitationId: z.ZodString; + url: z.ZodString; + }, z.core.$loose>]>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + }, z.core.$loose>>; + method: z.ZodLiteral<"roots/list">; +}, z.core.$strip>]>; +export declare const ServerNotificationSchema: z.ZodUnion; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + requestId: z.ZodUnion; + reason: z.ZodOptional; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/progress">; + params: z.ZodObject<{ + progressToken: z.ZodUnion; + progress: z.ZodNumber; + total: z.ZodOptional; + message: z.ZodOptional; + _meta: z.ZodOptional>; + }, z.core.$strip>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/message">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + level: z.ZodEnum<{ + error: "error"; + debug: "debug"; + info: "info"; + notice: "notice"; + warning: "warning"; + critical: "critical"; + alert: "alert"; + emergency: "emergency"; + }>; + logger: z.ZodOptional; + data: z.ZodUnknown; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/resources/updated">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + uri: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/resources/list_changed">; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/tools/list_changed">; +}, z.core.$strip>, z.ZodObject<{ + params: z.ZodOptional>; + }, z.core.$loose>>; + method: z.ZodLiteral<"notifications/prompts/list_changed">; +}, z.core.$strip>, z.ZodObject<{ + method: z.ZodLiteral<"notifications/elicitation/complete">; + params: z.ZodObject<{ + _meta: z.ZodOptional>; + elicitationId: z.ZodString; + }, z.core.$loose>; +}, z.core.$strip>]>; +export declare const ServerResultSchema: z.ZodUnion>; +}, z.core.$strict>, z.ZodObject<{ + _meta: z.ZodOptional>; + protocolVersion: z.ZodString; + capabilities: z.ZodObject<{ + experimental: z.ZodOptional>>; + logging: z.ZodOptional>; + completions: z.ZodOptional>; + prompts: z.ZodOptional; + }, z.core.$strip>>; + resources: z.ZodOptional; + listChanged: z.ZodOptional; + }, z.core.$strip>>; + tools: z.ZodOptional; + }, z.core.$strip>>; + }, z.core.$strip>; + serverInfo: z.ZodObject<{ + version: z.ZodString; + websiteUrl: z.ZodOptional; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>; + instructions: z.ZodOptional; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + completion: z.ZodObject<{ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.ZodArray; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.ZodOptional; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.ZodOptional; + }, z.core.$loose>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + description: z.ZodOptional; + messages: z.ZodArray; + content: z.ZodUnion; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + prompts: z.ZodArray; + arguments: z.ZodOptional; + required: z.ZodOptional; + }, z.core.$strip>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + resources: z.ZodArray; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + resourceTemplates: z.ZodArray; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + contents: z.ZodArray; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>>; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + content: z.ZodDefault; + text: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"image">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"audio">; + data: z.ZodString; + mimeType: z.ZodString; + _meta: z.ZodOptional>; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + description: z.ZodOptional; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + type: z.ZodLiteral<"resource_link">; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"resource">; + resource: z.ZodUnion; + _meta: z.ZodOptional>; + text: z.ZodString; + }, z.core.$strip>, z.ZodObject<{ + uri: z.ZodString; + mimeType: z.ZodOptional; + _meta: z.ZodOptional>; + blob: z.ZodString; + }, z.core.$strip>]>; + _meta: z.ZodOptional>; + }, z.core.$strip>]>>>; + structuredContent: z.ZodOptional>; + isError: z.ZodOptional; +}, z.core.$loose>, z.ZodObject<{ + _meta: z.ZodOptional>; + nextCursor: z.ZodOptional; + tools: z.ZodArray; + inputSchema: z.ZodObject<{ + type: z.ZodLiteral<"object">; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>; + outputSchema: z.ZodOptional; + properties: z.ZodOptional>>; + required: z.ZodOptional>; + }, z.core.$catchall>>; + annotations: z.ZodOptional; + readOnlyHint: z.ZodOptional; + destructiveHint: z.ZodOptional; + idempotentHint: z.ZodOptional; + openWorldHint: z.ZodOptional; + }, z.core.$strip>>; + securitySchemes: z.ZodOptional; + }, z.core.$strip>, z.ZodObject<{ + type: z.ZodLiteral<"oauth2">; + scopes: z.ZodOptional>; + }, z.core.$strip>]>>>; + _meta: z.ZodOptional>; + icons: z.ZodOptional; + sizes: z.ZodOptional>; + }, z.core.$strip>>>; + name: z.ZodString; + title: z.ZodOptional; + }, z.core.$strip>>; +}, z.core.$loose>]>; +export declare class McpError extends Error { + readonly code: number; + readonly data?: unknown; + constructor(code: number, message: string, data?: unknown); + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code: number, message: string, data?: unknown): McpError; +} +/** + * Specialized error type when a tool requires a URL mode elicitation. + * 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. + */ +export declare class UrlElicitationRequiredError extends McpError { + constructor(elicitations: ElicitRequestURLParams[], message?: string); + get elicitations(): ElicitRequestURLParams[]; +} +type Primitive = string | number | boolean | bigint | null | undefined; +type Flatten = T extends Primitive ? T : T extends Array ? Array> : T extends Set ? Set> : T extends Map ? Map, Flatten> : T extends object ? { + [K in keyof T]: Flatten; +} : T; +type Infer = Flatten>; +/** + * Headers that are compatible with both Node.js and the browser. + */ +export type IsomorphicHeaders = Record; +/** + * Information about the incoming request. + */ +export interface RequestInfo { + /** + * The headers of the request. + */ + headers: IsomorphicHeaders; +} +/** + * Extra information about a message. + */ +export interface MessageExtraInfo { + /** + * The request information. + */ + requestInfo?: RequestInfo; + /** + * The authentication information. + */ + authInfo?: AuthInfo; +} +export type ProgressToken = Infer; +export type Cursor = Infer; +export type Request = Infer; +export type RequestMeta = Infer; +export type Notification = Infer; +export type Result = Infer; +export type RequestId = Infer; +export type JSONRPCRequest = Infer; +export type JSONRPCNotification = Infer; +export type JSONRPCResponse = Infer; +export type JSONRPCError = Infer; +export type JSONRPCMessage = Infer; +export type RequestParams = Infer; +export type NotificationParams = Infer; +export type EmptyResult = Infer; +export type CancelledNotificationParams = Infer; +export type CancelledNotification = Infer; +export type Icon = Infer; +export type Icons = Infer; +export type BaseMetadata = Infer; +export type Implementation = Infer; +export type ClientCapabilities = Infer; +export type InitializeRequestParams = Infer; +export type InitializeRequest = Infer; +export type ServerCapabilities = Infer; +export type InitializeResult = Infer; +export type InitializedNotification = Infer; +export type PingRequest = Infer; +export type Progress = Infer; +export type ProgressNotificationParams = Infer; +export type ProgressNotification = Infer; +export type PaginatedRequestParams = Infer; +export type PaginatedRequest = Infer; +export type PaginatedResult = Infer; +export type ResourceContents = Infer; +export type TextResourceContents = Infer; +export type BlobResourceContents = Infer; +export type Resource = Infer; +export type ResourceTemplate = Infer; +export type ListResourcesRequest = Infer; +export type ListResourcesResult = Infer; +export type ListResourceTemplatesRequest = Infer; +export type ListResourceTemplatesResult = Infer; +export type ResourceRequestParams = Infer; +export type ReadResourceRequestParams = Infer; +export type ReadResourceRequest = Infer; +export type ReadResourceResult = Infer; +export type ResourceListChangedNotification = Infer; +export type SubscribeRequestParams = Infer; +export type SubscribeRequest = Infer; +export type UnsubscribeRequestParams = Infer; +export type UnsubscribeRequest = Infer; +export type ResourceUpdatedNotificationParams = Infer; +export type ResourceUpdatedNotification = Infer; +export type PromptArgument = Infer; +export type Prompt = Infer; +export type ListPromptsRequest = Infer; +export type ListPromptsResult = Infer; +export type GetPromptRequestParams = Infer; +export type GetPromptRequest = Infer; +export type TextContent = Infer; +export type ImageContent = Infer; +export type AudioContent = Infer; +export type ToolUseContent = Infer; +export type ToolResultContent = Infer; +export type EmbeddedResource = Infer; +export type ResourceLink = Infer; +export type ContentBlock = Infer; +export type PromptMessage = Infer; +export type GetPromptResult = Infer; +export type PromptListChangedNotification = Infer; +export type NoAuthSecurityScheme = Infer; +export type OAuth2SecurityScheme = Infer; +export type SecurityScheme = Infer; +export type ToolAnnotations = Infer; +export type Tool = Infer; +export type ListToolsRequest = Infer; +export type ListToolsResult = Infer; +export type CallToolRequestParams = Infer; +export type CallToolResult = Infer; +export type CompatibilityCallToolResult = Infer; +export type CallToolRequest = Infer; +export type ToolListChangedNotification = Infer; +export type LoggingLevel = Infer; +export type SetLevelRequestParams = Infer; +export type SetLevelRequest = Infer; +export type LoggingMessageNotificationParams = Infer; +export type LoggingMessageNotification = Infer; +export type ToolChoice = Infer; +export type ModelHint = Infer; +export type ModelPreferences = Infer; +export type SamplingMessageContentBlock = Infer; +export type SamplingMessage = Infer; +export type CreateMessageRequestParams = Infer; +export type CreateMessageRequest = Infer; +export type CreateMessageResult = Infer; +export type BooleanSchema = Infer; +export type StringSchema = Infer; +export type NumberSchema = Infer; +export type EnumSchema = Infer; +export type UntitledSingleSelectEnumSchema = Infer; +export type TitledSingleSelectEnumSchema = Infer; +export type LegacyTitledEnumSchema = Infer; +export type UntitledMultiSelectEnumSchema = Infer; +export type TitledMultiSelectEnumSchema = Infer; +export type SingleSelectEnumSchema = Infer; +export type MultiSelectEnumSchema = Infer; +export type PrimitiveSchemaDefinition = Infer; +export type ElicitRequestParams = Infer; +export type ElicitRequestFormParams = Infer; +export type ElicitRequestURLParams = Infer; +export type ElicitRequest = Infer; +export type ElicitationCompleteNotificationParams = Infer; +export type ElicitationCompleteNotification = Infer; +export type ElicitResult = Infer; +export type ResourceTemplateReference = Infer; +/** + * @deprecated Use ResourceTemplateReference instead + */ +export type ResourceReference = ResourceTemplateReference; +export type PromptReference = Infer; +export type CompleteRequestParams = Infer; +export type CompleteRequest = Infer; +export type CompleteRequestResourceTemplate = ExpandRecursively; +export type CompleteRequestPrompt = ExpandRecursively; +export type CompleteResult = Infer; +export type Root = Infer; +export type ListRootsRequest = Infer; +export type ListRootsResult = Infer; +export type RootsListChangedNotification = Infer; +export type ClientRequest = Infer; +export type ClientNotification = Infer; +export type ClientResult = Infer; +export type ServerRequest = Infer; +export type ServerNotification = Infer; +export type ServerResult = Infer; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/esm/types.d.ts.map b/dist/esm/types.d.ts.map new file mode 100644 index 0000000000..39761f83d0 --- /dev/null +++ b/dist/esm/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE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eAAe,GAAG;IAAE,MAAM,EAAE,qBAAqB,GAAG;QAAE,GAAG,EAAE,eAAe,CAAA;KAAE,CAAA;CAAE,CAAC,CAAC;AACtI,MAAM,MAAM,cAAc,GAAG,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAGhE,MAAM,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,UAAU,CAAC,CAAC;AAC5C,MAAM,MAAM,gBAAgB,GAAG,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AACpE,MAAM,MAAM,eAAe,GAAG,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAClE,MAAM,MAAM,4BAA4B,GAAG,KAAK,CAAC,OAAO,kCAAkC,CAAC,CAAC;AAG5F,MAAM,MAAM,aAAa,GAAG,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAC9D,MAAM,MAAM,kBAAkB,GAAG,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;AACxE,MAAM,MAAM,YAAY,GAAG,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAG5D,MAAM,MAAM,aAAa,GAAG,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAC9D,MAAM,MAAM,kBAAkB,GAAG,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;AACxE,MAAM,MAAM,YAAY,GAAG,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/types.js b/dist/esm/types.js new file mode 100644 index 0000000000..933121d8c3 --- /dev/null +++ b/dist/esm/types.js @@ -0,0 +1,1659 @@ +import * as z from 'zod/v4'; +export const LATEST_PROTOCOL_VERSION = '2025-06-18'; +export const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26'; +export const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-03-26', '2024-11-05', '2024-10-07']; +/* JSON-RPC types */ +export const JSONRPC_VERSION = '2.0'; +/** + * Assert 'object' type schema. + * + * @internal + */ +const AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function')); +/** + * A progress token, used to associate progress notifications with the original request. + */ +export const ProgressTokenSchema = z.union([z.string(), z.number().int()]); +/** + * An opaque token used to represent a cursor for pagination. + */ +export const CursorSchema = z.string(); +const RequestMetaSchema = z.looseObject({ + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken: ProgressTokenSchema.optional() +}); +/** + * Common params for any request. + */ +const BaseRequestParamsSchema = z.looseObject({ + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta: RequestMetaSchema.optional() +}); +export const RequestSchema = z.object({ + method: z.string(), + params: BaseRequestParamsSchema.optional() +}); +const NotificationsParamsSchema = z.looseObject({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +export const NotificationSchema = z.object({ + method: z.string(), + params: NotificationsParamsSchema.optional() +}); +export const ResultSchema = z.looseObject({ + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * A uniquely identifying ID for a request in JSON-RPC. + */ +export const RequestIdSchema = z.union([z.string(), z.number().int()]); +/** + * A request that expects a response. + */ +export const JSONRPCRequestSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + id: RequestIdSchema, + ...RequestSchema.shape +}) + .strict(); +export const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; +/** + * A notification which does not expect a response. + */ +export const JSONRPCNotificationSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + ...NotificationSchema.shape +}) + .strict(); +export const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; +/** + * A successful (non-error) response to a request. + */ +export const JSONRPCResponseSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema +}) + .strict(); +export const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; +/** + * Error codes defined by the JSON-RPC specification. + */ +export var ErrorCode; +(function (ErrorCode) { + // SDK error codes + ErrorCode[ErrorCode["ConnectionClosed"] = -32000] = "ConnectionClosed"; + ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout"; + // Standard JSON-RPC error codes + ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError"; + ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest"; + ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound"; + ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams"; + ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError"; + // MCP-specific error codes + ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; +})(ErrorCode || (ErrorCode = {})); +/** + * A response to a request that indicates an error occurred. + */ +export const JSONRPCErrorSchema = z + .object({ + jsonrpc: z.literal(JSONRPC_VERSION), + id: RequestIdSchema, + error: z.object({ + /** + * The error type that occurred. + */ + code: z.number().int(), + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: z.string(), + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data: z.optional(z.unknown()) + }) +}) + .strict(); +export const isJSONRPCError = (value) => JSONRPCErrorSchema.safeParse(value).success; +export const JSONRPCMessageSchema = z.union([JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResponseSchema, JSONRPCErrorSchema]); +/* Empty result */ +/** + * A response that indicates success but carries no data. + */ +export const EmptyResultSchema = ResultSchema.strict(); +export const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestIdSchema, + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason: z.string().optional() +}); +/* Cancellation */ +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + */ +export const CancelledNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/cancelled'), + params: CancelledNotificationParamsSchema +}); +/* Base Metadata */ +/** + * Icon schema for use in tools, prompts, resources, and implementations. + */ +export const IconSchema = z.object({ + /** + * URL or data URI for the icon. + */ + src: z.string(), + /** + * Optional MIME type for the icon. + */ + mimeType: z.string().optional(), + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes: z.array(z.string()).optional() +}); +/** + * Base schema to add `icons` property. + * + */ +export const IconsSchema = z.object({ + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons: z.array(IconSchema).optional() +}); +/** + * Base metadata interface for common properties across resources, tools, prompts, and implementations. + */ +export const BaseMetadataSchema = z.object({ + /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ + name: z.string(), + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title: z.string().optional() +}); +/* Initialization */ +/** + * Describes the name and version of an MCP implementation. + */ +export const ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: z.string(), + /** + * An optional URL of the website for this implementation. + */ + websiteUrl: z.string().optional() +}); +const FormElicitationCapabilitySchema = z.intersection(z.object({ + applyDefaults: z.boolean().optional() +}), z.record(z.string(), z.unknown())); +const ElicitationCapabilitySchema = z.preprocess(value => { + if (value && typeof value === 'object' && !Array.isArray(value)) { + if (Object.keys(value).length === 0) { + return { form: {} }; + } + } + return value; +}, z.intersection(z.object({ + form: FormElicitationCapabilitySchema.optional(), + url: AssertObjectSchema.optional() +}), z.record(z.string(), z.unknown()).optional())); +/** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ +export const ClientCapabilitiesSchema = z.object({ + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental: z.record(z.string(), AssertObjectSchema).optional(), + /** + * Present if the client supports sampling from an LLM. + */ + sampling: z + .object({ + /** + * Present if the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context: AssertObjectSchema.optional(), + /** + * Present if the client supports tool use via tools and toolChoice parameters. + */ + tools: AssertObjectSchema.optional() + }) + .optional(), + /** + * Present if the client supports eliciting user input. + */ + elicitation: ElicitationCapabilitySchema.optional(), + /** + * Present if the client supports listing roots. + */ + roots: z + .object({ + /** + * Whether the client supports issuing notifications for changes to the roots list. + */ + listChanged: z.boolean().optional() + }) + .optional() +}); +export const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: z.string(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema +}); +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ +export const InitializeRequestSchema = RequestSchema.extend({ + method: z.literal('initialize'), + params: InitializeRequestParamsSchema +}); +export const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; +/** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ +export const ServerCapabilitiesSchema = z.object({ + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental: z.record(z.string(), AssertObjectSchema).optional(), + /** + * Present if the server supports sending log messages to the client. + */ + logging: AssertObjectSchema.optional(), + /** + * Present if the server supports sending completions to the client. + */ + completions: AssertObjectSchema.optional(), + /** + * Present if the server offers any prompt templates. + */ + prompts: z.optional(z.object({ + /** + * Whether this server supports issuing notifications for changes to the prompt list. + */ + listChanged: z.optional(z.boolean()) + })), + /** + * Present if the server offers any resources to read. + */ + resources: z + .object({ + /** + * Whether this server supports clients subscribing to resource updates. + */ + subscribe: z.boolean().optional(), + /** + * Whether this server supports issuing notifications for changes to the resource list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server offers any tools to call. + */ + tools: z + .object({ + /** + * Whether this server supports issuing notifications for changes to the tool list. + */ + listChanged: z.boolean().optional() + }) + .optional() +}); +/** + * After receiving an initialize request from the client, the server sends this response. + */ +export const InitializeResultSchema = ResultSchema.extend({ + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: z.string(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions: z.string().optional() +}); +/** + * This notification is sent from the client to the server after initialization has finished. + */ +export const InitializedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/initialized') +}); +export const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; +/* Ping */ +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ +export const PingRequestSchema = RequestSchema.extend({ + method: z.literal('ping') +}); +/* Progress notifications */ +export const ProgressSchema = z.object({ + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + */ + progress: z.number(), + /** + * Total number of items to process (or total progress required), if known. + */ + total: z.optional(z.number()), + /** + * An optional message describing the current progress. + */ + message: z.optional(z.string()) +}); +export const ProgressNotificationParamsSchema = z.object({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressTokenSchema +}); +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ +export const ProgressNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/progress'), + params: ProgressNotificationParamsSchema +}); +export const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor: CursorSchema.optional() +}); +/* Pagination */ +export const PaginatedRequestSchema = RequestSchema.extend({ + params: PaginatedRequestParamsSchema.optional() +}); +export const PaginatedResultSchema = ResultSchema.extend({ + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor: z.optional(CursorSchema) +}); +/* Resources */ +/** + * The contents of a specific resource or sub-resource. + */ +export const ResourceContentsSchema = z.object({ + /** + * The URI of this resource. + */ + uri: z.string(), + /** + * The MIME type of this resource, if known. + */ + mimeType: z.optional(z.string()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +export const TextResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: z.string() +}); +/** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ +const Base64Schema = z.string().refine(val => { + try { + // atob throws a DOMException if the string contains characters + // that are not part of the Base64 character set. + atob(val); + return true; + } + catch (_a) { + return false; + } +}, { message: 'Invalid Base64 string' }); +export const BlobResourceContentsSchema = ResourceContentsSchema.extend({ + /** + * A base64-encoded string representing the binary data of the item. + */ + blob: Base64Schema +}); +/** + * A known resource that the server is capable of reading. + */ +export const ResourceSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * The URI of this resource. + */ + uri: z.string(), + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: z.optional(z.string()), + /** + * The MIME type of this resource, if known. + */ + mimeType: z.optional(z.string()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.looseObject({})) +}); +/** + * A template description for resources available on the server. + */ +export const ResourceTemplateSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + */ + uriTemplate: z.string(), + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description: z.optional(z.string()), + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType: z.optional(z.string()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.looseObject({})) +}); +/** + * Sent from the client to request a list of resources the server has. + */ +export const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('resources/list') +}); +/** + * The server's response to a resources/list request from the client. + */ +export const ListResourcesResultSchema = PaginatedResultSchema.extend({ + resources: z.array(ResourceSchema) +}); +/** + * Sent from the client to request a list of resource templates the server has. + */ +export const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('resources/templates/list') +}); +/** + * The server's response to a resources/templates/list request from the client. + */ +export const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ + resourceTemplates: z.array(ResourceTemplateSchema) +}); +export const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: z.string() +}); +/** + * Parameters for a `resources/read` request. + */ +export const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; +/** + * Sent from the client to the server, to read a specific resource URI. + */ +export const ReadResourceRequestSchema = RequestSchema.extend({ + method: z.literal('resources/read'), + params: ReadResourceRequestParamsSchema +}); +/** + * The server's response to a resources/read request from the client. + */ +export const ReadResourceResultSchema = ResultSchema.extend({ + contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) +}); +/** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ +export const ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/resources/list_changed') +}); +export const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + */ +export const SubscribeRequestSchema = RequestSchema.extend({ + method: z.literal('resources/subscribe'), + params: SubscribeRequestParamsSchema +}); +export const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + */ +export const UnsubscribeRequestSchema = RequestSchema.extend({ + method: z.literal('resources/unsubscribe'), + params: UnsubscribeRequestParamsSchema +}); +/** + * Parameters for a `notifications/resources/updated` notification. + */ +export const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + */ + uri: z.string() +}); +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + */ +export const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/resources/updated'), + params: ResourceUpdatedNotificationParamsSchema +}); +/* Prompts */ +/** + * Describes an argument that a prompt can accept. + */ +export const PromptArgumentSchema = z.object({ + /** + * The name of the argument. + */ + name: z.string(), + /** + * A human-readable description of the argument. + */ + description: z.optional(z.string()), + /** + * Whether this argument must be provided. + */ + required: z.optional(z.boolean()) +}); +/** + * A prompt or prompt template that the server offers. + */ +export const PromptSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * An optional description of what this prompt provides + */ + description: z.optional(z.string()), + /** + * A list of arguments to use for templating the prompt. + */ + arguments: z.optional(z.array(PromptArgumentSchema)), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.looseObject({})) +}); +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ +export const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('prompts/list') +}); +/** + * The server's response to a prompts/list request from the client. + */ +export const ListPromptsResultSchema = PaginatedResultSchema.extend({ + prompts: z.array(PromptSchema) +}); +/** + * Parameters for a `prompts/get` request. + */ +export const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The name of the prompt or prompt template. + */ + name: z.string(), + /** + * Arguments to use for templating the prompt. + */ + arguments: z.record(z.string(), z.string()).optional() +}); +/** + * Used by the client to get a prompt provided by the server. + */ +export const GetPromptRequestSchema = RequestSchema.extend({ + method: z.literal('prompts/get'), + params: GetPromptRequestParamsSchema +}); +/** + * Text provided to or from an LLM. + */ +export const TextContentSchema = z.object({ + type: z.literal('text'), + /** + * The text content of the message. + */ + text: z.string(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * An image provided to or from an LLM. + */ +export const ImageContentSchema = z.object({ + type: z.literal('image'), + /** + * The base64-encoded image data. + */ + data: Base64Schema, + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: z.string(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * An Audio provided to or from an LLM. + */ +export const AudioContentSchema = z.object({ + type: z.literal('audio'), + /** + * The base64-encoded audio data. + */ + data: Base64Schema, + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: z.string(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + */ +export const ToolUseContentSchema = z + .object({ + type: z.literal('tool_use'), + /** + * The name of the tool to invoke. + * Must match a tool name from the request's tools array. + */ + name: z.string(), + /** + * Unique identifier for this tool call. + * Used to correlate with ToolResultContent in subsequent messages. + */ + id: z.string(), + /** + * Arguments to pass to the tool. + * Must conform to the tool's inputSchema. + */ + input: z.object({}).passthrough(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()) +}) + .passthrough(); +/** + * The contents of a resource, embedded into a prompt or tool call result. + */ +export const EmbeddedResourceSchema = z.object({ + type: z.literal('resource'), + resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + */ +export const ResourceLinkSchema = ResourceSchema.extend({ + type: z.literal('resource_link') +}); +/** + * A content block that can be used in prompts and tool results. + */ +export const ContentBlockSchema = z.union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema +]); +/** + * Describes a message returned as part of a prompt. + */ +export const PromptMessageSchema = z.object({ + role: z.enum(['user', 'assistant']), + content: ContentBlockSchema +}); +/** + * The server's response to a prompts/get request from the client. + */ +export const GetPromptResultSchema = ResultSchema.extend({ + /** + * An optional description for the prompt. + */ + description: z.optional(z.string()), + messages: z.array(PromptMessageSchema) +}); +/** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export const PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/prompts/list_changed') +}); +/* Tools */ +/** + * Security scheme indicating no authentication is required. + */ +export const NoAuthSecuritySchemeSchema = z.object({ + type: z.literal('noauth') +}); +/** + * Security scheme indicating OAuth 2.0 authentication is required. + */ +export const OAuth2SecuritySchemeSchema = z.object({ + type: z.literal('oauth2'), + /** + * Optional list of OAuth 2.0 scopes required for this tool. + */ + scopes: z + .array(z.string().min(1)) + .refine((arr) => new Set(arr).size === arr.length, { + message: 'Scopes must be unique' + }) + .optional() +}); +/** + * A security scheme that can be used to authenticate tool calls. + */ +export const SecuritySchemeSchema = z.union([NoAuthSecuritySchemeSchema, OAuth2SecuritySchemeSchema]); +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + */ +export const ToolAnnotationsSchema = z.object({ + /** + * A human-readable title for the tool. + */ + title: z.string().optional(), + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint: z.boolean().optional(), + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint: z.boolean().optional(), + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on the its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint: z.boolean().optional(), + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint: z.boolean().optional() +}); +/** + * Definition for a tool the client can call. + */ +export const ToolSchema = z.object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + /** + * A human-readable description of the tool. + */ + description: z.string().optional(), + /** + * A JSON Schema 2020-12 object defining the expected parameters for the tool. + * Must have type: 'object' at the root level per MCP spec. + */ + inputSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), AssertObjectSchema).optional(), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()), + /** + * An optional JSON Schema 2020-12 object defining the structure of the tool's output + * returned in the structuredContent field of a CallToolResult. + * Must have type: 'object' at the root level per MCP spec. + */ + outputSchema: z + .object({ + type: z.literal('object'), + properties: z.record(z.string(), AssertObjectSchema).optional(), + required: z.array(z.string()).optional() + }) + .catchall(z.unknown()) + .optional(), + /** + * Optional additional tool information. + */ + annotations: z.optional(ToolAnnotationsSchema), + /** + * Optional list of security schemes supported by this tool. + * If missing, the tool follows the server's default authentication policy. + * If present, lists the supported authentication schemes (e.g., "noauth", "oauth2"). + */ + securitySchemes: z.array(SecuritySchemeSchema).optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Sent from the client to request a list of tools the server has. + */ +export const ListToolsRequestSchema = PaginatedRequestSchema.extend({ + method: z.literal('tools/list') +}); +/** + * The server's response to a tools/list request from the client. + */ +export const ListToolsResultSchema = PaginatedResultSchema.extend({ + tools: z.array(ToolSchema) +}); +/** + * The server's response to a tool call. + */ +export const CallToolResultSchema = ResultSchema.extend({ + /** + * A list of content objects that represent the result of the tool call. + * + * If the Tool does not define an outputSchema, this field MUST be present in the result. + * For backwards compatibility, this field is always present, but it may be empty. + */ + content: z.array(ContentBlockSchema).default([]), + /** + * An object containing structured tool output. + * + * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. + */ + structuredContent: z.record(z.string(), z.unknown()).optional(), + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError: z.optional(z.boolean()) +}); +/** + * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. + */ +export const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ + toolResult: z.unknown() +})); +/** + * Parameters for a `tools/call` request. + */ +export const CallToolRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The name of the tool to call. + */ + name: z.string(), + /** + * Arguments to pass to the tool. + */ + arguments: z.optional(z.record(z.string(), z.unknown())) +}); +/** + * Used by the client to invoke a tool provided by the server. + */ +export const CallToolRequestSchema = RequestSchema.extend({ + method: z.literal('tools/call'), + params: CallToolRequestParamsSchema +}); +/** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ +export const ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/tools/list_changed') +}); +/* Logging */ +/** + * The severity of a log message. + */ +export const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); +/** + * Parameters for a `logging/setLevel` request. + */ +export const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. + */ + level: LoggingLevelSchema +}); +/** + * A request from the client to the server, to enable or adjust logging. + */ +export const SetLevelRequestSchema = RequestSchema.extend({ + method: z.literal('logging/setLevel'), + params: SetLevelRequestParamsSchema +}); +/** + * Parameters for a `notifications/message` notification. + */ +export const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The severity of this log message. + */ + level: LoggingLevelSchema, + /** + * An optional name of the logger issuing this message. + */ + logger: z.string().optional(), + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: z.unknown() +}); +/** + * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + */ +export const LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/message'), + params: LoggingMessageNotificationParamsSchema +}); +/* Sampling */ +/** + * Hints to use for model selection. + */ +export const ModelHintSchema = z.object({ + /** + * A hint for a model name. + */ + name: z.string().optional() +}); +/** + * The server's preferences for model selection, requested of the client during sampling. + */ +export const ModelPreferencesSchema = z.object({ + /** + * Optional hints to use for model selection. + */ + hints: z.optional(z.array(ModelHintSchema)), + /** + * How much to prioritize cost when selecting a model. + */ + costPriority: z.optional(z.number().min(0).max(1)), + /** + * How much to prioritize sampling speed (latency) when selecting a model. + */ + speedPriority: z.optional(z.number().min(0).max(1)), + /** + * How much to prioritize intelligence and capabilities when selecting a model. + */ + intelligencePriority: z.optional(z.number().min(0).max(1)) +}); +/** + * Controls tool usage behavior in sampling requests. + */ +export const ToolChoiceSchema = z.object({ + /** + * Controls when tools are used: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode: z.optional(z.enum(['auto', 'required', 'none'])) +}); +/** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via ToolUseContent. + */ +export const ToolResultContentSchema = z + .object({ + type: z.literal('tool_result'), + toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'), + content: z.array(ContentBlockSchema).default([]), + structuredContent: z.object({}).passthrough().optional(), + isError: z.optional(z.boolean()), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()) +}) + .passthrough(); +/** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + */ +export const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema +]); +/** + * Describes a message issued to or received from an LLM API. + */ +export const SamplingMessageSchema = z + .object({ + role: z.enum(['user', 'assistant']), + content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()) +}) + .passthrough(); +/** + * Parameters for a `sampling/createMessage` request. + */ +export const CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({ + messages: z.array(SamplingMessageSchema), + /** + * The server's preferences for which model to select. The client MAY modify or omit this request. + */ + modelPreferences: ModelPreferencesSchema.optional(), + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt: z.string().optional(), + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(), + temperature: z.number().optional(), + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: z.number().int(), + stopSequences: z.array(z.string()).optional(), + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata: AssertObjectSchema.optional(), + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools: z.optional(z.array(ToolSchema)), + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice: z.optional(ToolChoiceSchema) +}); +/** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + */ +export const CreateMessageRequestSchema = RequestSchema.extend({ + method: z.literal('sampling/createMessage'), + params: CreateMessageRequestParamsSchema +}); +/** + * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. + */ +export const CreateMessageResultSchema = ResultSchema.extend({ + /** + * The name of the model that generated the message. + */ + model: z.string(), + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())), + role: z.enum(['user', 'assistant']), + /** + * Response content. May be ToolUseContent if stopReason is "toolUse". + */ + content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]) +}); +/* Elicitation */ +/** + * Primitive schema definition for boolean fields. + */ +export const BooleanSchemaSchema = z.object({ + type: z.literal('boolean'), + title: z.string().optional(), + description: z.string().optional(), + default: z.boolean().optional() +}); +/** + * Primitive schema definition for string fields. + */ +export const StringSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + minLength: z.number().optional(), + maxLength: z.number().optional(), + format: z.enum(['email', 'uri', 'date', 'date-time']).optional(), + default: z.string().optional() +}); +/** + * Primitive schema definition for number fields. + */ +export const NumberSchemaSchema = z.object({ + type: z.enum(['number', 'integer']), + title: z.string().optional(), + description: z.string().optional(), + minimum: z.number().optional(), + maximum: z.number().optional(), + default: z.number().optional() +}); +/** + * Schema for single-selection enumeration without display titles for options. + */ +export const UntitledSingleSelectEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + enum: z.array(z.string()), + default: z.string().optional() +}); +/** + * Schema for single-selection enumeration with display titles for each option. + */ +export const TitledSingleSelectEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + oneOf: z.array(z.object({ + const: z.string(), + title: z.string() + })), + default: z.string().optional() +}); +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + */ +export const LegacyTitledEnumSchemaSchema = z.object({ + type: z.literal('string'), + title: z.string().optional(), + description: z.string().optional(), + enum: z.array(z.string()), + enumNames: z.array(z.string()).optional(), + default: z.string().optional() +}); +// Combined single selection enumeration +export const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); +/** + * Schema for multiple-selection enumeration without display titles for options. + */ +export const UntitledMultiSelectEnumSchemaSchema = z.object({ + type: z.literal('array'), + title: z.string().optional(), + description: z.string().optional(), + minItems: z.number().optional(), + maxItems: z.number().optional(), + items: z.object({ + type: z.literal('string'), + enum: z.array(z.string()) + }), + default: z.array(z.string()).optional() +}); +/** + * Schema for multiple-selection enumeration with display titles for each option. + */ +export const TitledMultiSelectEnumSchemaSchema = z.object({ + type: z.literal('array'), + title: z.string().optional(), + description: z.string().optional(), + minItems: z.number().optional(), + maxItems: z.number().optional(), + items: z.object({ + anyOf: z.array(z.object({ + const: z.string(), + title: z.string() + })) + }), + default: z.array(z.string()).optional() +}); +/** + * Combined schema for multiple-selection enumeration + */ +export const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); +/** + * Primitive schema definition for enum fields. + */ +export const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); +/** + * Union of all primitive schema definitions. + */ +export const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); +/** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ +export const ElicitRequestFormParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The elicitation mode. + */ + mode: z.literal('form'), + /** + * The message to present to the user describing what information is being requested. + */ + message: z.string(), + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: z.object({ + type: z.literal('object'), + properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema), + required: z.array(z.string()).optional() + }) +}); +/** + * Parameters for an `elicitation/create` request for URL-based elicitation. + */ +export const ElicitRequestURLParamsSchema = BaseRequestParamsSchema.extend({ + /** + * The elicitation mode. + */ + mode: z.literal('url'), + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: z.string(), + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: z.string(), + /** + * The URL that the user should navigate to. + */ + url: z.string().url() +}); +/** + * The parameters for a request to elicit additional information from the user via the client. + */ +export const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); +/** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ +export const ElicitRequestSchema = RequestSchema.extend({ + method: z.literal('elicitation/create'), + params: ElicitRequestParamsSchema +}); +/** + * Parameters for a `notifications/elicitation/complete` notification. + * + * @category notifications/elicitation/complete + */ +export const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ + /** + * The ID of the elicitation that completed. + */ + elicitationId: z.string() +}); +/** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ +export const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/elicitation/complete'), + params: ElicitationCompleteNotificationParamsSchema +}); +/** + * The client's response to an elicitation/create request from the server. + */ +export const ElicitResultSchema = ResultSchema.extend({ + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: z.enum(['accept', 'decline', 'cancel']), + /** + * The submitted form data, only present when action is "accept". + * Contains values matching the requested schema. + */ + content: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional() +}); +/* Autocomplete */ +/** + * A reference to a resource or resource template definition. + */ +export const ResourceTemplateReferenceSchema = z.object({ + type: z.literal('ref/resource'), + /** + * The URI or URI template of the resource. + */ + uri: z.string() +}); +/** + * @deprecated Use ResourceTemplateReferenceSchema instead + */ +export const ResourceReferenceSchema = ResourceTemplateReferenceSchema; +/** + * Identifies a prompt. + */ +export const PromptReferenceSchema = z.object({ + type: z.literal('ref/prompt'), + /** + * The name of the prompt or prompt template + */ + name: z.string() +}); +/** + * Parameters for a `completion/complete` request. + */ +export const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + /** + * The argument's information + */ + argument: z.object({ + /** + * The name of the argument + */ + name: z.string(), + /** + * The value of the argument to use for completion matching. + */ + value: z.string() + }), + context: z + .object({ + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments: z.record(z.string(), z.string()).optional() + }) + .optional() +}); +/** + * A request from the client to the server, to ask for completion options. + */ +export const CompleteRequestSchema = RequestSchema.extend({ + method: z.literal('completion/complete'), + params: CompleteRequestParamsSchema +}); +export function assertCompleteRequestPrompt(request) { + if (request.params.ref.type !== 'ref/prompt') { + throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); + } + void request; +} +export function assertCompleteRequestResourceTemplate(request) { + if (request.params.ref.type !== 'ref/resource') { + throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); + } + void request; +} +/** + * The server's response to a completion/complete request + */ +export const CompleteResultSchema = ResultSchema.extend({ + completion: z.looseObject({ + /** + * An array of completion values. Must not exceed 100 items. + */ + values: z.array(z.string()).max(100), + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total: z.optional(z.number().int()), + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore: z.optional(z.boolean()) + }) +}); +/* Roots */ +/** + * Represents a root directory or file that the server can operate on. + */ +export const RootSchema = z.object({ + /** + * The URI identifying the root. This *must* start with file:// for now. + */ + uri: z.string().startsWith('file://'), + /** + * An optional name for the root. + */ + name: z.string().optional(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.record(z.string(), z.unknown()).optional() +}); +/** + * Sent from the server to request a list of root URIs from the client. + */ +export const ListRootsRequestSchema = RequestSchema.extend({ + method: z.literal('roots/list') +}); +/** + * The client's response to a roots/list request from the server. + */ +export const ListRootsResultSchema = ResultSchema.extend({ + roots: z.array(RootSchema) +}); +/** + * A notification from the client to the server, informing it that the list of roots has changed. + */ +export const RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: z.literal('notifications/roots/list_changed') +}); +/* Client messages */ +export const ClientRequestSchema = z.union([ + PingRequestSchema, + InitializeRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema +]); +export const ClientNotificationSchema = z.union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + InitializedNotificationSchema, + RootsListChangedNotificationSchema +]); +export const ClientResultSchema = z.union([EmptyResultSchema, CreateMessageResultSchema, ElicitResultSchema, ListRootsResultSchema]); +/* Server messages */ +export const ServerRequestSchema = z.union([PingRequestSchema, CreateMessageRequestSchema, ElicitRequestSchema, ListRootsRequestSchema]); +export const ServerNotificationSchema = z.union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + ElicitationCompleteNotificationSchema +]); +export const ServerResultSchema = z.union([ + EmptyResultSchema, + InitializeResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + CallToolResultSchema, + ListToolsResultSchema +]); +export class McpError extends Error { + constructor(code, message, data) { + super(`MCP error ${code}: ${message}`); + this.code = code; + this.data = data; + this.name = 'McpError'; + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + // Check for specific error types + if (code === ErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) { + return new UrlElicitationRequiredError(errorData.elicitations, message); + } + } + // Default to generic McpError + return new McpError(code, message, data); + } +} +/** + * Specialized error type when a tool requires a URL mode elicitation. + * 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. + */ +export class UrlElicitationRequiredError extends McpError { + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) { + super(ErrorCode.UrlElicitationRequired, message, { + elicitations: elicitations + }); + } + get elicitations() { + var _a, _b; + return (_b = (_a = this.data) === null || _a === void 0 ? void 0 : _a.elicitations) !== null && _b !== void 0 ? _b : []; + } +} +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/esm/types.js.map b/dist/esm/types.js.map new file mode 100644 index 0000000000..cfb037901e --- /dev/null +++ b/dist/esm/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAG5B,MAAM,CAAC,MAAM,uBAAuB,GAAG,YAAY,CAAC;AACpD,MAAM,CAAC,MAAM,mCAAmC,GAAG,YAAY,CAAC;AAChE,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,uBAAuB,EAAE,YAAY,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC;AAE/G,oBAAoB;AACpB,MAAM,CAAC,MAAM,eAAe,GAAG,KAAK,CAAC;AAMrC;;;;GAIG;AACH,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAS,CAAC,CAAC,EAAe,EAAE,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,UAAU,CAAC,CAAC,CAAC;AAClI;;GAEG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,CAA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AC;YACpD,MAAM,SAAS,GAAG,IAAoC,CAAC;YACvD,IAAI,SAAS,CAAC,YAAY,EAAE,CAAC;gBACzB,OAAO,IAAI,2BAA2B,CAAC,SAAS,CAAC,YAAwC,EAAE,OAAO,CAAC,CAAC;YACxG,CAAC;QACL,CAAC;QAED,8BAA8B;QAC9B,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC7C,CAAC;CACJ;AAED;;;GAGG;AACH,MAAM,OAAO,2BAA4B,SAAQ,QAAQ;IACrD,YAAY,YAAsC,EAAE,UAAkB,kBAAkB,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,WAAW;QACjI,KAAK,CAAC,SAAS,CAAC,sBAAsB,EAAE,OAAO,EAAE;YAC7C,YAAY,EAAE,YAAY;SAC7B,CAAC,CAAC;IACP,CAAC;IAED,IAAI,YAAY;;QACZ,OAAO,MAAA,MAAC,IAAI,CAAC,IAAmD,0CAAE,YAAY,mCAAI,EAAE,CAAC;IACzF,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/validation/ajv-provider.d.ts b/dist/esm/validation/ajv-provider.d.ts new file mode 100644 index 0000000000..43e24ffc93 --- /dev/null +++ b/dist/esm/validation/ajv-provider.d.ts @@ -0,0 +1,53 @@ +/** + * AJV-based JSON Schema validator provider + */ +import { Ajv } from 'ajv'; +import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from './types.js'; +/** + * @example + * ```typescript + * // Use with default AJV instance (recommended) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Use with custom AJV instance + * import { Ajv } from 'ajv'; + * const ajv = new Ajv({ strict: true, allErrors: true }); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ +export declare class AjvJsonSchemaValidator implements jsonSchemaValidator { + private _ajv; + /** + * Create an AJV validator + * + * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. + * + * @example + * ```typescript + * // Use default configuration (recommended for most cases) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Or provide custom AJV instance for advanced configuration + * import { Ajv } from 'ajv'; + * import addFormats from 'ajv-formats'; + * + * const ajv = new Ajv({ validateFormats: true }); + * addFormats(ajv); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ + constructor(ajv?: Ajv); + /** + * Create a validator for the given JSON Schema + * + * The validator is compiled once and can be reused multiple times. + * If the schema has an $id, it will be cached by AJV automatically. + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema: JsonSchemaType): JsonSchemaValidator; +} +//# sourceMappingURL=ajv-provider.d.ts.map \ No newline at end of file diff --git a/dist/esm/validation/ajv-provider.d.ts.map b/dist/esm/validation/ajv-provider.d.ts.map new file mode 100644 index 0000000000..4e955a3b32 --- /dev/null +++ b/dist/esm/validation/ajv-provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"ajv-provider.d.ts","sourceRoot":"","sources":["../../../src/validation/ajv-provider.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAE1B,OAAO,KAAK,EAAE,cAAc,EAAE,mBAAmB,EAA6B,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAgBtH;;;;;;;;;;;;GAYG;AACH,qBAAa,sBAAuB,YAAW,mBAAmB;IAC9D,OAAO,CAAC,IAAI,CAAM;IAElB;;;;;;;;;;;;;;;;;;;OAmBG;gBACS,GAAG,CAAC,EAAE,GAAG;IAIrB;;;;;;;;OAQG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC;CAyBlE"} \ No newline at end of file diff --git a/dist/esm/validation/ajv-provider.js b/dist/esm/validation/ajv-provider.js new file mode 100644 index 0000000000..02762f0c1d --- /dev/null +++ b/dist/esm/validation/ajv-provider.js @@ -0,0 +1,88 @@ +/** + * AJV-based JSON Schema validator provider + */ +import { Ajv } from 'ajv'; +import _addFormats from 'ajv-formats'; +function createDefaultAjvInstance() { + const ajv = new Ajv({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + const addFormats = _addFormats; + addFormats(ajv); + return ajv; +} +/** + * @example + * ```typescript + * // Use with default AJV instance (recommended) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Use with custom AJV instance + * import { Ajv } from 'ajv'; + * const ajv = new Ajv({ strict: true, allErrors: true }); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ +export class AjvJsonSchemaValidator { + /** + * Create an AJV validator + * + * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. + * + * @example + * ```typescript + * // Use default configuration (recommended for most cases) + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // Or provide custom AJV instance for advanced configuration + * import { Ajv } from 'ajv'; + * import addFormats from 'ajv-formats'; + * + * const ajv = new Ajv({ validateFormats: true }); + * addFormats(ajv); + * const validator = new AjvJsonSchemaValidator(ajv); + * ``` + */ + constructor(ajv) { + this._ajv = ajv !== null && ajv !== void 0 ? ajv : createDefaultAjvInstance(); + } + /** + * Create a validator for the given JSON Schema + * + * The validator is compiled once and can be reused multiple times. + * If the schema has an $id, it will be cached by AJV automatically. + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema) { + var _a; + // Check if schema has $id and is already compiled/cached + const ajvValidator = '$id' in schema && typeof schema.$id === 'string' + ? ((_a = this._ajv.getSchema(schema.$id)) !== null && _a !== void 0 ? _a : this._ajv.compile(schema)) + : this._ajv.compile(schema); + return (input) => { + const valid = ajvValidator(input); + if (valid) { + return { + valid: true, + data: input, + errorMessage: undefined + }; + } + else { + return { + valid: false, + data: undefined, + errorMessage: this._ajv.errorsText(ajvValidator.errors) + }; + } + }; + } +} +//# sourceMappingURL=ajv-provider.js.map \ No newline at end of file diff --git a/dist/esm/validation/ajv-provider.js.map b/dist/esm/validation/ajv-provider.js.map new file mode 100644 index 0000000000..ce7e5d0c95 --- /dev/null +++ b/dist/esm/validation/ajv-provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ajv-provider.js","sourceRoot":"","sources":["../../../src/validation/ajv-provider.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAC1B,OAAO,WAAW,MAAM,aAAa,CAAC;AAGtC,SAAS,wBAAwB;IAC7B,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC;QAChB,MAAM,EAAE,KAAK;QACb,eAAe,EAAE,IAAI;QACrB,cAAc,EAAE,KAAK;QACrB,SAAS,EAAE,IAAI;KAClB,CAAC,CAAC;IAEH,MAAM,UAAU,GAAG,WAAoD,CAAC;IACxE,UAAU,CAAC,GAAG,CAAC,CAAC;IAEhB,OAAO,GAAG,CAAC;AACf,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,OAAO,sBAAsB;IAG/B;;;;;;;;;;;;;;;;;;;OAmBG;IACH,YAAY,GAAS;QACjB,IAAI,CAAC,IAAI,GAAG,GAAG,aAAH,GAAG,cAAH,GAAG,GAAI,wBAAwB,EAAE,CAAC;IAClD,CAAC;IAED;;;;;;;;OAQG;IACH,YAAY,CAAI,MAAsB;;QAClC,yDAAyD;QACzD,MAAM,YAAY,GACd,KAAK,IAAI,MAAM,IAAI,OAAO,MAAM,CAAC,GAAG,KAAK,QAAQ;YAC7C,CAAC,CAAC,CAAC,MAAA,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,mCAAI,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YAChE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAEpC,OAAO,CAAC,KAAc,EAAgC,EAAE;YACpD,MAAM,KAAK,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;YAElC,IAAI,KAAK,EAAE,CAAC;gBACR,OAAO;oBACH,KAAK,EAAE,IAAI;oBACX,IAAI,EAAE,KAAU;oBAChB,YAAY,EAAE,SAAS;iBAC1B,CAAC;YACN,CAAC;iBAAM,CAAC;gBACJ,OAAO;oBACH,KAAK,EAAE,KAAK;oBACZ,IAAI,EAAE,SAAS;oBACf,YAAY,EAAE,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,MAAM,CAAC;iBAC1D,CAAC;YACN,CAAC;QACL,CAAC,CAAC;IACN,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/validation/cfworker-provider.d.ts b/dist/esm/validation/cfworker-provider.d.ts new file mode 100644 index 0000000000..89c244a609 --- /dev/null +++ b/dist/esm/validation/cfworker-provider.d.ts @@ -0,0 +1,51 @@ +/** + * Cloudflare Worker-compatible JSON Schema validator provider + * + * This provider uses @cfworker/json-schema for validation without code generation, + * making it compatible with edge runtimes like Cloudflare Workers that restrict + * eval and new Function. + */ +import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from './types.js'; +/** + * JSON Schema draft version supported by @cfworker/json-schema + */ +export type CfWorkerSchemaDraft = '4' | '7' | '2019-09' | '2020-12'; +/** + * + * @example + * ```typescript + * // Use with default configuration (2020-12, shortcircuit) + * const validator = new CfWorkerJsonSchemaValidator(); + * + * // Use with custom configuration + * const validator = new CfWorkerJsonSchemaValidator({ + * draft: '2020-12', + * shortcircuit: false // Report all errors + * }); + * ``` + */ +export declare class CfWorkerJsonSchemaValidator implements jsonSchemaValidator { + private shortcircuit; + private draft; + /** + * Create a validator + * + * @param options - Configuration options + * @param options.shortcircuit - If true, stop validation after first error (default: true) + * @param options.draft - JSON Schema draft version to use (default: '2020-12') + */ + constructor(options?: { + shortcircuit?: boolean; + draft?: CfWorkerSchemaDraft; + }); + /** + * Create a validator for the given JSON Schema + * + * Unlike AJV, this validator is not cached internally + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema: JsonSchemaType): JsonSchemaValidator; +} +//# sourceMappingURL=cfworker-provider.d.ts.map \ No newline at end of file diff --git a/dist/esm/validation/cfworker-provider.d.ts.map b/dist/esm/validation/cfworker-provider.d.ts.map new file mode 100644 index 0000000000..ce404d92fc --- /dev/null +++ b/dist/esm/validation/cfworker-provider.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"cfworker-provider.d.ts","sourceRoot":"","sources":["../../../src/validation/cfworker-provider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,mBAAmB,EAA6B,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtH;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG,GAAG,GAAG,GAAG,GAAG,SAAS,GAAG,SAAS,CAAC;AAEpE;;;;;;;;;;;;;GAaG;AACH,qBAAa,2BAA4B,YAAW,mBAAmB;IACnE,OAAO,CAAC,YAAY,CAAU;IAC9B,OAAO,CAAC,KAAK,CAAsB;IAEnC;;;;;;OAMG;gBACS,OAAO,CAAC,EAAE;QAAE,YAAY,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,mBAAmB,CAAA;KAAE;IAK7E;;;;;;;OAOG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC;CAsBlE"} \ No newline at end of file diff --git a/dist/esm/validation/cfworker-provider.js b/dist/esm/validation/cfworker-provider.js new file mode 100644 index 0000000000..d55ef011e3 --- /dev/null +++ b/dist/esm/validation/cfworker-provider.js @@ -0,0 +1,66 @@ +/** + * Cloudflare Worker-compatible JSON Schema validator provider + * + * This provider uses @cfworker/json-schema for validation without code generation, + * making it compatible with edge runtimes like Cloudflare Workers that restrict + * eval and new Function. + */ +import { Validator } from '@cfworker/json-schema'; +/** + * + * @example + * ```typescript + * // Use with default configuration (2020-12, shortcircuit) + * const validator = new CfWorkerJsonSchemaValidator(); + * + * // Use with custom configuration + * const validator = new CfWorkerJsonSchemaValidator({ + * draft: '2020-12', + * shortcircuit: false // Report all errors + * }); + * ``` + */ +export class CfWorkerJsonSchemaValidator { + /** + * Create a validator + * + * @param options - Configuration options + * @param options.shortcircuit - If true, stop validation after first error (default: true) + * @param options.draft - JSON Schema draft version to use (default: '2020-12') + */ + constructor(options) { + var _a, _b; + this.shortcircuit = (_a = options === null || options === void 0 ? void 0 : options.shortcircuit) !== null && _a !== void 0 ? _a : true; + this.draft = (_b = options === null || options === void 0 ? void 0 : options.draft) !== null && _b !== void 0 ? _b : '2020-12'; + } + /** + * Create a validator for the given JSON Schema + * + * Unlike AJV, this validator is not cached internally + * + * @param schema - Standard JSON Schema object + * @returns A validator function that validates input data + */ + getValidator(schema) { + const cfSchema = schema; + const validator = new Validator(cfSchema, this.draft, this.shortcircuit); + return (input) => { + const result = validator.validate(input); + if (result.valid) { + return { + valid: true, + data: input, + errorMessage: undefined + }; + } + else { + return { + valid: false, + data: undefined, + errorMessage: result.errors.map(err => `${err.instanceLocation}: ${err.error}`).join('; ') + }; + } + }; + } +} +//# sourceMappingURL=cfworker-provider.js.map \ No newline at end of file diff --git a/dist/esm/validation/cfworker-provider.js.map b/dist/esm/validation/cfworker-provider.js.map new file mode 100644 index 0000000000..0f0e1799f8 --- /dev/null +++ b/dist/esm/validation/cfworker-provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"cfworker-provider.js","sourceRoot":"","sources":["../../../src/validation/cfworker-provider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAe,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAQ/D;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO,2BAA2B;IAIpC;;;;;;OAMG;IACH,YAAY,OAAiE;;QACzE,IAAI,CAAC,YAAY,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,mCAAI,IAAI,CAAC;QAClD,IAAI,CAAC,KAAK,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,KAAK,mCAAI,SAAS,CAAC;IAC7C,CAAC;IAED;;;;;;;OAOG;IACH,YAAY,CAAI,MAAsB;QAClC,MAAM,QAAQ,GAAG,MAA2B,CAAC;QAC7C,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC,QAAQ,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;QAEzE,OAAO,CAAC,KAAc,EAAgC,EAAE;YACpD,MAAM,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;YAEzC,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;gBACf,OAAO;oBACH,KAAK,EAAE,IAAI;oBACX,IAAI,EAAE,KAAU;oBAChB,YAAY,EAAE,SAAS;iBAC1B,CAAC;YACN,CAAC;iBAAM,CAAC;gBACJ,OAAO;oBACH,KAAK,EAAE,KAAK;oBACZ,IAAI,EAAE,SAAS;oBACf,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,gBAAgB,KAAK,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;iBAC7F,CAAC;YACN,CAAC;QACL,CAAC,CAAC;IACN,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/validation/index.d.ts b/dist/esm/validation/index.d.ts new file mode 100644 index 0000000000..99e993967f --- /dev/null +++ b/dist/esm/validation/index.d.ts @@ -0,0 +1,29 @@ +/** + * JSON Schema validation + * + * This module provides configurable JSON Schema validation for the MCP SDK. + * Choose a validator based on your runtime environment: + * + * - AjvJsonSchemaValidator: Best for Node.js (default, fastest) + * Import from: @modelcontextprotocol/sdk/validation/ajv + * Requires peer dependencies: ajv, ajv-formats + * + * - CfWorkerJsonSchemaValidator: Best for edge runtimes + * Import from: @modelcontextprotocol/sdk/validation/cfworker + * Requires peer dependency: @cfworker/json-schema + * + * @example + * ```typescript + * // For Node.js with AJV + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // For Cloudflare Workers + * import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker'; + * const validator = new CfWorkerJsonSchemaValidator(); + * ``` + * + * @module validation + */ +export type { JsonSchemaType, JsonSchemaValidator, JsonSchemaValidatorResult, jsonSchemaValidator } from './types.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/esm/validation/index.d.ts.map b/dist/esm/validation/index.d.ts.map new file mode 100644 index 0000000000..a8845b96e7 --- /dev/null +++ b/dist/esm/validation/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/validation/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAGH,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC"} \ No newline at end of file diff --git a/dist/esm/validation/index.js b/dist/esm/validation/index.js new file mode 100644 index 0000000000..685b1fd45f --- /dev/null +++ b/dist/esm/validation/index.js @@ -0,0 +1,29 @@ +/** + * JSON Schema validation + * + * This module provides configurable JSON Schema validation for the MCP SDK. + * Choose a validator based on your runtime environment: + * + * - AjvJsonSchemaValidator: Best for Node.js (default, fastest) + * Import from: @modelcontextprotocol/sdk/validation/ajv + * Requires peer dependencies: ajv, ajv-formats + * + * - CfWorkerJsonSchemaValidator: Best for edge runtimes + * Import from: @modelcontextprotocol/sdk/validation/cfworker + * Requires peer dependency: @cfworker/json-schema + * + * @example + * ```typescript + * // For Node.js with AJV + * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; + * const validator = new AjvJsonSchemaValidator(); + * + * // For Cloudflare Workers + * import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker'; + * const validator = new CfWorkerJsonSchemaValidator(); + * ``` + * + * @module validation + */ +export {}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/esm/validation/index.js.map b/dist/esm/validation/index.js.map new file mode 100644 index 0000000000..ed2b9fc234 --- /dev/null +++ b/dist/esm/validation/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/validation/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG"} \ No newline at end of file diff --git a/dist/esm/validation/types.d.ts b/dist/esm/validation/types.d.ts new file mode 100644 index 0000000000..5872215c78 --- /dev/null +++ b/dist/esm/validation/types.d.ts @@ -0,0 +1,55 @@ +import type { Schema } from '@cfworker/json-schema'; +/** + * Result of a JSON Schema validation operation + */ +export type JsonSchemaValidatorResult = { + valid: true; + data: T; + errorMessage: undefined; +} | { + valid: false; + data: undefined; + errorMessage: string; +}; +/** + * A validator function that validates data against a JSON Schema + */ +export type JsonSchemaValidator = (input: unknown) => JsonSchemaValidatorResult; +/** + * Provider interface for creating validators from JSON Schemas + * + * This is the main extension point for custom validator implementations. + * Implementations should: + * - Support JSON Schema Draft 2020-12 (or be compatible with it) + * - Return validator functions that can be called multiple times + * - Handle schema compilation/caching internally + * - Provide clear error messages on validation failure + * + * @example + * ```typescript + * class MyValidatorProvider implements jsonSchemaValidator { + * getValidator(schema: JsonSchemaType): JsonSchemaValidator { + * // Compile/cache validator from schema + * return (input: unknown) => { + * // Validate input against schema + * if (valid) { + * return { valid: true, data: input as T, errorMessage: undefined }; + * } else { + * return { valid: false, data: undefined, errorMessage: 'Error details' }; + * } + * }; + * } + * } + * ``` + */ +export interface jsonSchemaValidator { + /** + * Create a validator for the given JSON Schema + * + * @param schema - Standard JSON Schema object + * @returns A validator function that can be called multiple times + */ + getValidator(schema: JsonSchemaType): JsonSchemaValidator; +} +export type JsonSchemaType = Schema; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/esm/validation/types.d.ts.map b/dist/esm/validation/types.d.ts.map new file mode 100644 index 0000000000..3bdf64e589 --- /dev/null +++ b/dist/esm/validation/types.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/validation/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAEpD;;GAEG;AACH,MAAM,MAAM,yBAAyB,CAAC,CAAC,IACjC;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,CAAC,CAAC;IAAC,YAAY,EAAE,SAAS,CAAA;CAAE,GACjD;IAAE,KAAK,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,SAAS,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC;AAE9D;;GAEG;AACH,MAAM,MAAM,mBAAmB,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,KAAK,yBAAyB,CAAC,CAAC,CAAC,CAAC;AAEtF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,WAAW,mBAAmB;IAChC;;;;;OAKG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAAC;CACnE;AAED,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/dist/esm/validation/types.js b/dist/esm/validation/types.js new file mode 100644 index 0000000000..718fd38ae4 --- /dev/null +++ b/dist/esm/validation/types.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/esm/validation/types.js.map b/dist/esm/validation/types.js.map new file mode 100644 index 0000000000..51361cf6a4 --- /dev/null +++ b/dist/esm/validation/types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/validation/types.ts"],"names":[],"mappings":""} \ No newline at end of file From d5373fe924b2664bf417491acd6ccd4f18f17e61 Mon Sep 17 00:00:00 2001 From: Mikko Kutilainen Date: Sat, 22 Nov 2025 22:24:10 +0200 Subject: [PATCH 3/9] remove dist --- dist/cjs/client/auth.d.ts | 280 -- dist/cjs/client/auth.d.ts.map | 1 - dist/cjs/client/auth.js | 799 --- dist/cjs/client/auth.js.map | 1 - dist/cjs/client/index.d.ts | 379 -- dist/cjs/client/index.d.ts.map | 1 - dist/cjs/client/index.js | 423 -- dist/cjs/client/index.js.map | 1 - dist/cjs/client/middleware.d.ts | 169 - dist/cjs/client/middleware.d.ts.map | 1 - dist/cjs/client/middleware.js | 252 - dist/cjs/client/middleware.js.map | 1 - dist/cjs/client/sse.d.ts | 81 - dist/cjs/client/sse.d.ts.map | 1 - dist/cjs/client/sse.js | 213 - dist/cjs/client/sse.js.map | 1 - dist/cjs/client/stdio.d.ts | 78 - dist/cjs/client/stdio.d.ts.map | 1 - dist/cjs/client/stdio.js | 184 - dist/cjs/client/stdio.js.map | 1 - dist/cjs/client/streamableHttp.d.ts | 159 - dist/cjs/client/streamableHttp.d.ts.map | 1 - dist/cjs/client/streamableHttp.js | 426 -- dist/cjs/client/streamableHttp.js.map | 1 - dist/cjs/client/websocket.d.ts | 17 - dist/cjs/client/websocket.d.ts.map | 1 - dist/cjs/client/websocket.js | 63 - dist/cjs/client/websocket.js.map | 1 - .../client/elicitationUrlExample.d.ts | 2 - .../client/elicitationUrlExample.d.ts.map | 1 - .../examples/client/elicitationUrlExample.js | 693 --- .../client/elicitationUrlExample.js.map | 1 - .../client/multipleClientsParallel.d.ts | 2 - .../client/multipleClientsParallel.d.ts.map | 1 - .../client/multipleClientsParallel.js | 134 - .../client/multipleClientsParallel.js.map | 1 - .../client/parallelToolCallsClient.d.ts | 2 - .../client/parallelToolCallsClient.d.ts.map | 1 - .../client/parallelToolCallsClient.js | 176 - .../client/parallelToolCallsClient.js.map | 1 - .../examples/client/simpleOAuthClient.d.ts | 3 - .../client/simpleOAuthClient.d.ts.map | 1 - dist/cjs/examples/client/simpleOAuthClient.js | 337 -- .../examples/client/simpleOAuthClient.js.map | 1 - .../client/simpleOAuthClientProvider.d.ts | 26 - .../client/simpleOAuthClientProvider.d.ts.map | 1 - .../client/simpleOAuthClientProvider.js | 51 - .../client/simpleOAuthClientProvider.js.map | 1 - .../examples/client/simpleStreamableHttp.d.ts | 2 - .../client/simpleStreamableHttp.d.ts.map | 1 - .../examples/client/simpleStreamableHttp.js | 749 --- .../client/simpleStreamableHttp.js.map | 1 - .../streamableHttpWithSseFallbackClient.d.ts | 2 - ...reamableHttpWithSseFallbackClient.d.ts.map | 1 - .../streamableHttpWithSseFallbackClient.js | 168 - ...streamableHttpWithSseFallbackClient.js.map | 1 - .../server/demoInMemoryOAuthProvider.d.ts | 78 - .../server/demoInMemoryOAuthProvider.d.ts.map | 1 - .../server/demoInMemoryOAuthProvider.js | 205 - .../server/demoInMemoryOAuthProvider.js.map | 1 - .../server/elicitationFormExample.d.ts | 2 - .../server/elicitationFormExample.d.ts.map | 1 - .../examples/server/elicitationFormExample.js | 441 -- .../server/elicitationFormExample.js.map | 1 - .../server/elicitationUrlExample.d.ts | 2 - .../server/elicitationUrlExample.d.ts.map | 1 - .../examples/server/elicitationUrlExample.js | 655 --- .../server/elicitationUrlExample.js.map | 1 - .../server/jsonResponseStreamableHttp.d.ts | 2 - .../jsonResponseStreamableHttp.d.ts.map | 1 - .../server/jsonResponseStreamableHttp.js | 175 - .../server/jsonResponseStreamableHttp.js.map | 1 - .../server/mcpServerOutputSchema.d.ts | 7 - .../server/mcpServerOutputSchema.d.ts.map | 1 - .../examples/server/mcpServerOutputSchema.js | 95 - .../server/mcpServerOutputSchema.js.map | 1 - dist/cjs/examples/server/simpleSseServer.d.ts | 2 - .../examples/server/simpleSseServer.d.ts.map | 1 - dist/cjs/examples/server/simpleSseServer.js | 169 - .../examples/server/simpleSseServer.js.map | 1 - .../server/simpleStatelessStreamableHttp.d.ts | 2 - .../simpleStatelessStreamableHttp.d.ts.map | 1 - .../server/simpleStatelessStreamableHttp.js | 170 - .../simpleStatelessStreamableHttp.js.map | 1 - .../examples/server/simpleStreamableHttp.d.ts | 2 - .../server/simpleStreamableHttp.d.ts.map | 1 - .../examples/server/simpleStreamableHttp.js | 611 --- .../server/simpleStreamableHttp.js.map | 1 - .../sseAndStreamableHttpCompatibleServer.d.ts | 2 - ...AndStreamableHttpCompatibleServer.d.ts.map | 1 - .../sseAndStreamableHttpCompatibleServer.js | 263 - ...seAndStreamableHttpCompatibleServer.js.map | 1 - .../standaloneSseWithGetStreamableHttp.d.ts | 2 - ...tandaloneSseWithGetStreamableHttp.d.ts.map | 1 - .../standaloneSseWithGetStreamableHttp.js | 116 - .../standaloneSseWithGetStreamableHttp.js.map | 1 - .../examples/server/toolWithSampleServer.d.ts | 2 - .../server/toolWithSampleServer.d.ts.map | 1 - .../examples/server/toolWithSampleServer.js | 71 - .../server/toolWithSampleServer.js.map | 1 - .../examples/shared/inMemoryEventStore.d.ts | 31 - .../shared/inMemoryEventStore.d.ts.map | 1 - .../cjs/examples/shared/inMemoryEventStore.js | 69 - .../examples/shared/inMemoryEventStore.js.map | 1 - dist/cjs/inMemory.d.ts | 31 - dist/cjs/inMemory.d.ts.map | 1 - dist/cjs/inMemory.js | 53 - dist/cjs/inMemory.js.map | 1 - dist/cjs/package.json | 1 - dist/cjs/server/auth/clients.d.ts | 19 - dist/cjs/server/auth/clients.d.ts.map | 1 - dist/cjs/server/auth/clients.js | 3 - dist/cjs/server/auth/clients.js.map | 1 - dist/cjs/server/auth/errors.d.ts | 141 - dist/cjs/server/auth/errors.d.ts.map | 1 - dist/cjs/server/auth/errors.js | 193 - dist/cjs/server/auth/errors.js.map | 1 - dist/cjs/server/auth/handlers/authorize.d.ts | 13 - .../server/auth/handlers/authorize.d.ts.map | 1 - dist/cjs/server/auth/handlers/authorize.js | 167 - .../cjs/server/auth/handlers/authorize.js.map | 1 - dist/cjs/server/auth/handlers/metadata.d.ts | 4 - .../server/auth/handlers/metadata.d.ts.map | 1 - dist/cjs/server/auth/handlers/metadata.js | 21 - dist/cjs/server/auth/handlers/metadata.js.map | 1 - dist/cjs/server/auth/handlers/register.d.ts | 29 - .../server/auth/handlers/register.d.ts.map | 1 - dist/cjs/server/auth/handlers/register.js | 77 - dist/cjs/server/auth/handlers/register.js.map | 1 - dist/cjs/server/auth/handlers/revoke.d.ts | 13 - dist/cjs/server/auth/handlers/revoke.d.ts.map | 1 - dist/cjs/server/auth/handlers/revoke.js | 65 - dist/cjs/server/auth/handlers/revoke.js.map | 1 - dist/cjs/server/auth/handlers/token.d.ts | 13 - dist/cjs/server/auth/handlers/token.d.ts.map | 1 - dist/cjs/server/auth/handlers/token.js | 136 - dist/cjs/server/auth/handlers/token.js.map | 1 - .../auth/middleware/allowedMethods.d.ts | 9 - .../auth/middleware/allowedMethods.d.ts.map | 1 - .../server/auth/middleware/allowedMethods.js | 21 - .../auth/middleware/allowedMethods.js.map | 1 - .../server/auth/middleware/bearerAuth.d.ts | 35 - .../auth/middleware/bearerAuth.d.ts.map | 1 - dist/cjs/server/auth/middleware/bearerAuth.js | 75 - .../server/auth/middleware/bearerAuth.js.map | 1 - .../server/auth/middleware/clientAuth.d.ts | 19 - .../auth/middleware/clientAuth.d.ts.map | 1 - dist/cjs/server/auth/middleware/clientAuth.js | 75 - .../server/auth/middleware/clientAuth.js.map | 1 - dist/cjs/server/auth/provider.d.ts | 68 - dist/cjs/server/auth/provider.d.ts.map | 1 - dist/cjs/server/auth/provider.js | 3 - dist/cjs/server/auth/provider.js.map | 1 - .../server/auth/providers/proxyProvider.d.ts | 49 - .../auth/providers/proxyProvider.d.ts.map | 1 - .../server/auth/providers/proxyProvider.js | 161 - .../auth/providers/proxyProvider.js.map | 1 - dist/cjs/server/auth/router.d.ts | 101 - dist/cjs/server/auth/router.d.ts.map | 1 - dist/cjs/server/auth/router.js | 125 - dist/cjs/server/auth/router.js.map | 1 - dist/cjs/server/auth/types.d.ts | 32 - dist/cjs/server/auth/types.d.ts.map | 1 - dist/cjs/server/auth/types.js | 3 - dist/cjs/server/auth/types.js.map | 1 - dist/cjs/server/completable.d.ts | 38 - dist/cjs/server/completable.d.ts.map | 1 - dist/cjs/server/completable.js | 48 - dist/cjs/server/completable.js.map | 1 - dist/cjs/server/index.d.ts | 333 -- dist/cjs/server/index.d.ts.map | 1 - dist/cjs/server/index.js | 304 -- dist/cjs/server/index.js.map | 1 - dist/cjs/server/mcp.d.ts | 332 -- dist/cjs/server/mcp.d.ts.map | 1 - dist/cjs/server/mcp.js | 758 --- dist/cjs/server/mcp.js.map | 1 - dist/cjs/server/sse.d.ts | 76 - dist/cjs/server/sse.d.ts.map | 1 - dist/cjs/server/sse.js | 168 - dist/cjs/server/sse.js.map | 1 - dist/cjs/server/stdio.d.ts | 28 - dist/cjs/server/stdio.d.ts.map | 1 - dist/cjs/server/stdio.js | 85 - dist/cjs/server/stdio.js.map | 1 - dist/cjs/server/streamableHttp.d.ts | 185 - dist/cjs/server/streamableHttp.d.ts.map | 1 - dist/cjs/server/streamableHttp.js | 631 --- dist/cjs/server/streamableHttp.js.map | 1 - dist/cjs/server/zod-compat.d.ts | 82 - dist/cjs/server/zod-compat.d.ts.map | 1 - dist/cjs/server/zod-compat.js | 252 - dist/cjs/server/zod-compat.js.map | 1 - dist/cjs/server/zod-json-schema-compat.d.ts | 12 - .../server/zod-json-schema-compat.d.ts.map | 1 - dist/cjs/server/zod-json-schema-compat.js | 80 - dist/cjs/server/zod-json-schema-compat.js.map | 1 - dist/cjs/shared/auth-utils.d.ts | 23 - dist/cjs/shared/auth-utils.d.ts.map | 1 - dist/cjs/shared/auth-utils.js | 48 - dist/cjs/shared/auth-utils.js.map | 1 - dist/cjs/shared/auth.d.ts | 240 - dist/cjs/shared/auth.d.ts.map | 1 - dist/cjs/shared/auth.js | 224 - dist/cjs/shared/auth.js.map | 1 - dist/cjs/shared/metadataUtils.d.ts | 16 - dist/cjs/shared/metadataUtils.d.ts.map | 1 - dist/cjs/shared/metadataUtils.js | 26 - dist/cjs/shared/metadataUtils.js.map | 1 - dist/cjs/shared/protocol.d.ts | 226 - dist/cjs/shared/protocol.d.ts.map | 1 - dist/cjs/shared/protocol.js | 442 -- dist/cjs/shared/protocol.js.map | 1 - dist/cjs/shared/stdio.d.ts | 13 - dist/cjs/shared/stdio.d.ts.map | 1 - dist/cjs/shared/stdio.js | 37 - dist/cjs/shared/stdio.js.map | 1 - dist/cjs/shared/toolNameValidation.d.ts | 31 - dist/cjs/shared/toolNameValidation.d.ts.map | 1 - dist/cjs/shared/toolNameValidation.js | 97 - dist/cjs/shared/toolNameValidation.js.map | 1 - dist/cjs/shared/transport.d.ts | 89 - dist/cjs/shared/transport.d.ts.map | 1 - dist/cjs/shared/transport.js | 43 - dist/cjs/shared/transport.js.map | 1 - dist/cjs/shared/uriTemplate.d.ts | 25 - dist/cjs/shared/uriTemplate.d.ts.map | 1 - dist/cjs/shared/uriTemplate.js | 243 - dist/cjs/shared/uriTemplate.js.map | 1 - dist/cjs/shared/zodTestMatrix.d.ts | 16 - dist/cjs/shared/zodTestMatrix.d.ts.map | 1 - dist/cjs/shared/zodTestMatrix.js | 43 - dist/cjs/shared/zodTestMatrix.js.map | 1 - dist/cjs/spec.types.d.ts | 2033 -------- dist/cjs/spec.types.d.ts.map | 1 - dist/cjs/spec.types.js | 27 - dist/cjs/spec.types.js.map | 1 - dist/cjs/types.d.ts | 4390 ----------------- dist/cjs/types.d.ts.map | 1 - dist/cjs/types.js | 1697 ------- dist/cjs/types.js.map | 1 - dist/cjs/validation/ajv-provider.d.ts | 53 - dist/cjs/validation/ajv-provider.d.ts.map | 1 - dist/cjs/validation/ajv-provider.js | 95 - dist/cjs/validation/ajv-provider.js.map | 1 - dist/cjs/validation/cfworker-provider.d.ts | 51 - .../cjs/validation/cfworker-provider.d.ts.map | 1 - dist/cjs/validation/cfworker-provider.js | 70 - dist/cjs/validation/cfworker-provider.js.map | 1 - dist/cjs/validation/index.d.ts | 29 - dist/cjs/validation/index.d.ts.map | 1 - dist/cjs/validation/index.js | 30 - dist/cjs/validation/index.js.map | 1 - dist/cjs/validation/types.d.ts | 55 - dist/cjs/validation/types.d.ts.map | 1 - dist/cjs/validation/types.js | 3 - dist/cjs/validation/types.js.map | 1 - dist/esm/client/auth.d.ts | 280 -- dist/esm/client/auth.d.ts.map | 1 - dist/esm/client/auth.js | 777 --- dist/esm/client/auth.js.map | 1 - dist/esm/client/index.d.ts | 379 -- dist/esm/client/index.d.ts.map | 1 - dist/esm/client/index.js | 418 -- dist/esm/client/index.js.map | 1 - dist/esm/client/middleware.d.ts | 169 - dist/esm/client/middleware.d.ts.map | 1 - dist/esm/client/middleware.js | 245 - dist/esm/client/middleware.js.map | 1 - dist/esm/client/sse.d.ts | 81 - dist/esm/client/sse.d.ts.map | 1 - dist/esm/client/sse.js | 208 - dist/esm/client/sse.js.map | 1 - dist/esm/client/stdio.d.ts | 78 - dist/esm/client/stdio.d.ts.map | 1 - dist/esm/client/stdio.js | 176 - dist/esm/client/stdio.js.map | 1 - dist/esm/client/streamableHttp.d.ts | 159 - dist/esm/client/streamableHttp.d.ts.map | 1 - dist/esm/client/streamableHttp.js | 421 -- dist/esm/client/streamableHttp.js.map | 1 - dist/esm/client/websocket.d.ts | 17 - dist/esm/client/websocket.d.ts.map | 1 - dist/esm/client/websocket.js | 59 - dist/esm/client/websocket.js.map | 1 - .../client/elicitationUrlExample.d.ts | 2 - .../client/elicitationUrlExample.d.ts.map | 1 - .../examples/client/elicitationUrlExample.js | 691 --- .../client/elicitationUrlExample.js.map | 1 - .../client/multipleClientsParallel.d.ts | 2 - .../client/multipleClientsParallel.d.ts.map | 1 - .../client/multipleClientsParallel.js | 132 - .../client/multipleClientsParallel.js.map | 1 - .../client/parallelToolCallsClient.d.ts | 2 - .../client/parallelToolCallsClient.d.ts.map | 1 - .../client/parallelToolCallsClient.js | 174 - .../client/parallelToolCallsClient.js.map | 1 - .../examples/client/simpleOAuthClient.d.ts | 3 - .../client/simpleOAuthClient.d.ts.map | 1 - dist/esm/examples/client/simpleOAuthClient.js | 335 -- .../examples/client/simpleOAuthClient.js.map | 1 - .../client/simpleOAuthClientProvider.d.ts | 26 - .../client/simpleOAuthClientProvider.d.ts.map | 1 - .../client/simpleOAuthClientProvider.js | 47 - .../client/simpleOAuthClientProvider.js.map | 1 - .../examples/client/simpleStreamableHttp.d.ts | 2 - .../client/simpleStreamableHttp.d.ts.map | 1 - .../examples/client/simpleStreamableHttp.js | 747 --- .../client/simpleStreamableHttp.js.map | 1 - .../streamableHttpWithSseFallbackClient.d.ts | 2 - ...reamableHttpWithSseFallbackClient.d.ts.map | 1 - .../streamableHttpWithSseFallbackClient.js | 166 - ...streamableHttpWithSseFallbackClient.js.map | 1 - .../server/demoInMemoryOAuthProvider.d.ts | 78 - .../server/demoInMemoryOAuthProvider.d.ts.map | 1 - .../server/demoInMemoryOAuthProvider.js | 196 - .../server/demoInMemoryOAuthProvider.js.map | 1 - .../server/elicitationFormExample.d.ts | 2 - .../server/elicitationFormExample.d.ts.map | 1 - .../examples/server/elicitationFormExample.js | 436 -- .../server/elicitationFormExample.js.map | 1 - .../server/elicitationUrlExample.d.ts | 2 - .../server/elicitationUrlExample.d.ts.map | 1 - .../examples/server/elicitationUrlExample.js | 650 --- .../server/elicitationUrlExample.js.map | 1 - .../server/jsonResponseStreamableHttp.d.ts | 2 - .../jsonResponseStreamableHttp.d.ts.map | 1 - .../server/jsonResponseStreamableHttp.js | 147 - .../server/jsonResponseStreamableHttp.js.map | 1 - .../server/mcpServerOutputSchema.d.ts | 7 - .../server/mcpServerOutputSchema.d.ts.map | 1 - .../examples/server/mcpServerOutputSchema.js | 70 - .../server/mcpServerOutputSchema.js.map | 1 - dist/esm/examples/server/simpleSseServer.d.ts | 2 - .../examples/server/simpleSseServer.d.ts.map | 1 - dist/esm/examples/server/simpleSseServer.js | 141 - .../examples/server/simpleSseServer.js.map | 1 - .../server/simpleStatelessStreamableHttp.d.ts | 2 - .../simpleStatelessStreamableHttp.d.ts.map | 1 - .../server/simpleStatelessStreamableHttp.js | 142 - .../simpleStatelessStreamableHttp.js.map | 1 - .../examples/server/simpleStreamableHttp.d.ts | 2 - .../server/simpleStreamableHttp.d.ts.map | 1 - .../examples/server/simpleStreamableHttp.js | 583 --- .../server/simpleStreamableHttp.js.map | 1 - .../sseAndStreamableHttpCompatibleServer.d.ts | 2 - ...AndStreamableHttpCompatibleServer.d.ts.map | 1 - .../sseAndStreamableHttpCompatibleServer.js | 235 - ...seAndStreamableHttpCompatibleServer.js.map | 1 - .../standaloneSseWithGetStreamableHttp.d.ts | 2 - ...tandaloneSseWithGetStreamableHttp.d.ts.map | 1 - .../standaloneSseWithGetStreamableHttp.js | 111 - .../standaloneSseWithGetStreamableHttp.js.map | 1 - .../examples/server/toolWithSampleServer.d.ts | 2 - .../server/toolWithSampleServer.d.ts.map | 1 - .../examples/server/toolWithSampleServer.js | 46 - .../server/toolWithSampleServer.js.map | 1 - .../examples/shared/inMemoryEventStore.d.ts | 31 - .../shared/inMemoryEventStore.d.ts.map | 1 - .../esm/examples/shared/inMemoryEventStore.js | 65 - .../examples/shared/inMemoryEventStore.js.map | 1 - dist/esm/inMemory.d.ts | 31 - dist/esm/inMemory.d.ts.map | 1 - dist/esm/inMemory.js | 49 - dist/esm/inMemory.js.map | 1 - dist/esm/package.json | 1 - dist/esm/server/auth/clients.d.ts | 19 - dist/esm/server/auth/clients.d.ts.map | 1 - dist/esm/server/auth/clients.js | 2 - dist/esm/server/auth/clients.js.map | 1 - dist/esm/server/auth/errors.d.ts | 141 - dist/esm/server/auth/errors.d.ts.map | 1 - dist/esm/server/auth/errors.js | 172 - dist/esm/server/auth/errors.js.map | 1 - dist/esm/server/auth/handlers/authorize.d.ts | 13 - .../server/auth/handlers/authorize.d.ts.map | 1 - dist/esm/server/auth/handlers/authorize.js | 138 - .../esm/server/auth/handlers/authorize.js.map | 1 - dist/esm/server/auth/handlers/metadata.d.ts | 4 - .../server/auth/handlers/metadata.d.ts.map | 1 - dist/esm/server/auth/handlers/metadata.js | 15 - dist/esm/server/auth/handlers/metadata.js.map | 1 - dist/esm/server/auth/handlers/register.d.ts | 29 - .../server/auth/handlers/register.d.ts.map | 1 - dist/esm/server/auth/handlers/register.js | 71 - dist/esm/server/auth/handlers/register.js.map | 1 - dist/esm/server/auth/handlers/revoke.d.ts | 13 - dist/esm/server/auth/handlers/revoke.d.ts.map | 1 - dist/esm/server/auth/handlers/revoke.js | 59 - dist/esm/server/auth/handlers/revoke.js.map | 1 - dist/esm/server/auth/handlers/token.d.ts | 13 - dist/esm/server/auth/handlers/token.d.ts.map | 1 - dist/esm/server/auth/handlers/token.js | 107 - dist/esm/server/auth/handlers/token.js.map | 1 - .../auth/middleware/allowedMethods.d.ts | 9 - .../auth/middleware/allowedMethods.d.ts.map | 1 - .../server/auth/middleware/allowedMethods.js | 18 - .../auth/middleware/allowedMethods.js.map | 1 - .../server/auth/middleware/bearerAuth.d.ts | 35 - .../auth/middleware/bearerAuth.d.ts.map | 1 - dist/esm/server/auth/middleware/bearerAuth.js | 72 - .../server/auth/middleware/bearerAuth.js.map | 1 - .../server/auth/middleware/clientAuth.d.ts | 19 - .../auth/middleware/clientAuth.d.ts.map | 1 - dist/esm/server/auth/middleware/clientAuth.js | 49 - .../server/auth/middleware/clientAuth.js.map | 1 - dist/esm/server/auth/provider.d.ts | 68 - dist/esm/server/auth/provider.d.ts.map | 1 - dist/esm/server/auth/provider.js | 2 - dist/esm/server/auth/provider.js.map | 1 - .../server/auth/providers/proxyProvider.d.ts | 49 - .../auth/providers/proxyProvider.d.ts.map | 1 - .../server/auth/providers/proxyProvider.js | 157 - .../auth/providers/proxyProvider.js.map | 1 - dist/esm/server/auth/router.d.ts | 101 - dist/esm/server/auth/router.d.ts.map | 1 - dist/esm/server/auth/router.js | 115 - dist/esm/server/auth/router.js.map | 1 - dist/esm/server/auth/types.d.ts | 32 - dist/esm/server/auth/types.d.ts.map | 1 - dist/esm/server/auth/types.js | 2 - dist/esm/server/auth/types.js.map | 1 - dist/esm/server/completable.d.ts | 38 - dist/esm/server/completable.d.ts.map | 1 - dist/esm/server/completable.js | 41 - dist/esm/server/completable.js.map | 1 - dist/esm/server/index.d.ts | 333 -- dist/esm/server/index.d.ts.map | 1 - dist/esm/server/index.js | 300 -- dist/esm/server/index.js.map | 1 - dist/esm/server/mcp.d.ts | 332 -- dist/esm/server/mcp.d.ts.map | 1 - dist/esm/server/mcp.js | 753 --- dist/esm/server/mcp.js.map | 1 - dist/esm/server/sse.d.ts | 76 - dist/esm/server/sse.d.ts.map | 1 - dist/esm/server/sse.js | 161 - dist/esm/server/sse.js.map | 1 - dist/esm/server/stdio.d.ts | 28 - dist/esm/server/stdio.d.ts.map | 1 - dist/esm/server/stdio.js | 78 - dist/esm/server/stdio.js.map | 1 - dist/esm/server/streamableHttp.d.ts | 185 - dist/esm/server/streamableHttp.d.ts.map | 1 - dist/esm/server/streamableHttp.js | 624 --- dist/esm/server/streamableHttp.js.map | 1 - dist/esm/server/zod-compat.d.ts | 82 - dist/esm/server/zod-compat.d.ts.map | 1 - dist/esm/server/zod-compat.js | 217 - dist/esm/server/zod-compat.js.map | 1 - dist/esm/server/zod-json-schema-compat.d.ts | 12 - .../server/zod-json-schema-compat.d.ts.map | 1 - dist/esm/server/zod-json-schema-compat.js | 52 - dist/esm/server/zod-json-schema-compat.js.map | 1 - dist/esm/shared/auth-utils.d.ts | 23 - dist/esm/shared/auth-utils.d.ts.map | 1 - dist/esm/shared/auth-utils.js | 44 - dist/esm/shared/auth-utils.js.map | 1 - dist/esm/shared/auth.d.ts | 240 - dist/esm/shared/auth.d.ts.map | 1 - dist/esm/shared/auth.js | 198 - dist/esm/shared/auth.js.map | 1 - dist/esm/shared/metadataUtils.d.ts | 16 - dist/esm/shared/metadataUtils.d.ts.map | 1 - dist/esm/shared/metadataUtils.js | 23 - dist/esm/shared/metadataUtils.js.map | 1 - dist/esm/shared/protocol.d.ts | 226 - dist/esm/shared/protocol.d.ts.map | 1 - dist/esm/shared/protocol.js | 437 -- dist/esm/shared/protocol.js.map | 1 - dist/esm/shared/stdio.d.ts | 13 - dist/esm/shared/stdio.d.ts.map | 1 - dist/esm/shared/stdio.js | 31 - dist/esm/shared/stdio.js.map | 1 - dist/esm/shared/toolNameValidation.d.ts | 31 - dist/esm/shared/toolNameValidation.d.ts.map | 1 - dist/esm/shared/toolNameValidation.js | 92 - dist/esm/shared/toolNameValidation.js.map | 1 - dist/esm/shared/transport.d.ts | 89 - dist/esm/shared/transport.d.ts.map | 1 - dist/esm/shared/transport.js | 39 - dist/esm/shared/transport.js.map | 1 - dist/esm/shared/uriTemplate.d.ts | 25 - dist/esm/shared/uriTemplate.d.ts.map | 1 - dist/esm/shared/uriTemplate.js | 239 - dist/esm/shared/uriTemplate.js.map | 1 - dist/esm/shared/zodTestMatrix.d.ts | 16 - dist/esm/shared/zodTestMatrix.d.ts.map | 1 - dist/esm/shared/zodTestMatrix.js | 17 - dist/esm/shared/zodTestMatrix.js.map | 1 - dist/esm/spec.types.d.ts | 2033 -------- dist/esm/spec.types.d.ts.map | 1 - dist/esm/spec.types.js | 24 - dist/esm/spec.types.js.map | 1 - dist/esm/types.d.ts | 4390 ----------------- dist/esm/types.d.ts.map | 1 - dist/esm/types.js | 1659 ------- dist/esm/types.js.map | 1 - dist/esm/validation/ajv-provider.d.ts | 53 - dist/esm/validation/ajv-provider.d.ts.map | 1 - dist/esm/validation/ajv-provider.js | 88 - dist/esm/validation/ajv-provider.js.map | 1 - dist/esm/validation/cfworker-provider.d.ts | 51 - .../esm/validation/cfworker-provider.d.ts.map | 1 - dist/esm/validation/cfworker-provider.js | 66 - dist/esm/validation/cfworker-provider.js.map | 1 - dist/esm/validation/index.d.ts | 29 - dist/esm/validation/index.d.ts.map | 1 - dist/esm/validation/index.js | 29 - dist/esm/validation/index.js.map | 1 - dist/esm/validation/types.d.ts | 55 - dist/esm/validation/types.d.ts.map | 1 - dist/esm/validation/types.js | 2 - dist/esm/validation/types.js.map | 1 - 514 files changed, 48831 deletions(-) delete mode 100644 dist/cjs/client/auth.d.ts delete mode 100644 dist/cjs/client/auth.d.ts.map delete mode 100644 dist/cjs/client/auth.js delete mode 100644 dist/cjs/client/auth.js.map delete mode 100644 dist/cjs/client/index.d.ts delete mode 100644 dist/cjs/client/index.d.ts.map delete mode 100644 dist/cjs/client/index.js delete mode 100644 dist/cjs/client/index.js.map delete mode 100644 dist/cjs/client/middleware.d.ts delete mode 100644 dist/cjs/client/middleware.d.ts.map delete mode 100644 dist/cjs/client/middleware.js delete mode 100644 dist/cjs/client/middleware.js.map delete mode 100644 dist/cjs/client/sse.d.ts delete mode 100644 dist/cjs/client/sse.d.ts.map delete mode 100644 dist/cjs/client/sse.js delete mode 100644 dist/cjs/client/sse.js.map delete mode 100644 dist/cjs/client/stdio.d.ts delete mode 100644 dist/cjs/client/stdio.d.ts.map delete mode 100644 dist/cjs/client/stdio.js delete mode 100644 dist/cjs/client/stdio.js.map delete mode 100644 dist/cjs/client/streamableHttp.d.ts delete mode 100644 dist/cjs/client/streamableHttp.d.ts.map delete mode 100644 dist/cjs/client/streamableHttp.js delete mode 100644 dist/cjs/client/streamableHttp.js.map delete mode 100644 dist/cjs/client/websocket.d.ts delete mode 100644 dist/cjs/client/websocket.d.ts.map delete mode 100644 dist/cjs/client/websocket.js delete mode 100644 dist/cjs/client/websocket.js.map delete mode 100644 dist/cjs/examples/client/elicitationUrlExample.d.ts delete mode 100644 dist/cjs/examples/client/elicitationUrlExample.d.ts.map delete mode 100644 dist/cjs/examples/client/elicitationUrlExample.js delete mode 100644 dist/cjs/examples/client/elicitationUrlExample.js.map delete mode 100644 dist/cjs/examples/client/multipleClientsParallel.d.ts delete mode 100644 dist/cjs/examples/client/multipleClientsParallel.d.ts.map delete mode 100644 dist/cjs/examples/client/multipleClientsParallel.js delete mode 100644 dist/cjs/examples/client/multipleClientsParallel.js.map delete mode 100644 dist/cjs/examples/client/parallelToolCallsClient.d.ts delete mode 100644 dist/cjs/examples/client/parallelToolCallsClient.d.ts.map delete mode 100644 dist/cjs/examples/client/parallelToolCallsClient.js delete mode 100644 dist/cjs/examples/client/parallelToolCallsClient.js.map delete mode 100644 dist/cjs/examples/client/simpleOAuthClient.d.ts delete mode 100644 dist/cjs/examples/client/simpleOAuthClient.d.ts.map delete mode 100644 dist/cjs/examples/client/simpleOAuthClient.js delete mode 100644 dist/cjs/examples/client/simpleOAuthClient.js.map delete mode 100644 dist/cjs/examples/client/simpleOAuthClientProvider.d.ts delete mode 100644 dist/cjs/examples/client/simpleOAuthClientProvider.d.ts.map delete mode 100644 dist/cjs/examples/client/simpleOAuthClientProvider.js delete mode 100644 dist/cjs/examples/client/simpleOAuthClientProvider.js.map delete mode 100644 dist/cjs/examples/client/simpleStreamableHttp.d.ts delete mode 100644 dist/cjs/examples/client/simpleStreamableHttp.d.ts.map delete mode 100644 dist/cjs/examples/client/simpleStreamableHttp.js delete mode 100644 dist/cjs/examples/client/simpleStreamableHttp.js.map delete mode 100644 dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts delete mode 100644 dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts.map delete mode 100644 dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js delete mode 100644 dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js.map delete mode 100644 dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts delete mode 100644 dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts.map delete mode 100644 dist/cjs/examples/server/demoInMemoryOAuthProvider.js delete mode 100644 dist/cjs/examples/server/demoInMemoryOAuthProvider.js.map delete mode 100644 dist/cjs/examples/server/elicitationFormExample.d.ts delete mode 100644 dist/cjs/examples/server/elicitationFormExample.d.ts.map delete mode 100644 dist/cjs/examples/server/elicitationFormExample.js delete mode 100644 dist/cjs/examples/server/elicitationFormExample.js.map delete mode 100644 dist/cjs/examples/server/elicitationUrlExample.d.ts delete mode 100644 dist/cjs/examples/server/elicitationUrlExample.d.ts.map delete mode 100644 dist/cjs/examples/server/elicitationUrlExample.js delete mode 100644 dist/cjs/examples/server/elicitationUrlExample.js.map delete mode 100644 dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts delete mode 100644 dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts.map delete mode 100644 dist/cjs/examples/server/jsonResponseStreamableHttp.js delete mode 100644 dist/cjs/examples/server/jsonResponseStreamableHttp.js.map delete mode 100644 dist/cjs/examples/server/mcpServerOutputSchema.d.ts delete mode 100644 dist/cjs/examples/server/mcpServerOutputSchema.d.ts.map delete mode 100644 dist/cjs/examples/server/mcpServerOutputSchema.js delete mode 100644 dist/cjs/examples/server/mcpServerOutputSchema.js.map delete mode 100644 dist/cjs/examples/server/simpleSseServer.d.ts delete mode 100644 dist/cjs/examples/server/simpleSseServer.d.ts.map delete mode 100644 dist/cjs/examples/server/simpleSseServer.js delete mode 100644 dist/cjs/examples/server/simpleSseServer.js.map delete mode 100644 dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts delete mode 100644 dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts.map delete mode 100644 dist/cjs/examples/server/simpleStatelessStreamableHttp.js delete mode 100644 dist/cjs/examples/server/simpleStatelessStreamableHttp.js.map delete mode 100644 dist/cjs/examples/server/simpleStreamableHttp.d.ts delete mode 100644 dist/cjs/examples/server/simpleStreamableHttp.d.ts.map delete mode 100644 dist/cjs/examples/server/simpleStreamableHttp.js delete mode 100644 dist/cjs/examples/server/simpleStreamableHttp.js.map delete mode 100644 dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts delete mode 100644 dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map delete mode 100644 dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js delete mode 100644 dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js.map delete mode 100644 dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts delete mode 100644 dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map delete mode 100644 dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js delete mode 100644 dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js.map delete mode 100644 dist/cjs/examples/server/toolWithSampleServer.d.ts delete mode 100644 dist/cjs/examples/server/toolWithSampleServer.d.ts.map delete mode 100644 dist/cjs/examples/server/toolWithSampleServer.js delete mode 100644 dist/cjs/examples/server/toolWithSampleServer.js.map delete mode 100644 dist/cjs/examples/shared/inMemoryEventStore.d.ts delete mode 100644 dist/cjs/examples/shared/inMemoryEventStore.d.ts.map delete mode 100644 dist/cjs/examples/shared/inMemoryEventStore.js delete mode 100644 dist/cjs/examples/shared/inMemoryEventStore.js.map delete mode 100644 dist/cjs/inMemory.d.ts delete mode 100644 dist/cjs/inMemory.d.ts.map delete mode 100644 dist/cjs/inMemory.js delete mode 100644 dist/cjs/inMemory.js.map delete mode 100644 dist/cjs/package.json delete mode 100644 dist/cjs/server/auth/clients.d.ts delete mode 100644 dist/cjs/server/auth/clients.d.ts.map delete mode 100644 dist/cjs/server/auth/clients.js delete mode 100644 dist/cjs/server/auth/clients.js.map delete mode 100644 dist/cjs/server/auth/errors.d.ts delete mode 100644 dist/cjs/server/auth/errors.d.ts.map delete mode 100644 dist/cjs/server/auth/errors.js delete mode 100644 dist/cjs/server/auth/errors.js.map delete mode 100644 dist/cjs/server/auth/handlers/authorize.d.ts delete mode 100644 dist/cjs/server/auth/handlers/authorize.d.ts.map delete mode 100644 dist/cjs/server/auth/handlers/authorize.js delete mode 100644 dist/cjs/server/auth/handlers/authorize.js.map delete mode 100644 dist/cjs/server/auth/handlers/metadata.d.ts delete mode 100644 dist/cjs/server/auth/handlers/metadata.d.ts.map delete mode 100644 dist/cjs/server/auth/handlers/metadata.js delete mode 100644 dist/cjs/server/auth/handlers/metadata.js.map delete mode 100644 dist/cjs/server/auth/handlers/register.d.ts delete mode 100644 dist/cjs/server/auth/handlers/register.d.ts.map delete mode 100644 dist/cjs/server/auth/handlers/register.js delete mode 100644 dist/cjs/server/auth/handlers/register.js.map delete mode 100644 dist/cjs/server/auth/handlers/revoke.d.ts delete mode 100644 dist/cjs/server/auth/handlers/revoke.d.ts.map delete mode 100644 dist/cjs/server/auth/handlers/revoke.js delete mode 100644 dist/cjs/server/auth/handlers/revoke.js.map delete mode 100644 dist/cjs/server/auth/handlers/token.d.ts delete mode 100644 dist/cjs/server/auth/handlers/token.d.ts.map delete mode 100644 dist/cjs/server/auth/handlers/token.js delete mode 100644 dist/cjs/server/auth/handlers/token.js.map delete mode 100644 dist/cjs/server/auth/middleware/allowedMethods.d.ts delete mode 100644 dist/cjs/server/auth/middleware/allowedMethods.d.ts.map delete mode 100644 dist/cjs/server/auth/middleware/allowedMethods.js delete mode 100644 dist/cjs/server/auth/middleware/allowedMethods.js.map delete mode 100644 dist/cjs/server/auth/middleware/bearerAuth.d.ts delete mode 100644 dist/cjs/server/auth/middleware/bearerAuth.d.ts.map delete mode 100644 dist/cjs/server/auth/middleware/bearerAuth.js delete mode 100644 dist/cjs/server/auth/middleware/bearerAuth.js.map delete mode 100644 dist/cjs/server/auth/middleware/clientAuth.d.ts delete mode 100644 dist/cjs/server/auth/middleware/clientAuth.d.ts.map delete mode 100644 dist/cjs/server/auth/middleware/clientAuth.js delete mode 100644 dist/cjs/server/auth/middleware/clientAuth.js.map delete mode 100644 dist/cjs/server/auth/provider.d.ts delete mode 100644 dist/cjs/server/auth/provider.d.ts.map delete mode 100644 dist/cjs/server/auth/provider.js delete mode 100644 dist/cjs/server/auth/provider.js.map delete mode 100644 dist/cjs/server/auth/providers/proxyProvider.d.ts delete mode 100644 dist/cjs/server/auth/providers/proxyProvider.d.ts.map delete mode 100644 dist/cjs/server/auth/providers/proxyProvider.js delete mode 100644 dist/cjs/server/auth/providers/proxyProvider.js.map delete mode 100644 dist/cjs/server/auth/router.d.ts delete mode 100644 dist/cjs/server/auth/router.d.ts.map delete mode 100644 dist/cjs/server/auth/router.js delete mode 100644 dist/cjs/server/auth/router.js.map delete mode 100644 dist/cjs/server/auth/types.d.ts delete mode 100644 dist/cjs/server/auth/types.d.ts.map delete mode 100644 dist/cjs/server/auth/types.js delete mode 100644 dist/cjs/server/auth/types.js.map delete mode 100644 dist/cjs/server/completable.d.ts delete mode 100644 dist/cjs/server/completable.d.ts.map delete mode 100644 dist/cjs/server/completable.js delete mode 100644 dist/cjs/server/completable.js.map delete mode 100644 dist/cjs/server/index.d.ts delete mode 100644 dist/cjs/server/index.d.ts.map delete mode 100644 dist/cjs/server/index.js delete mode 100644 dist/cjs/server/index.js.map delete mode 100644 dist/cjs/server/mcp.d.ts delete mode 100644 dist/cjs/server/mcp.d.ts.map delete mode 100644 dist/cjs/server/mcp.js delete mode 100644 dist/cjs/server/mcp.js.map delete mode 100644 dist/cjs/server/sse.d.ts delete mode 100644 dist/cjs/server/sse.d.ts.map delete mode 100644 dist/cjs/server/sse.js delete mode 100644 dist/cjs/server/sse.js.map delete mode 100644 dist/cjs/server/stdio.d.ts delete mode 100644 dist/cjs/server/stdio.d.ts.map delete mode 100644 dist/cjs/server/stdio.js delete mode 100644 dist/cjs/server/stdio.js.map delete mode 100644 dist/cjs/server/streamableHttp.d.ts delete mode 100644 dist/cjs/server/streamableHttp.d.ts.map delete mode 100644 dist/cjs/server/streamableHttp.js delete mode 100644 dist/cjs/server/streamableHttp.js.map delete mode 100644 dist/cjs/server/zod-compat.d.ts delete mode 100644 dist/cjs/server/zod-compat.d.ts.map delete mode 100644 dist/cjs/server/zod-compat.js delete mode 100644 dist/cjs/server/zod-compat.js.map delete mode 100644 dist/cjs/server/zod-json-schema-compat.d.ts delete mode 100644 dist/cjs/server/zod-json-schema-compat.d.ts.map delete mode 100644 dist/cjs/server/zod-json-schema-compat.js delete mode 100644 dist/cjs/server/zod-json-schema-compat.js.map delete mode 100644 dist/cjs/shared/auth-utils.d.ts delete mode 100644 dist/cjs/shared/auth-utils.d.ts.map delete mode 100644 dist/cjs/shared/auth-utils.js delete mode 100644 dist/cjs/shared/auth-utils.js.map delete mode 100644 dist/cjs/shared/auth.d.ts delete mode 100644 dist/cjs/shared/auth.d.ts.map delete mode 100644 dist/cjs/shared/auth.js delete mode 100644 dist/cjs/shared/auth.js.map delete mode 100644 dist/cjs/shared/metadataUtils.d.ts delete mode 100644 dist/cjs/shared/metadataUtils.d.ts.map delete mode 100644 dist/cjs/shared/metadataUtils.js delete mode 100644 dist/cjs/shared/metadataUtils.js.map delete mode 100644 dist/cjs/shared/protocol.d.ts delete mode 100644 dist/cjs/shared/protocol.d.ts.map delete mode 100644 dist/cjs/shared/protocol.js delete mode 100644 dist/cjs/shared/protocol.js.map delete mode 100644 dist/cjs/shared/stdio.d.ts delete mode 100644 dist/cjs/shared/stdio.d.ts.map delete mode 100644 dist/cjs/shared/stdio.js delete mode 100644 dist/cjs/shared/stdio.js.map delete mode 100644 dist/cjs/shared/toolNameValidation.d.ts delete mode 100644 dist/cjs/shared/toolNameValidation.d.ts.map delete mode 100644 dist/cjs/shared/toolNameValidation.js delete mode 100644 dist/cjs/shared/toolNameValidation.js.map delete mode 100644 dist/cjs/shared/transport.d.ts delete mode 100644 dist/cjs/shared/transport.d.ts.map delete mode 100644 dist/cjs/shared/transport.js delete mode 100644 dist/cjs/shared/transport.js.map delete mode 100644 dist/cjs/shared/uriTemplate.d.ts delete mode 100644 dist/cjs/shared/uriTemplate.d.ts.map delete mode 100644 dist/cjs/shared/uriTemplate.js delete mode 100644 dist/cjs/shared/uriTemplate.js.map delete mode 100644 dist/cjs/shared/zodTestMatrix.d.ts delete mode 100644 dist/cjs/shared/zodTestMatrix.d.ts.map delete mode 100644 dist/cjs/shared/zodTestMatrix.js delete mode 100644 dist/cjs/shared/zodTestMatrix.js.map delete mode 100644 dist/cjs/spec.types.d.ts delete mode 100644 dist/cjs/spec.types.d.ts.map delete mode 100644 dist/cjs/spec.types.js delete mode 100644 dist/cjs/spec.types.js.map delete mode 100644 dist/cjs/types.d.ts delete mode 100644 dist/cjs/types.d.ts.map delete mode 100644 dist/cjs/types.js delete mode 100644 dist/cjs/types.js.map delete mode 100644 dist/cjs/validation/ajv-provider.d.ts delete mode 100644 dist/cjs/validation/ajv-provider.d.ts.map delete mode 100644 dist/cjs/validation/ajv-provider.js delete mode 100644 dist/cjs/validation/ajv-provider.js.map delete mode 100644 dist/cjs/validation/cfworker-provider.d.ts delete mode 100644 dist/cjs/validation/cfworker-provider.d.ts.map delete mode 100644 dist/cjs/validation/cfworker-provider.js delete mode 100644 dist/cjs/validation/cfworker-provider.js.map delete mode 100644 dist/cjs/validation/index.d.ts delete mode 100644 dist/cjs/validation/index.d.ts.map delete mode 100644 dist/cjs/validation/index.js delete mode 100644 dist/cjs/validation/index.js.map delete mode 100644 dist/cjs/validation/types.d.ts delete mode 100644 dist/cjs/validation/types.d.ts.map delete mode 100644 dist/cjs/validation/types.js delete mode 100644 dist/cjs/validation/types.js.map delete mode 100644 dist/esm/client/auth.d.ts delete mode 100644 dist/esm/client/auth.d.ts.map delete mode 100644 dist/esm/client/auth.js delete mode 100644 dist/esm/client/auth.js.map delete mode 100644 dist/esm/client/index.d.ts delete mode 100644 dist/esm/client/index.d.ts.map delete mode 100644 dist/esm/client/index.js delete mode 100644 dist/esm/client/index.js.map delete mode 100644 dist/esm/client/middleware.d.ts delete mode 100644 dist/esm/client/middleware.d.ts.map delete mode 100644 dist/esm/client/middleware.js delete mode 100644 dist/esm/client/middleware.js.map delete mode 100644 dist/esm/client/sse.d.ts delete mode 100644 dist/esm/client/sse.d.ts.map delete mode 100644 dist/esm/client/sse.js delete mode 100644 dist/esm/client/sse.js.map delete mode 100644 dist/esm/client/stdio.d.ts delete mode 100644 dist/esm/client/stdio.d.ts.map delete mode 100644 dist/esm/client/stdio.js delete mode 100644 dist/esm/client/stdio.js.map delete mode 100644 dist/esm/client/streamableHttp.d.ts delete mode 100644 dist/esm/client/streamableHttp.d.ts.map delete mode 100644 dist/esm/client/streamableHttp.js delete mode 100644 dist/esm/client/streamableHttp.js.map delete mode 100644 dist/esm/client/websocket.d.ts delete mode 100644 dist/esm/client/websocket.d.ts.map delete mode 100644 dist/esm/client/websocket.js delete mode 100644 dist/esm/client/websocket.js.map delete mode 100644 dist/esm/examples/client/elicitationUrlExample.d.ts delete mode 100644 dist/esm/examples/client/elicitationUrlExample.d.ts.map delete mode 100644 dist/esm/examples/client/elicitationUrlExample.js delete mode 100644 dist/esm/examples/client/elicitationUrlExample.js.map delete mode 100644 dist/esm/examples/client/multipleClientsParallel.d.ts delete mode 100644 dist/esm/examples/client/multipleClientsParallel.d.ts.map delete mode 100644 dist/esm/examples/client/multipleClientsParallel.js delete mode 100644 dist/esm/examples/client/multipleClientsParallel.js.map delete mode 100644 dist/esm/examples/client/parallelToolCallsClient.d.ts delete mode 100644 dist/esm/examples/client/parallelToolCallsClient.d.ts.map delete mode 100644 dist/esm/examples/client/parallelToolCallsClient.js delete mode 100644 dist/esm/examples/client/parallelToolCallsClient.js.map delete mode 100644 dist/esm/examples/client/simpleOAuthClient.d.ts delete mode 100644 dist/esm/examples/client/simpleOAuthClient.d.ts.map delete mode 100644 dist/esm/examples/client/simpleOAuthClient.js delete mode 100644 dist/esm/examples/client/simpleOAuthClient.js.map delete mode 100644 dist/esm/examples/client/simpleOAuthClientProvider.d.ts delete mode 100644 dist/esm/examples/client/simpleOAuthClientProvider.d.ts.map delete mode 100644 dist/esm/examples/client/simpleOAuthClientProvider.js delete mode 100644 dist/esm/examples/client/simpleOAuthClientProvider.js.map delete mode 100644 dist/esm/examples/client/simpleStreamableHttp.d.ts delete mode 100644 dist/esm/examples/client/simpleStreamableHttp.d.ts.map delete mode 100644 dist/esm/examples/client/simpleStreamableHttp.js delete mode 100644 dist/esm/examples/client/simpleStreamableHttp.js.map delete mode 100644 dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts delete mode 100644 dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts.map delete mode 100644 dist/esm/examples/client/streamableHttpWithSseFallbackClient.js delete mode 100644 dist/esm/examples/client/streamableHttpWithSseFallbackClient.js.map delete mode 100644 dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts delete mode 100644 dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts.map delete mode 100644 dist/esm/examples/server/demoInMemoryOAuthProvider.js delete mode 100644 dist/esm/examples/server/demoInMemoryOAuthProvider.js.map delete mode 100644 dist/esm/examples/server/elicitationFormExample.d.ts delete mode 100644 dist/esm/examples/server/elicitationFormExample.d.ts.map delete mode 100644 dist/esm/examples/server/elicitationFormExample.js delete mode 100644 dist/esm/examples/server/elicitationFormExample.js.map delete mode 100644 dist/esm/examples/server/elicitationUrlExample.d.ts delete mode 100644 dist/esm/examples/server/elicitationUrlExample.d.ts.map delete mode 100644 dist/esm/examples/server/elicitationUrlExample.js delete mode 100644 dist/esm/examples/server/elicitationUrlExample.js.map delete mode 100644 dist/esm/examples/server/jsonResponseStreamableHttp.d.ts delete mode 100644 dist/esm/examples/server/jsonResponseStreamableHttp.d.ts.map delete mode 100644 dist/esm/examples/server/jsonResponseStreamableHttp.js delete mode 100644 dist/esm/examples/server/jsonResponseStreamableHttp.js.map delete mode 100644 dist/esm/examples/server/mcpServerOutputSchema.d.ts delete mode 100644 dist/esm/examples/server/mcpServerOutputSchema.d.ts.map delete mode 100644 dist/esm/examples/server/mcpServerOutputSchema.js delete mode 100644 dist/esm/examples/server/mcpServerOutputSchema.js.map delete mode 100644 dist/esm/examples/server/simpleSseServer.d.ts delete mode 100644 dist/esm/examples/server/simpleSseServer.d.ts.map delete mode 100644 dist/esm/examples/server/simpleSseServer.js delete mode 100644 dist/esm/examples/server/simpleSseServer.js.map delete mode 100644 dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts delete mode 100644 dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts.map delete mode 100644 dist/esm/examples/server/simpleStatelessStreamableHttp.js delete mode 100644 dist/esm/examples/server/simpleStatelessStreamableHttp.js.map delete mode 100644 dist/esm/examples/server/simpleStreamableHttp.d.ts delete mode 100644 dist/esm/examples/server/simpleStreamableHttp.d.ts.map delete mode 100644 dist/esm/examples/server/simpleStreamableHttp.js delete mode 100644 dist/esm/examples/server/simpleStreamableHttp.js.map delete mode 100644 dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts delete mode 100644 dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map delete mode 100644 dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js delete mode 100644 dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js.map delete mode 100644 dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts delete mode 100644 dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map delete mode 100644 dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js delete mode 100644 dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js.map delete mode 100644 dist/esm/examples/server/toolWithSampleServer.d.ts delete mode 100644 dist/esm/examples/server/toolWithSampleServer.d.ts.map delete mode 100644 dist/esm/examples/server/toolWithSampleServer.js delete mode 100644 dist/esm/examples/server/toolWithSampleServer.js.map delete mode 100644 dist/esm/examples/shared/inMemoryEventStore.d.ts delete mode 100644 dist/esm/examples/shared/inMemoryEventStore.d.ts.map delete mode 100644 dist/esm/examples/shared/inMemoryEventStore.js delete mode 100644 dist/esm/examples/shared/inMemoryEventStore.js.map delete mode 100644 dist/esm/inMemory.d.ts delete mode 100644 dist/esm/inMemory.d.ts.map delete mode 100644 dist/esm/inMemory.js delete mode 100644 dist/esm/inMemory.js.map delete mode 100644 dist/esm/package.json delete mode 100644 dist/esm/server/auth/clients.d.ts delete mode 100644 dist/esm/server/auth/clients.d.ts.map delete mode 100644 dist/esm/server/auth/clients.js delete mode 100644 dist/esm/server/auth/clients.js.map delete mode 100644 dist/esm/server/auth/errors.d.ts delete mode 100644 dist/esm/server/auth/errors.d.ts.map delete mode 100644 dist/esm/server/auth/errors.js delete mode 100644 dist/esm/server/auth/errors.js.map delete mode 100644 dist/esm/server/auth/handlers/authorize.d.ts delete mode 100644 dist/esm/server/auth/handlers/authorize.d.ts.map delete mode 100644 dist/esm/server/auth/handlers/authorize.js delete mode 100644 dist/esm/server/auth/handlers/authorize.js.map delete mode 100644 dist/esm/server/auth/handlers/metadata.d.ts delete mode 100644 dist/esm/server/auth/handlers/metadata.d.ts.map delete mode 100644 dist/esm/server/auth/handlers/metadata.js delete mode 100644 dist/esm/server/auth/handlers/metadata.js.map delete mode 100644 dist/esm/server/auth/handlers/register.d.ts delete mode 100644 dist/esm/server/auth/handlers/register.d.ts.map delete mode 100644 dist/esm/server/auth/handlers/register.js delete mode 100644 dist/esm/server/auth/handlers/register.js.map delete mode 100644 dist/esm/server/auth/handlers/revoke.d.ts delete mode 100644 dist/esm/server/auth/handlers/revoke.d.ts.map delete mode 100644 dist/esm/server/auth/handlers/revoke.js delete mode 100644 dist/esm/server/auth/handlers/revoke.js.map delete mode 100644 dist/esm/server/auth/handlers/token.d.ts delete mode 100644 dist/esm/server/auth/handlers/token.d.ts.map delete mode 100644 dist/esm/server/auth/handlers/token.js delete mode 100644 dist/esm/server/auth/handlers/token.js.map delete mode 100644 dist/esm/server/auth/middleware/allowedMethods.d.ts delete mode 100644 dist/esm/server/auth/middleware/allowedMethods.d.ts.map delete mode 100644 dist/esm/server/auth/middleware/allowedMethods.js delete mode 100644 dist/esm/server/auth/middleware/allowedMethods.js.map delete mode 100644 dist/esm/server/auth/middleware/bearerAuth.d.ts delete mode 100644 dist/esm/server/auth/middleware/bearerAuth.d.ts.map delete mode 100644 dist/esm/server/auth/middleware/bearerAuth.js delete mode 100644 dist/esm/server/auth/middleware/bearerAuth.js.map delete mode 100644 dist/esm/server/auth/middleware/clientAuth.d.ts delete mode 100644 dist/esm/server/auth/middleware/clientAuth.d.ts.map delete mode 100644 dist/esm/server/auth/middleware/clientAuth.js delete mode 100644 dist/esm/server/auth/middleware/clientAuth.js.map delete mode 100644 dist/esm/server/auth/provider.d.ts delete mode 100644 dist/esm/server/auth/provider.d.ts.map delete mode 100644 dist/esm/server/auth/provider.js delete mode 100644 dist/esm/server/auth/provider.js.map delete mode 100644 dist/esm/server/auth/providers/proxyProvider.d.ts delete mode 100644 dist/esm/server/auth/providers/proxyProvider.d.ts.map delete mode 100644 dist/esm/server/auth/providers/proxyProvider.js delete mode 100644 dist/esm/server/auth/providers/proxyProvider.js.map delete mode 100644 dist/esm/server/auth/router.d.ts delete mode 100644 dist/esm/server/auth/router.d.ts.map delete mode 100644 dist/esm/server/auth/router.js delete mode 100644 dist/esm/server/auth/router.js.map delete mode 100644 dist/esm/server/auth/types.d.ts delete mode 100644 dist/esm/server/auth/types.d.ts.map delete mode 100644 dist/esm/server/auth/types.js delete mode 100644 dist/esm/server/auth/types.js.map delete mode 100644 dist/esm/server/completable.d.ts delete mode 100644 dist/esm/server/completable.d.ts.map delete mode 100644 dist/esm/server/completable.js delete mode 100644 dist/esm/server/completable.js.map delete mode 100644 dist/esm/server/index.d.ts delete mode 100644 dist/esm/server/index.d.ts.map delete mode 100644 dist/esm/server/index.js delete mode 100644 dist/esm/server/index.js.map delete mode 100644 dist/esm/server/mcp.d.ts delete mode 100644 dist/esm/server/mcp.d.ts.map delete mode 100644 dist/esm/server/mcp.js delete mode 100644 dist/esm/server/mcp.js.map delete mode 100644 dist/esm/server/sse.d.ts delete mode 100644 dist/esm/server/sse.d.ts.map delete mode 100644 dist/esm/server/sse.js delete mode 100644 dist/esm/server/sse.js.map delete mode 100644 dist/esm/server/stdio.d.ts delete mode 100644 dist/esm/server/stdio.d.ts.map delete mode 100644 dist/esm/server/stdio.js delete mode 100644 dist/esm/server/stdio.js.map delete mode 100644 dist/esm/server/streamableHttp.d.ts delete mode 100644 dist/esm/server/streamableHttp.d.ts.map delete mode 100644 dist/esm/server/streamableHttp.js delete mode 100644 dist/esm/server/streamableHttp.js.map delete mode 100644 dist/esm/server/zod-compat.d.ts delete mode 100644 dist/esm/server/zod-compat.d.ts.map delete mode 100644 dist/esm/server/zod-compat.js delete mode 100644 dist/esm/server/zod-compat.js.map delete mode 100644 dist/esm/server/zod-json-schema-compat.d.ts delete mode 100644 dist/esm/server/zod-json-schema-compat.d.ts.map delete mode 100644 dist/esm/server/zod-json-schema-compat.js delete mode 100644 dist/esm/server/zod-json-schema-compat.js.map delete mode 100644 dist/esm/shared/auth-utils.d.ts delete mode 100644 dist/esm/shared/auth-utils.d.ts.map delete mode 100644 dist/esm/shared/auth-utils.js delete mode 100644 dist/esm/shared/auth-utils.js.map delete mode 100644 dist/esm/shared/auth.d.ts delete mode 100644 dist/esm/shared/auth.d.ts.map delete mode 100644 dist/esm/shared/auth.js delete mode 100644 dist/esm/shared/auth.js.map delete mode 100644 dist/esm/shared/metadataUtils.d.ts delete mode 100644 dist/esm/shared/metadataUtils.d.ts.map delete mode 100644 dist/esm/shared/metadataUtils.js delete mode 100644 dist/esm/shared/metadataUtils.js.map delete mode 100644 dist/esm/shared/protocol.d.ts delete mode 100644 dist/esm/shared/protocol.d.ts.map delete mode 100644 dist/esm/shared/protocol.js delete mode 100644 dist/esm/shared/protocol.js.map delete mode 100644 dist/esm/shared/stdio.d.ts delete mode 100644 dist/esm/shared/stdio.d.ts.map delete mode 100644 dist/esm/shared/stdio.js delete mode 100644 dist/esm/shared/stdio.js.map delete mode 100644 dist/esm/shared/toolNameValidation.d.ts delete mode 100644 dist/esm/shared/toolNameValidation.d.ts.map delete mode 100644 dist/esm/shared/toolNameValidation.js delete mode 100644 dist/esm/shared/toolNameValidation.js.map delete mode 100644 dist/esm/shared/transport.d.ts delete mode 100644 dist/esm/shared/transport.d.ts.map delete mode 100644 dist/esm/shared/transport.js delete mode 100644 dist/esm/shared/transport.js.map delete mode 100644 dist/esm/shared/uriTemplate.d.ts delete mode 100644 dist/esm/shared/uriTemplate.d.ts.map delete mode 100644 dist/esm/shared/uriTemplate.js delete mode 100644 dist/esm/shared/uriTemplate.js.map delete mode 100644 dist/esm/shared/zodTestMatrix.d.ts delete mode 100644 dist/esm/shared/zodTestMatrix.d.ts.map delete mode 100644 dist/esm/shared/zodTestMatrix.js delete mode 100644 dist/esm/shared/zodTestMatrix.js.map delete mode 100644 dist/esm/spec.types.d.ts delete mode 100644 dist/esm/spec.types.d.ts.map delete mode 100644 dist/esm/spec.types.js delete mode 100644 dist/esm/spec.types.js.map delete mode 100644 dist/esm/types.d.ts delete mode 100644 dist/esm/types.d.ts.map delete mode 100644 dist/esm/types.js delete mode 100644 dist/esm/types.js.map delete mode 100644 dist/esm/validation/ajv-provider.d.ts delete mode 100644 dist/esm/validation/ajv-provider.d.ts.map delete mode 100644 dist/esm/validation/ajv-provider.js delete mode 100644 dist/esm/validation/ajv-provider.js.map delete mode 100644 dist/esm/validation/cfworker-provider.d.ts delete mode 100644 dist/esm/validation/cfworker-provider.d.ts.map delete mode 100644 dist/esm/validation/cfworker-provider.js delete mode 100644 dist/esm/validation/cfworker-provider.js.map delete mode 100644 dist/esm/validation/index.d.ts delete mode 100644 dist/esm/validation/index.d.ts.map delete mode 100644 dist/esm/validation/index.js delete mode 100644 dist/esm/validation/index.js.map delete mode 100644 dist/esm/validation/types.d.ts delete mode 100644 dist/esm/validation/types.d.ts.map delete mode 100644 dist/esm/validation/types.js delete mode 100644 dist/esm/validation/types.js.map diff --git a/dist/cjs/client/auth.d.ts b/dist/cjs/client/auth.d.ts deleted file mode 100644 index 0bf7a645e4..0000000000 --- a/dist/cjs/client/auth.d.ts +++ /dev/null @@ -1,280 +0,0 @@ -import { OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens, OAuthMetadata, OAuthClientInformationFull, OAuthProtectedResourceMetadata, AuthorizationServerMetadata } from '../shared/auth.js'; -import { OAuthError } from '../server/auth/errors.js'; -import { FetchLike } from '../shared/transport.js'; -/** - * Implements an end-to-end OAuth client to be used with one MCP server. - * - * This client relies upon a concept of an authorized "session," the exact - * meaning of which is application-defined. Tokens, authorization codes, and - * code verifiers should not cross different sessions. - */ -export interface OAuthClientProvider { - /** - * The URL to redirect the user agent to after authorization. - */ - get redirectUrl(): string | URL; - /** - * External URL the server should use to fetch client metadata document - */ - clientMetadataUrl?: string; - /** - * Metadata about this OAuth client. - */ - get clientMetadata(): OAuthClientMetadata; - /** - * Returns a OAuth2 state parameter. - */ - state?(): string | Promise; - /** - * Loads information about this OAuth client, as registered already with the - * server, or returns `undefined` if the client is not registered with the - * server. - */ - clientInformation(): OAuthClientInformationMixed | undefined | Promise; - /** - * If implemented, this permits the OAuth client to dynamically register with - * the server. Client information saved this way should later be read via - * `clientInformation()`. - * - * This method is not required to be implemented if client information is - * statically known (e.g., pre-registered). - */ - saveClientInformation?(clientInformation: OAuthClientInformationMixed): void | Promise; - /** - * Loads any existing OAuth tokens for the current session, or returns - * `undefined` if there are no saved tokens. - */ - tokens(): OAuthTokens | undefined | Promise; - /** - * Stores new OAuth tokens for the current session, after a successful - * authorization. - */ - saveTokens(tokens: OAuthTokens): void | Promise; - /** - * Invoked to redirect the user agent to the given URL to begin the authorization flow. - */ - redirectToAuthorization(authorizationUrl: URL): void | Promise; - /** - * Saves a PKCE code verifier for the current session, before redirecting to - * the authorization flow. - */ - saveCodeVerifier(codeVerifier: string): void | Promise; - /** - * Loads the PKCE code verifier for the current session, necessary to validate - * the authorization result. - */ - codeVerifier(): string | Promise; - /** - * Adds custom client authentication to OAuth token requests. - * - * This optional method allows implementations to customize how client credentials - * are included in token exchange and refresh requests. When provided, this method - * is called instead of the default authentication logic, giving full control over - * the authentication mechanism. - * - * Common use cases include: - * - Supporting authentication methods beyond the standard OAuth 2.0 methods - * - Adding custom headers for proprietary authentication schemes - * - Implementing client assertion-based authentication (e.g., JWT bearer tokens) - * - * @param headers - The request headers (can be modified to add authentication) - * @param params - The request body parameters (can be modified to add credentials) - * @param url - The token endpoint URL being called - * @param metadata - Optional OAuth metadata for the server, which may include supported authentication methods - */ - addClientAuthentication?(headers: Headers, params: URLSearchParams, url: string | URL, metadata?: AuthorizationServerMetadata): void | Promise; - /** - * If defined, overrides the selection and validation of the - * RFC 8707 Resource Indicator. If left undefined, default - * validation behavior will be used. - * - * Implementations must verify the returned resource matches the MCP server. - */ - validateResourceURL?(serverUrl: string | URL, resource?: string): Promise; - /** - * If implemented, provides a way for the client to invalidate (e.g. delete) the specified - * credentials, in the case where the server has indicated that they are no longer valid. - * This avoids requiring the user to intervene manually. - */ - invalidateCredentials?(scope: 'all' | 'client' | 'tokens' | 'verifier'): void | Promise; -} -export type AuthResult = 'AUTHORIZED' | 'REDIRECT'; -export declare class UnauthorizedError extends Error { - constructor(message?: string); -} -type ClientAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'none'; -/** - * Determines the best client authentication method to use based on server support and client configuration. - * - * Priority order (highest to lowest): - * 1. client_secret_basic (if client secret is available) - * 2. client_secret_post (if client secret is available) - * 3. none (for public clients) - * - * @param clientInformation - OAuth client information containing credentials - * @param supportedMethods - Authentication methods supported by the authorization server - * @returns The selected authentication method - */ -export declare function selectClientAuthMethod(clientInformation: OAuthClientInformationMixed, supportedMethods: string[]): ClientAuthMethod; -/** - * Parses an OAuth error response from a string or Response object. - * - * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec - * and an instance of the appropriate OAuthError subclass will be returned. - * If parsing fails, it falls back to a generic ServerError that includes - * the response status (if available) and original content. - * - * @param input - A Response object or string containing the error response - * @returns A Promise that resolves to an OAuthError instance - */ -export declare function parseErrorResponse(input: Response | string): Promise; -/** - * Orchestrates the full auth flow with a server. - * - * This can be used as a single entry point for all authorization functionality, - * instead of linking together the other lower-level functions in this module. - */ -export declare function auth(provider: OAuthClientProvider, options: { - serverUrl: string | URL; - authorizationCode?: string; - scope?: string; - resourceMetadataUrl?: URL; - fetchFn?: FetchLike; -}): Promise; -/** - * SEP-991: URL-based Client IDs - * Validate that the client_id is a valid URL with https scheme - */ -export declare function isHttpsUrl(value?: string): boolean; -export declare function selectResourceURL(serverUrl: string | URL, provider: OAuthClientProvider, resourceMetadata?: OAuthProtectedResourceMetadata): Promise; -/** - * Extract resource_metadata, scope, and error from WWW-Authenticate header. - */ -export declare function extractWWWAuthenticateParams(res: Response): { - resourceMetadataUrl?: URL; - scope?: string; - error?: string; -}; -/** - * Extract resource_metadata from response header. - * @deprecated Use `extractWWWAuthenticateParams` instead. - */ -export declare function extractResourceMetadataUrl(res: Response): URL | undefined; -/** - * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata. - * - * If the server returns a 404 for the well-known endpoint, this function will - * return `undefined`. Any other errors will be thrown as exceptions. - */ -export declare function discoverOAuthProtectedResourceMetadata(serverUrl: string | URL, opts?: { - protocolVersion?: string; - resourceMetadataUrl?: string | URL; -}, fetchFn?: FetchLike): Promise; -/** - * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata. - * - * If the server returns a 404 for the well-known endpoint, this function will - * return `undefined`. Any other errors will be thrown as exceptions. - * - * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`. - */ -export declare function discoverOAuthMetadata(issuer: string | URL, { authorizationServerUrl, protocolVersion }?: { - authorizationServerUrl?: string | URL; - protocolVersion?: string; -}, fetchFn?: FetchLike): Promise; -/** - * Builds a list of discovery URLs to try for authorization server metadata. - * URLs are returned in priority order: - * 1. OAuth metadata at the given URL - * 2. OIDC metadata endpoints at the given URL - */ -export declare function buildDiscoveryUrls(authorizationServerUrl: string | URL): { - url: URL; - type: 'oauth' | 'oidc'; -}[]; -/** - * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata - * and OpenID Connect Discovery 1.0 specifications. - * - * This function implements a fallback strategy for authorization server discovery: - * 1. Attempts RFC 8414 OAuth metadata discovery first - * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery - * - * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's - * protected resource metadata, or the MCP server's URL if the - * metadata was not found. - * @param options - Configuration options - * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch - * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION - * @returns Promise resolving to authorization server metadata, or undefined if discovery fails - */ -export declare function discoverAuthorizationServerMetadata(authorizationServerUrl: string | URL, { fetchFn, protocolVersion }?: { - fetchFn?: FetchLike; - protocolVersion?: string; -}): Promise; -/** - * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL. - */ -export declare function startAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, redirectUrl, scope, state, resource }: { - metadata?: AuthorizationServerMetadata; - clientInformation: OAuthClientInformationMixed; - redirectUrl: string | URL; - scope?: string; - state?: string; - resource?: URL; -}): Promise<{ - authorizationUrl: URL; - codeVerifier: string; -}>; -/** - * Exchanges an authorization code for an access token with the given server. - * - * Supports multiple client authentication methods as specified in OAuth 2.1: - * - Automatically selects the best authentication method based on server support - * - Falls back to appropriate defaults when server metadata is unavailable - * - * @param authorizationServerUrl - The authorization server's base URL - * @param options - Configuration object containing client info, auth code, etc. - * @returns Promise resolving to OAuth tokens - * @throws {Error} When token exchange fails or authentication is invalid - */ -export declare function exchangeAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }: { - metadata?: AuthorizationServerMetadata; - clientInformation: OAuthClientInformationMixed; - authorizationCode: string; - codeVerifier: string; - redirectUri: string | URL; - resource?: URL; - addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; - fetchFn?: FetchLike; -}): Promise; -/** - * Exchange a refresh token for an updated access token. - * - * Supports multiple client authentication methods as specified in OAuth 2.1: - * - Automatically selects the best authentication method based on server support - * - Preserves the original refresh token if a new one is not returned - * - * @param authorizationServerUrl - The authorization server's base URL - * @param options - Configuration object containing client info, refresh token, etc. - * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced) - * @throws {Error} When token refresh fails or authentication is invalid - */ -export declare function refreshAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }: { - metadata?: AuthorizationServerMetadata; - clientInformation: OAuthClientInformationMixed; - refreshToken: string; - resource?: URL; - addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; - fetchFn?: FetchLike; -}): Promise; -/** - * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. - */ -export declare function registerClient(authorizationServerUrl: string | URL, { metadata, clientMetadata, fetchFn }: { - metadata?: AuthorizationServerMetadata; - clientMetadata: OAuthClientMetadata; - fetchFn?: FetchLike; -}): Promise; -export {}; -//# sourceMappingURL=auth.d.ts.map \ No newline at end of file diff --git a/dist/cjs/client/auth.d.ts.map b/dist/cjs/client/auth.d.ts.map deleted file mode 100644 index ef03546f80..0000000000 --- a/dist/cjs/client/auth.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/client/auth.ts"],"names":[],"mappings":"AAEA,OAAO,EACH,mBAAmB,EAEnB,2BAA2B,EAC3B,WAAW,EACX,aAAa,EACb,0BAA0B,EAC1B,8BAA8B,EAE9B,2BAA2B,EAE9B,MAAM,mBAAmB,CAAC;AAQ3B,OAAO,EAKH,UAAU,EAGb,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;;;;;GAMG;AACH,MAAM,WAAW,mBAAmB;IAChC;;OAEG;IACH,IAAI,WAAW,IAAI,MAAM,GAAG,GAAG,CAAC;IAEhC;;OAEG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;OAEG;IACH,IAAI,cAAc,IAAI,mBAAmB,CAAC;IAE1C;;OAEG;IACH,KAAK,CAAC,IAAI,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAEnC;;;;OAIG;IACH,iBAAiB,IAAI,2BAA2B,GAAG,SAAS,GAAG,OAAO,CAAC,2BAA2B,GAAG,SAAS,CAAC,CAAC;IAEhH;;;;;;;OAOG;IACH,qB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GAAG,GAAG,EACpC,EACI,QAAQ,EACR,cAAc,EACd,OAAO,EACV,EAAE;IACC,QAAQ,CAAC,EAAE,2BAA2B,CAAC;IACvC,cAAc,EAAE,mBAAmB,CAAC;IACpC,OAAO,CAAC,EAAE,SAAS,CAAC;CACvB,GACF,OAAO,CAAC,0BAA0B,CAAC,CA0BrC"} \ No newline at end of file diff --git a/dist/cjs/client/auth.js b/dist/cjs/client/auth.js deleted file mode 100644 index c929497b14..0000000000 --- a/dist/cjs/client/auth.js +++ /dev/null @@ -1,799 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.UnauthorizedError = void 0; -exports.selectClientAuthMethod = selectClientAuthMethod; -exports.parseErrorResponse = parseErrorResponse; -exports.auth = auth; -exports.isHttpsUrl = isHttpsUrl; -exports.selectResourceURL = selectResourceURL; -exports.extractWWWAuthenticateParams = extractWWWAuthenticateParams; -exports.extractResourceMetadataUrl = extractResourceMetadataUrl; -exports.discoverOAuthProtectedResourceMetadata = discoverOAuthProtectedResourceMetadata; -exports.discoverOAuthMetadata = discoverOAuthMetadata; -exports.buildDiscoveryUrls = buildDiscoveryUrls; -exports.discoverAuthorizationServerMetadata = discoverAuthorizationServerMetadata; -exports.startAuthorization = startAuthorization; -exports.exchangeAuthorization = exchangeAuthorization; -exports.refreshAuthorization = refreshAuthorization; -exports.registerClient = registerClient; -const pkce_challenge_1 = __importDefault(require("pkce-challenge")); -const types_js_1 = require("../types.js"); -const auth_js_1 = require("../shared/auth.js"); -const auth_js_2 = require("../shared/auth.js"); -const auth_utils_js_1 = require("../shared/auth-utils.js"); -const errors_js_1 = require("../server/auth/errors.js"); -class UnauthorizedError extends Error { - constructor(message) { - super(message !== null && message !== void 0 ? message : 'Unauthorized'); - } -} -exports.UnauthorizedError = UnauthorizedError; -function isClientAuthMethod(method) { - return ['client_secret_basic', 'client_secret_post', 'none'].includes(method); -} -const AUTHORIZATION_CODE_RESPONSE_TYPE = 'code'; -const AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256'; -/** - * Determines the best client authentication method to use based on server support and client configuration. - * - * Priority order (highest to lowest): - * 1. client_secret_basic (if client secret is available) - * 2. client_secret_post (if client secret is available) - * 3. none (for public clients) - * - * @param clientInformation - OAuth client information containing credentials - * @param supportedMethods - Authentication methods supported by the authorization server - * @returns The selected authentication method - */ -function selectClientAuthMethod(clientInformation, supportedMethods) { - const hasClientSecret = clientInformation.client_secret !== undefined; - // If server doesn't specify supported methods, use RFC 6749 defaults - if (supportedMethods.length === 0) { - return hasClientSecret ? 'client_secret_post' : 'none'; - } - // Prefer the method returned by the server during client registration if valid and supported - if ('token_endpoint_auth_method' in clientInformation && - clientInformation.token_endpoint_auth_method && - isClientAuthMethod(clientInformation.token_endpoint_auth_method) && - supportedMethods.includes(clientInformation.token_endpoint_auth_method)) { - return clientInformation.token_endpoint_auth_method; - } - // Try methods in priority order (most secure first) - if (hasClientSecret && supportedMethods.includes('client_secret_basic')) { - return 'client_secret_basic'; - } - if (hasClientSecret && supportedMethods.includes('client_secret_post')) { - return 'client_secret_post'; - } - if (supportedMethods.includes('none')) { - return 'none'; - } - // Fallback: use what we have - return hasClientSecret ? 'client_secret_post' : 'none'; -} -/** - * Applies client authentication to the request based on the specified method. - * - * Implements OAuth 2.1 client authentication methods: - * - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1) - * - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1) - * - none: Public client authentication (RFC 6749 Section 2.1) - * - * @param method - The authentication method to use - * @param clientInformation - OAuth client information containing credentials - * @param headers - HTTP headers object to modify - * @param params - URL search parameters to modify - * @throws {Error} When required credentials are missing - */ -function applyClientAuthentication(method, clientInformation, headers, params) { - const { client_id, client_secret } = clientInformation; - switch (method) { - case 'client_secret_basic': - applyBasicAuth(client_id, client_secret, headers); - return; - case 'client_secret_post': - applyPostAuth(client_id, client_secret, params); - return; - case 'none': - applyPublicAuth(client_id, params); - return; - default: - throw new Error(`Unsupported client authentication method: ${method}`); - } -} -/** - * Applies HTTP Basic authentication (RFC 6749 Section 2.3.1) - */ -function applyBasicAuth(clientId, clientSecret, headers) { - if (!clientSecret) { - throw new Error('client_secret_basic authentication requires a client_secret'); - } - const credentials = btoa(`${clientId}:${clientSecret}`); - headers.set('Authorization', `Basic ${credentials}`); -} -/** - * Applies POST body authentication (RFC 6749 Section 2.3.1) - */ -function applyPostAuth(clientId, clientSecret, params) { - params.set('client_id', clientId); - if (clientSecret) { - params.set('client_secret', clientSecret); - } -} -/** - * Applies public client authentication (RFC 6749 Section 2.1) - */ -function applyPublicAuth(clientId, params) { - params.set('client_id', clientId); -} -/** - * Parses an OAuth error response from a string or Response object. - * - * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec - * and an instance of the appropriate OAuthError subclass will be returned. - * If parsing fails, it falls back to a generic ServerError that includes - * the response status (if available) and original content. - * - * @param input - A Response object or string containing the error response - * @returns A Promise that resolves to an OAuthError instance - */ -async function parseErrorResponse(input) { - const statusCode = input instanceof Response ? input.status : undefined; - const body = input instanceof Response ? await input.text() : input; - try { - const result = auth_js_1.OAuthErrorResponseSchema.parse(JSON.parse(body)); - const { error, error_description, error_uri } = result; - const errorClass = errors_js_1.OAUTH_ERRORS[error] || errors_js_1.ServerError; - return new errorClass(error_description || '', error_uri); - } - catch (error) { - // Not a valid OAuth error response, but try to inform the user of the raw data anyway - const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}Invalid OAuth error response: ${error}. Raw body: ${body}`; - return new errors_js_1.ServerError(errorMessage); - } -} -/** - * Orchestrates the full auth flow with a server. - * - * This can be used as a single entry point for all authorization functionality, - * instead of linking together the other lower-level functions in this module. - */ -async function auth(provider, options) { - var _a, _b; - try { - return await authInternal(provider, options); - } - catch (error) { - // Handle recoverable error types by invalidating credentials and retrying - if (error instanceof errors_js_1.InvalidClientError || error instanceof errors_js_1.UnauthorizedClientError) { - await ((_a = provider.invalidateCredentials) === null || _a === void 0 ? void 0 : _a.call(provider, 'all')); - return await authInternal(provider, options); - } - else if (error instanceof errors_js_1.InvalidGrantError) { - await ((_b = provider.invalidateCredentials) === null || _b === void 0 ? void 0 : _b.call(provider, 'tokens')); - return await authInternal(provider, options); - } - // Throw otherwise - throw error; - } -} -async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) { - var _a, _b; - let resourceMetadata; - let authorizationServerUrl; - try { - resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn); - if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { - authorizationServerUrl = resourceMetadata.authorization_servers[0]; - } - } - catch (_c) { - // Ignore errors and fall back to /.well-known/oauth-authorization-server - } - /** - * If we don't get a valid authorization server metadata from protected resource metadata, - * fallback to the legacy MCP spec's implementation (version 2025-03-26): MCP server base URL acts as the Authorization server. - */ - if (!authorizationServerUrl) { - authorizationServerUrl = new URL('/', serverUrl); - } - const resource = await selectResourceURL(serverUrl, provider, resourceMetadata); - const metadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { - fetchFn - }); - // Handle client registration if needed - let clientInformation = await Promise.resolve(provider.clientInformation()); - if (!clientInformation) { - if (authorizationCode !== undefined) { - throw new Error('Existing OAuth client information is required when exchanging an authorization code'); - } - const supportsUrlBasedClientId = (metadata === null || metadata === void 0 ? void 0 : metadata.client_id_metadata_document_supported) === true; - const clientMetadataUrl = provider.clientMetadataUrl; - if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) { - throw new errors_js_1.InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`); - } - const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl; - if (shouldUseUrlBasedClientId) { - // SEP-991: URL-based Client IDs - clientInformation = { - client_id: clientMetadataUrl - }; - await ((_a = provider.saveClientInformation) === null || _a === void 0 ? void 0 : _a.call(provider, clientInformation)); - } - else { - // Fallback to dynamic registration - if (!provider.saveClientInformation) { - throw new Error('OAuth client information must be saveable for dynamic registration'); - } - const fullInformation = await registerClient(authorizationServerUrl, { - metadata, - clientMetadata: provider.clientMetadata, - fetchFn - }); - await provider.saveClientInformation(fullInformation); - clientInformation = fullInformation; - } - } - // Exchange authorization code for tokens - if (authorizationCode !== undefined) { - const codeVerifier = await provider.codeVerifier(); - const tokens = await exchangeAuthorization(authorizationServerUrl, { - metadata, - clientInformation, - authorizationCode, - codeVerifier, - redirectUri: provider.redirectUrl, - resource, - addClientAuthentication: provider.addClientAuthentication, - fetchFn: fetchFn - }); - await provider.saveTokens(tokens); - return 'AUTHORIZED'; - } - const tokens = await provider.tokens(); - // Handle token refresh or new authorization - if (tokens === null || tokens === void 0 ? void 0 : tokens.refresh_token) { - try { - // Attempt to refresh the token - const newTokens = await refreshAuthorization(authorizationServerUrl, { - metadata, - clientInformation, - refreshToken: tokens.refresh_token, - resource, - addClientAuthentication: provider.addClientAuthentication, - fetchFn - }); - await provider.saveTokens(newTokens); - return 'AUTHORIZED'; - } - catch (error) { - // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry. - if (!(error instanceof errors_js_1.OAuthError) || error instanceof errors_js_1.ServerError) { - // Could not refresh OAuth tokens - } - else { - // Refresh failed for another reason, re-throw - throw error; - } - } - } - const state = provider.state ? await provider.state() : undefined; - // Start new authorization flow - const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, { - metadata, - clientInformation, - state, - redirectUrl: provider.redirectUrl, - scope: scope || ((_b = resourceMetadata === null || resourceMetadata === void 0 ? void 0 : resourceMetadata.scopes_supported) === null || _b === void 0 ? void 0 : _b.join(' ')) || provider.clientMetadata.scope, - resource - }); - await provider.saveCodeVerifier(codeVerifier); - await provider.redirectToAuthorization(authorizationUrl); - return 'REDIRECT'; -} -/** - * SEP-991: URL-based Client IDs - * Validate that the client_id is a valid URL with https scheme - */ -function isHttpsUrl(value) { - if (!value) - return false; - try { - const url = new URL(value); - return url.protocol === 'https:' && url.pathname !== '/'; - } - catch (_a) { - return false; - } -} -async function selectResourceURL(serverUrl, provider, resourceMetadata) { - const defaultResource = (0, auth_utils_js_1.resourceUrlFromServerUrl)(serverUrl); - // If provider has custom validation, delegate to it - if (provider.validateResourceURL) { - return await provider.validateResourceURL(defaultResource, resourceMetadata === null || resourceMetadata === void 0 ? void 0 : resourceMetadata.resource); - } - // Only include resource parameter when Protected Resource Metadata is present - if (!resourceMetadata) { - return undefined; - } - // Validate that the metadata's resource is compatible with our request - if (!(0, auth_utils_js_1.checkResourceAllowed)({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) { - throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`); - } - // Prefer the resource from metadata since it's what the server is telling us to request - return new URL(resourceMetadata.resource); -} -/** - * Extract resource_metadata, scope, and error from WWW-Authenticate header. - */ -function extractWWWAuthenticateParams(res) { - const authenticateHeader = res.headers.get('WWW-Authenticate'); - if (!authenticateHeader) { - return {}; - } - const [type, scheme] = authenticateHeader.split(' '); - if (type.toLowerCase() !== 'bearer' || !scheme) { - return {}; - } - const resourceMetadataMatch = extractFieldFromWwwAuth(res, 'resource_metadata') || undefined; - let resourceMetadataUrl; - if (resourceMetadataMatch) { - try { - resourceMetadataUrl = new URL(resourceMetadataMatch); - } - catch (_a) { - // Ignore invalid URL - } - } - const scope = extractFieldFromWwwAuth(res, 'scope') || undefined; - const error = extractFieldFromWwwAuth(res, 'error') || undefined; - return { - resourceMetadataUrl, - scope, - error - }; -} -/** - * Extracts a specific field's value from the WWW-Authenticate header string. - * - * @param response The HTTP response object containing the headers. - * @param fieldName The name of the field to extract (e.g., "realm", "nonce"). - * @returns The field value - */ -function extractFieldFromWwwAuth(response, fieldName) { - const wwwAuthHeader = response.headers.get('WWW-Authenticate'); - if (!wwwAuthHeader) { - return null; - } - const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`); - const match = wwwAuthHeader.match(pattern); - if (match) { - // Pattern matches: field_name="value" or field_name=value (unquoted) - return match[1] || match[2]; - } - return null; -} -/** - * Extract resource_metadata from response header. - * @deprecated Use `extractWWWAuthenticateParams` instead. - */ -function extractResourceMetadataUrl(res) { - const authenticateHeader = res.headers.get('WWW-Authenticate'); - if (!authenticateHeader) { - return undefined; - } - const [type, scheme] = authenticateHeader.split(' '); - if (type.toLowerCase() !== 'bearer' || !scheme) { - return undefined; - } - const regex = /resource_metadata="([^"]*)"/; - const match = regex.exec(authenticateHeader); - if (!match) { - return undefined; - } - try { - return new URL(match[1]); - } - catch (_a) { - return undefined; - } -} -/** - * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata. - * - * If the server returns a 404 for the well-known endpoint, this function will - * return `undefined`. Any other errors will be thrown as exceptions. - */ -async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) { - const response = await discoverMetadataWithFallback(serverUrl, 'oauth-protected-resource', fetchFn, { - protocolVersion: opts === null || opts === void 0 ? void 0 : opts.protocolVersion, - metadataUrl: opts === null || opts === void 0 ? void 0 : opts.resourceMetadataUrl - }); - if (!response || response.status === 404) { - throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`); - } - if (!response.ok) { - throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`); - } - return auth_js_2.OAuthProtectedResourceMetadataSchema.parse(await response.json()); -} -/** - * Helper function to handle fetch with CORS retry logic - */ -async function fetchWithCorsRetry(url, headers, fetchFn = fetch) { - try { - return await fetchFn(url, { headers }); - } - catch (error) { - if (error instanceof TypeError) { - if (headers) { - // CORS errors come back as TypeError, retry without headers - return fetchWithCorsRetry(url, undefined, fetchFn); - } - else { - // We're getting CORS errors on retry too, return undefined - return undefined; - } - } - throw error; - } -} -/** - * Constructs the well-known path for auth-related metadata discovery - */ -function buildWellKnownPath(wellKnownPrefix, pathname = '', options = {}) { - // Strip trailing slash from pathname to avoid double slashes - if (pathname.endsWith('/')) { - pathname = pathname.slice(0, -1); - } - return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`; -} -/** - * Tries to discover OAuth metadata at a specific URL - */ -async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) { - const headers = { - 'MCP-Protocol-Version': protocolVersion - }; - return await fetchWithCorsRetry(url, headers, fetchFn); -} -/** - * Determines if fallback to root discovery should be attempted - */ -function shouldAttemptFallback(response, pathname) { - return !response || (response.status >= 400 && response.status < 500 && pathname !== '/'); -} -/** - * Generic function for discovering OAuth metadata with fallback support - */ -async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) { - var _a, _b; - const issuer = new URL(serverUrl); - const protocolVersion = (_a = opts === null || opts === void 0 ? void 0 : opts.protocolVersion) !== null && _a !== void 0 ? _a : types_js_1.LATEST_PROTOCOL_VERSION; - let url; - if (opts === null || opts === void 0 ? void 0 : opts.metadataUrl) { - url = new URL(opts.metadataUrl); - } - else { - // Try path-aware discovery first - const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname); - url = new URL(wellKnownPath, (_b = opts === null || opts === void 0 ? void 0 : opts.metadataServerUrl) !== null && _b !== void 0 ? _b : issuer); - url.search = issuer.search; - } - let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn); - // If path-aware discovery fails with 404 and we're not already at root, try fallback to root discovery - if (!(opts === null || opts === void 0 ? void 0 : opts.metadataUrl) && shouldAttemptFallback(response, issuer.pathname)) { - const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer); - response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn); - } - return response; -} -/** - * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata. - * - * If the server returns a 404 for the well-known endpoint, this function will - * return `undefined`. Any other errors will be thrown as exceptions. - * - * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`. - */ -async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) { - if (typeof issuer === 'string') { - issuer = new URL(issuer); - } - if (!authorizationServerUrl) { - authorizationServerUrl = issuer; - } - if (typeof authorizationServerUrl === 'string') { - authorizationServerUrl = new URL(authorizationServerUrl); - } - protocolVersion !== null && protocolVersion !== void 0 ? protocolVersion : (protocolVersion = types_js_1.LATEST_PROTOCOL_VERSION); - const response = await discoverMetadataWithFallback(authorizationServerUrl, 'oauth-authorization-server', fetchFn, { - protocolVersion, - metadataServerUrl: authorizationServerUrl - }); - if (!response || response.status === 404) { - return undefined; - } - if (!response.ok) { - throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`); - } - return auth_js_2.OAuthMetadataSchema.parse(await response.json()); -} -/** - * Builds a list of discovery URLs to try for authorization server metadata. - * URLs are returned in priority order: - * 1. OAuth metadata at the given URL - * 2. OIDC metadata endpoints at the given URL - */ -function buildDiscoveryUrls(authorizationServerUrl) { - const url = typeof authorizationServerUrl === 'string' ? new URL(authorizationServerUrl) : authorizationServerUrl; - const hasPath = url.pathname !== '/'; - const urlsToTry = []; - if (!hasPath) { - // Root path: https://example.com/.well-known/oauth-authorization-server - urlsToTry.push({ - url: new URL('/.well-known/oauth-authorization-server', url.origin), - type: 'oauth' - }); - // OIDC: https://example.com/.well-known/openid-configuration - urlsToTry.push({ - url: new URL(`/.well-known/openid-configuration`, url.origin), - type: 'oidc' - }); - return urlsToTry; - } - // Strip trailing slash from pathname to avoid double slashes - let pathname = url.pathname; - if (pathname.endsWith('/')) { - pathname = pathname.slice(0, -1); - } - // 1. OAuth metadata at the given URL - // Insert well-known before the path: https://example.com/.well-known/oauth-authorization-server/tenant1 - urlsToTry.push({ - url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin), - type: 'oauth' - }); - // 2. OIDC metadata endpoints - // RFC 8414 style: Insert /.well-known/openid-configuration before the path - urlsToTry.push({ - url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin), - type: 'oidc' - }); - // OIDC Discovery 1.0 style: Append /.well-known/openid-configuration after the path - urlsToTry.push({ - url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin), - type: 'oidc' - }); - return urlsToTry; -} -/** - * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata - * and OpenID Connect Discovery 1.0 specifications. - * - * This function implements a fallback strategy for authorization server discovery: - * 1. Attempts RFC 8414 OAuth metadata discovery first - * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery - * - * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's - * protected resource metadata, or the MCP server's URL if the - * metadata was not found. - * @param options - Configuration options - * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch - * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION - * @returns Promise resolving to authorization server metadata, or undefined if discovery fails - */ -async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = types_js_1.LATEST_PROTOCOL_VERSION } = {}) { - const headers = { - 'MCP-Protocol-Version': protocolVersion, - Accept: 'application/json' - }; - // Get the list of URLs to try - const urlsToTry = buildDiscoveryUrls(authorizationServerUrl); - // Try each URL in order - for (const { url: endpointUrl, type } of urlsToTry) { - const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn); - if (!response) { - /** - * CORS error occurred - don't throw as the endpoint may not allow CORS, - * continue trying other possible endpoints - */ - continue; - } - if (!response.ok) { - // Continue looking for any 4xx response code. - if (response.status >= 400 && response.status < 500) { - continue; // Try next URL - } - throw new Error(`HTTP ${response.status} trying to load ${type === 'oauth' ? 'OAuth' : 'OpenID provider'} metadata from ${endpointUrl}`); - } - // Parse and validate based on type - if (type === 'oauth') { - return auth_js_2.OAuthMetadataSchema.parse(await response.json()); - } - else { - return auth_js_1.OpenIdProviderDiscoveryMetadataSchema.parse(await response.json()); - } - } - return undefined; -} -/** - * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL. - */ -async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) { - let authorizationUrl; - if (metadata) { - authorizationUrl = new URL(metadata.authorization_endpoint); - if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) { - throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`); - } - if (metadata.code_challenge_methods_supported && - !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) { - throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`); - } - } - else { - authorizationUrl = new URL('/authorize', authorizationServerUrl); - } - // Generate PKCE challenge - const challenge = await (0, pkce_challenge_1.default)(); - const codeVerifier = challenge.code_verifier; - const codeChallenge = challenge.code_challenge; - authorizationUrl.searchParams.set('response_type', AUTHORIZATION_CODE_RESPONSE_TYPE); - authorizationUrl.searchParams.set('client_id', clientInformation.client_id); - authorizationUrl.searchParams.set('code_challenge', codeChallenge); - authorizationUrl.searchParams.set('code_challenge_method', AUTHORIZATION_CODE_CHALLENGE_METHOD); - authorizationUrl.searchParams.set('redirect_uri', String(redirectUrl)); - if (state) { - authorizationUrl.searchParams.set('state', state); - } - if (scope) { - authorizationUrl.searchParams.set('scope', scope); - } - if (scope === null || scope === void 0 ? void 0 : scope.includes('offline_access')) { - // if the request includes the OIDC-only "offline_access" scope, - // we need to set the prompt to "consent" to ensure the user is prompted to grant offline access - // https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess - authorizationUrl.searchParams.append('prompt', 'consent'); - } - if (resource) { - authorizationUrl.searchParams.set('resource', resource.href); - } - return { authorizationUrl, codeVerifier }; -} -/** - * Exchanges an authorization code for an access token with the given server. - * - * Supports multiple client authentication methods as specified in OAuth 2.1: - * - Automatically selects the best authentication method based on server support - * - Falls back to appropriate defaults when server metadata is unavailable - * - * @param authorizationServerUrl - The authorization server's base URL - * @param options - Configuration object containing client info, auth code, etc. - * @returns Promise resolving to OAuth tokens - * @throws {Error} When token exchange fails or authentication is invalid - */ -async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) { - var _a; - const grantType = 'authorization_code'; - const tokenUrl = (metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL('/token', authorizationServerUrl); - if ((metadata === null || metadata === void 0 ? void 0 : metadata.grant_types_supported) && !metadata.grant_types_supported.includes(grantType)) { - throw new Error(`Incompatible auth server: does not support grant type ${grantType}`); - } - // Exchange code for tokens - const headers = new Headers({ - 'Content-Type': 'application/x-www-form-urlencoded', - Accept: 'application/json' - }); - const params = new URLSearchParams({ - grant_type: grantType, - code: authorizationCode, - code_verifier: codeVerifier, - redirect_uri: String(redirectUri) - }); - if (addClientAuthentication) { - addClientAuthentication(headers, params, authorizationServerUrl, metadata); - } - else { - // Determine and apply client authentication method - const supportedMethods = (_a = metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint_auth_methods_supported) !== null && _a !== void 0 ? _a : []; - const authMethod = selectClientAuthMethod(clientInformation, supportedMethods); - applyClientAuthentication(authMethod, clientInformation, headers, params); - } - if (resource) { - params.set('resource', resource.href); - } - const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, { - method: 'POST', - headers, - body: params - }); - if (!response.ok) { - throw await parseErrorResponse(response); - } - return auth_js_2.OAuthTokensSchema.parse(await response.json()); -} -/** - * Exchange a refresh token for an updated access token. - * - * Supports multiple client authentication methods as specified in OAuth 2.1: - * - Automatically selects the best authentication method based on server support - * - Preserves the original refresh token if a new one is not returned - * - * @param authorizationServerUrl - The authorization server's base URL - * @param options - Configuration object containing client info, refresh token, etc. - * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced) - * @throws {Error} When token refresh fails or authentication is invalid - */ -async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) { - var _a; - const grantType = 'refresh_token'; - let tokenUrl; - if (metadata) { - tokenUrl = new URL(metadata.token_endpoint); - if (metadata.grant_types_supported && !metadata.grant_types_supported.includes(grantType)) { - throw new Error(`Incompatible auth server: does not support grant type ${grantType}`); - } - } - else { - tokenUrl = new URL('/token', authorizationServerUrl); - } - // Exchange refresh token - const headers = new Headers({ - 'Content-Type': 'application/x-www-form-urlencoded' - }); - const params = new URLSearchParams({ - grant_type: grantType, - refresh_token: refreshToken - }); - if (addClientAuthentication) { - addClientAuthentication(headers, params, authorizationServerUrl, metadata); - } - else { - // Determine and apply client authentication method - const supportedMethods = (_a = metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint_auth_methods_supported) !== null && _a !== void 0 ? _a : []; - const authMethod = selectClientAuthMethod(clientInformation, supportedMethods); - applyClientAuthentication(authMethod, clientInformation, headers, params); - } - if (resource) { - params.set('resource', resource.href); - } - const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, { - method: 'POST', - headers, - body: params - }); - if (!response.ok) { - throw await parseErrorResponse(response); - } - return auth_js_2.OAuthTokensSchema.parse({ refresh_token: refreshToken, ...(await response.json()) }); -} -/** - * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. - */ -async function registerClient(authorizationServerUrl, { metadata, clientMetadata, fetchFn }) { - let registrationUrl; - if (metadata) { - if (!metadata.registration_endpoint) { - throw new Error('Incompatible auth server: does not support dynamic client registration'); - } - registrationUrl = new URL(metadata.registration_endpoint); - } - else { - registrationUrl = new URL('/register', authorizationServerUrl); - } - const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(registrationUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(clientMetadata) - }); - if (!response.ok) { - throw await parseErrorResponse(response); - } - return auth_js_2.OAuthClientInformationFullSchema.parse(await response.json()); -} -//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/dist/cjs/client/auth.js.map b/dist/cjs/client/auth.js.map deleted file mode 100644 index 8d17a404c8..0000000000 --- a/dist/cjs/client/auth.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/client/auth.ts"],"names":[],"mappings":";;;;;;AAiLA,wDAiCC;AA+ED,gDAcC;AAQD,oBAyBC;AAwJD,gCAQC;AAED,8CAuBC;AAKD,oEA8BC;AA8BD,gEAsBC;AAQD,wFAkBC;AAgGD,sDAoCC;AAQD,gDAgDC;AAkBD,kFAiDC;AAKD,gDAmEC;AAcD,sDAmEC;AAcD,oDAgEC;AAKD,wCAqCC;AA1oCD,oEAA2C;AAC3C,0CAAsD;AACtD,+CAW2B;AAC3B,+CAK2B;AAC3B,2DAAyF;AACzF,wDAQkC;AAyHlC,MAAa,iBAAkB,SAAQ,KAAK;IACxC,YAAY,OAAgB;QACxB,KAAK,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,cAAc,CAAC,CAAC;IACrC,CAAC;CACJ;AAJD,8CAIC;AAID,SAAS,kBAAkB,CAAC,MAAc;IACtC,OAAO,CAAC,qBAAqB,EAAE,oBAAoB,EAAE,MAAM,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAClF,CAAC;AAED,MAAM,gCAAgC,GAAG,MAAM,CAAC;AAChD,MAAM,mCAAmC,GAAG,MAAM,CAAC;AAEnD;;;;;;;;;;;GAWG;AACH,SAAgB,sBAAsB,CAAC,iBAA8C,EAAE,gBAA0B;IAC7G,MAAM,eAAe,GAAG,iBAAiB,CAAC,aAAa,KAAK,SAAS,CAAC;IAEtE,qEAAqE;IACrE,IAAI,gBAAgB,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAChC,OAAO,eAAe,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,MAAM,CAAC;IAC3D,CAAC;IAED,6FAA6F;IAC7F,IACI,4BAA4B,IAAI,iBAAiB;QACjD,iBAAiB,CAAC,0BAA0B;QAC5C,kBAAkB,CAAC,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CAAC;QAC9F,CAAC;QAED,eAAe,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC;IAC9D,CAAC;SAAM,CAAC;QACJ,eAAe,GAAG,IAAI,GAAG,CAAC,WAAW,EAAE,sBAAsB,CAAC,CAAC;IACnE,CAAC;IAED,MAAM,QAAQ,GAAG,MAAM,CAAC,OAAO,aAAP,OAAO,cAAP,OAAO,GAAI,KAAK,CAAC,CAAC,eAAe,EAAE;QACvD,MAAM,EAAE,MAAM;QACd,OAAO,EAAE;YACL,cAAc,EAAE,kBAAkB;SACrC;QACD,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,cAAc,CAAC;KACvC,CAAC,CAAC;IAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACf,MAAM,MAAM,kBAAkB,CAAC,QAAQ,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,0CAAgC,CAAC,KAAK,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;AACzE,CAAC"} \ No newline at end of file diff --git a/dist/cjs/client/index.d.ts b/dist/cjs/client/index.d.ts deleted file mode 100644 index 03148dd89b..0000000000 --- a/dist/cjs/client/index.d.ts +++ /dev/null @@ -1,379 +0,0 @@ -import { Protocol, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; -import type { Transport } from '../shared/transport.js'; -import { type CallToolRequest, CallToolResultSchema, type ClientCapabilities, type ClientNotification, type ClientRequest, type ClientResult, type CompatibilityCallToolResultSchema, type CompleteRequest, type GetPromptRequest, type Implementation, type ListPromptsRequest, type ListResourcesRequest, type ListResourceTemplatesRequest, type ListToolsRequest, type LoggingLevel, type Notification, type ReadResourceRequest, type Request, type Result, type ServerCapabilities, type SubscribeRequest, type UnsubscribeRequest } from '../types.js'; -import type { jsonSchemaValidator } from '../validation/types.js'; -import { AnyObjectSchema, SchemaOutput } from '../server/zod-compat.js'; -import type { RequestHandlerExtra } from '../shared/protocol.js'; -/** - * Determines which elicitation modes are supported based on declared client capabilities. - * - * According to the spec: - * - An empty elicitation capability object defaults to form mode support (backwards compatibility) - * - URL mode is only supported if explicitly declared - * - * @param capabilities - The client's elicitation capabilities - * @returns An object indicating which modes are supported - */ -export declare function getSupportedElicitationModes(capabilities: ClientCapabilities['elicitation']): { - supportsFormMode: boolean; - supportsUrlMode: boolean; -}; -export type ClientOptions = ProtocolOptions & { - /** - * Capabilities to advertise as being supported by this client. - */ - capabilities?: ClientCapabilities; - /** - * JSON Schema validator for tool output validation. - * - * The validator is used to validate structured content returned by tools - * against their declared output schemas. - * - * @default AjvJsonSchemaValidator - * - * @example - * ```typescript - * // ajv - * const client = new Client( - * { name: 'my-client', version: '1.0.0' }, - * { - * capabilities: {}, - * jsonSchemaValidator: new AjvJsonSchemaValidator() - * } - * ); - * - * // @cfworker/json-schema - * const client = new Client( - * { name: 'my-client', version: '1.0.0' }, - * { - * capabilities: {}, - * jsonSchemaValidator: new CfWorkerJsonSchemaValidator() - * } - * ); - * ``` - */ - jsonSchemaValidator?: jsonSchemaValidator; -}; -/** - * An MCP client on top of a pluggable transport. - * - * The client will automatically begin the initialization flow with the server when connect() is called. - * - * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: - * - * ```typescript - * // Custom schemas - * const CustomRequestSchema = RequestSchema.extend({...}) - * const CustomNotificationSchema = NotificationSchema.extend({...}) - * const CustomResultSchema = ResultSchema.extend({...}) - * - * // Type aliases - * type CustomRequest = z.infer - * type CustomNotification = z.infer - * type CustomResult = z.infer - * - * // Create typed client - * const client = new Client({ - * name: "CustomClient", - * version: "1.0.0" - * }) - * ``` - */ -export declare class Client extends Protocol { - private _clientInfo; - private _serverCapabilities?; - private _serverVersion?; - private _capabilities; - private _instructions?; - private _jsonSchemaValidator; - private _cachedToolOutputValidators; - /** - * Initializes this client with the given name and version information. - */ - constructor(_clientInfo: Implementation, options?: ClientOptions); - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - registerCapabilities(capabilities: ClientCapabilities): void; - /** - * Override request handler registration to enforce client-side validation for elicitation. - */ - setRequestHandler(requestSchema: T, handler: (request: SchemaOutput, extra: RequestHandlerExtra) => ClientResult | ResultT | Promise): void; - protected assertCapability(capability: keyof ServerCapabilities, method: string): void; - connect(transport: Transport, options?: RequestOptions): Promise; - /** - * After initialization has completed, this will be populated with the server's reported capabilities. - */ - getServerCapabilities(): ServerCapabilities | undefined; - /** - * After initialization has completed, this will be populated with information about the server's name and version. - */ - getServerVersion(): Implementation | undefined; - /** - * After initialization has completed, this may be populated with information about the server's instructions. - */ - getInstructions(): string | undefined; - protected assertCapabilityForMethod(method: RequestT['method']): void; - protected assertNotificationCapability(method: NotificationT['method']): void; - protected assertRequestHandlerCapability(method: string): void; - ping(options?: RequestOptions): Promise<{ - _meta?: Record | undefined; - }>; - complete(params: CompleteRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - completion: { - [x: string]: unknown; - values: string[]; - total?: number | undefined; - hasMore?: boolean | undefined; - }; - _meta?: Record | undefined; - }>; - setLoggingLevel(level: LoggingLevel, options?: RequestOptions): Promise<{ - _meta?: Record | undefined; - }>; - getPrompt(params: GetPromptRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - messages: { - role: "user" | "assistant"; - content: { - type: "text"; - text: string; - _meta?: Record | undefined; - } | { - type: "image"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "audio"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "resource"; - resource: { - uri: string; - text: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - } | { - uri: string; - blob: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - }; - _meta?: Record | undefined; - } | { - uri: string; - name: string; - type: "resource_link"; - description?: string | undefined; - mimeType?: string | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - }; - }[]; - _meta?: Record | undefined; - description?: string | undefined; - }>; - listPrompts(params?: ListPromptsRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - prompts: { - name: string; - description?: string | undefined; - arguments?: { - name: string; - description?: string | undefined; - required?: boolean | undefined; - }[] | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - }[]; - _meta?: Record | undefined; - nextCursor?: string | undefined; - }>; - listResources(params?: ListResourcesRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - resources: { - uri: string; - name: string; - description?: string | undefined; - mimeType?: string | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - }[]; - _meta?: Record | undefined; - nextCursor?: string | undefined; - }>; - listResourceTemplates(params?: ListResourceTemplatesRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - resourceTemplates: { - uriTemplate: string; - name: string; - description?: string | undefined; - mimeType?: string | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - }[]; - _meta?: Record | undefined; - nextCursor?: string | undefined; - }>; - readResource(params: ReadResourceRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - contents: ({ - uri: string; - text: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - } | { - uri: string; - blob: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - })[]; - _meta?: Record | undefined; - }>; - subscribeResource(params: SubscribeRequest['params'], options?: RequestOptions): Promise<{ - _meta?: Record | undefined; - }>; - unsubscribeResource(params: UnsubscribeRequest['params'], options?: RequestOptions): Promise<{ - _meta?: Record | undefined; - }>; - callTool(params: CallToolRequest['params'], resultSchema?: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options?: RequestOptions): Promise<{ - [x: string]: unknown; - content: ({ - type: "text"; - text: string; - _meta?: Record | undefined; - } | { - type: "image"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "audio"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "resource"; - resource: { - uri: string; - text: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - } | { - uri: string; - blob: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - }; - _meta?: Record | undefined; - } | { - uri: string; - name: string; - type: "resource_link"; - description?: string | undefined; - mimeType?: string | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - })[]; - _meta?: Record | undefined; - structuredContent?: Record | undefined; - isError?: boolean | undefined; - } | { - [x: string]: unknown; - toolResult: unknown; - _meta?: Record | undefined; - }>; - /** - * Cache validators for tool output schemas. - * Called after listTools() to pre-compile validators for better performance. - */ - private cacheToolOutputSchemas; - /** - * Get cached validator for a tool - */ - private getToolOutputValidator; - listTools(params?: ListToolsRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - tools: { - inputSchema: { - [x: string]: unknown; - type: "object"; - properties?: Record | undefined; - required?: string[] | undefined; - }; - name: string; - description?: string | undefined; - outputSchema?: { - [x: string]: unknown; - type: "object"; - properties?: Record | undefined; - required?: string[] | undefined; - } | undefined; - annotations?: { - title?: string | undefined; - readOnlyHint?: boolean | undefined; - destructiveHint?: boolean | undefined; - idempotentHint?: boolean | undefined; - openWorldHint?: boolean | undefined; - } | undefined; - securitySchemes?: ({ - type: "noauth"; - } | { - type: "oauth2"; - scopes?: string[] | undefined; - })[] | undefined; - _meta?: Record | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - }[]; - _meta?: Record | undefined; - nextCursor?: string | undefined; - }>; - sendRootsListChanged(): Promise; -} -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/cjs/client/index.d.ts.map b/dist/cjs/client/index.d.ts.map deleted file mode 100644 index c19d4ef588..0000000000 --- a/dist/cjs/client/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAAE,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC/G,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EACH,KAAK,eAAe,EACpB,oBAAoB,EACpB,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,YAAY,EACjB,KAAK,iCAAiC,EACtC,KAAK,eAAe,EAIpB,KAAK,gBAAgB,EAErB,KAAK,cAAc,EAGnB,KAAK,kBAAkB,EAEvB,KAAK,oBAAoB,EAEzB,KAAK,4BAA4B,EAEjC,KAAK,gBAAgB,EAErB,KAAK,YAAY,EAEjB,KAAK,YAAY,EACjB,KAAK,mBAAmB,EAExB,KAAK,OAAO,EACZ,KAAK,MAAM,EACX,KAAK,kBAAkB,EAEvB,KAAK,gBAAgB,EAErB,KAAK,kBAAkB,EAG1B,MAAM,aAAa,CAAC;AAErB,OAAO,KAAK,EAAuC,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AACvG,OAAO,EACH,eAAe,EACf,YAAY,EAMf,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AA0CjE;;;;;;;;;GASG;AACH,wBAAgB,4BAA4B,CAAC,YAAY,EAAE,kBAAkB,CAAC,aAAa,CAAC,GAAG;IAC3F,gBAAgB,EAAE,OAAO,CAAC;IAC1B,eAAe,EAAE,OAAO,CAAC;CAC5B,CAaA;AAED,MAAM,MAAM,aAAa,GAAG,eAAe,GAAG;IAC1C;;OAEG;IACH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AAE,cAAc;;;;;;;;;;;;;;;IAI5E,iBAAiB,CAAC,MAAM,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;IAI9E,mBAAmB,CAAC,MAAM,EAAE,kBAAkB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;IAIlF,QAAQ,CACV,MAAM,EAAE,eAAe,CAAC,QAAQ,CAAC,EACjC,YAAY,GAAE,OAAO,oBAAoB,GAAG,OAAO,iCAAwD,EAC3G,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IA0C5B;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IAY9B;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAIxB,SAAS,CAAC,MAAM,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IASvE,oBAAoB;CAG7B"} \ No newline at end of file diff --git a/dist/cjs/client/index.js b/dist/cjs/client/index.js deleted file mode 100644 index 511a2d7d35..0000000000 --- a/dist/cjs/client/index.js +++ /dev/null @@ -1,423 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Client = void 0; -exports.getSupportedElicitationModes = getSupportedElicitationModes; -const protocol_js_1 = require("../shared/protocol.js"); -const types_js_1 = require("../types.js"); -const ajv_provider_js_1 = require("../validation/ajv-provider.js"); -const zod_compat_js_1 = require("../server/zod-compat.js"); -/** - * Elicitation default application helper. Applies defaults to the data based on the schema. - * - * @param schema - The schema to apply defaults to. - * @param data - The data to apply defaults to. - */ -function applyElicitationDefaults(schema, data) { - if (!schema || data === null || typeof data !== 'object') - return; - // Handle object properties - if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') { - const obj = data; - const props = schema.properties; - for (const key of Object.keys(props)) { - const propSchema = props[key]; - // If missing or explicitly undefined, apply default if present - if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) { - obj[key] = propSchema.default; - } - // Recurse into existing nested objects/arrays - if (obj[key] !== undefined) { - applyElicitationDefaults(propSchema, obj[key]); - } - } - } - if (Array.isArray(schema.anyOf)) { - for (const sub of schema.anyOf) { - applyElicitationDefaults(sub, data); - } - } - // Combine schemas - if (Array.isArray(schema.oneOf)) { - for (const sub of schema.oneOf) { - applyElicitationDefaults(sub, data); - } - } -} -/** - * Determines which elicitation modes are supported based on declared client capabilities. - * - * According to the spec: - * - An empty elicitation capability object defaults to form mode support (backwards compatibility) - * - URL mode is only supported if explicitly declared - * - * @param capabilities - The client's elicitation capabilities - * @returns An object indicating which modes are supported - */ -function getSupportedElicitationModes(capabilities) { - if (!capabilities) { - return { supportsFormMode: false, supportsUrlMode: false }; - } - const hasFormCapability = capabilities.form !== undefined; - const hasUrlCapability = capabilities.url !== undefined; - // If neither form nor url are explicitly declared, form mode is supported (backwards compatibility) - const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability); - const supportsUrlMode = hasUrlCapability; - return { supportsFormMode, supportsUrlMode }; -} -/** - * An MCP client on top of a pluggable transport. - * - * The client will automatically begin the initialization flow with the server when connect() is called. - * - * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: - * - * ```typescript - * // Custom schemas - * const CustomRequestSchema = RequestSchema.extend({...}) - * const CustomNotificationSchema = NotificationSchema.extend({...}) - * const CustomResultSchema = ResultSchema.extend({...}) - * - * // Type aliases - * type CustomRequest = z.infer - * type CustomNotification = z.infer - * type CustomResult = z.infer - * - * // Create typed client - * const client = new Client({ - * name: "CustomClient", - * version: "1.0.0" - * }) - * ``` - */ -class Client extends protocol_js_1.Protocol { - /** - * Initializes this client with the given name and version information. - */ - constructor(_clientInfo, options) { - var _a, _b; - super(options); - this._clientInfo = _clientInfo; - this._cachedToolOutputValidators = new Map(); - this._capabilities = (_a = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a !== void 0 ? _a : {}; - this._jsonSchemaValidator = (_b = options === null || options === void 0 ? void 0 : options.jsonSchemaValidator) !== null && _b !== void 0 ? _b : new ajv_provider_js_1.AjvJsonSchemaValidator(); - } - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - registerCapabilities(capabilities) { - if (this.transport) { - throw new Error('Cannot register capabilities after connecting to transport'); - } - this._capabilities = (0, protocol_js_1.mergeCapabilities)(this._capabilities, capabilities); - } - /** - * Override request handler registration to enforce client-side validation for elicitation. - */ - setRequestHandler(requestSchema, handler) { - var _a, _b, _c; - const shape = (0, zod_compat_js_1.getObjectShape)(requestSchema); - const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method; - if (!methodSchema) { - throw new Error('Schema is missing a method literal'); - } - // Extract literal value using type-safe property access - let methodValue; - if ((0, zod_compat_js_1.isZ4Schema)(methodSchema)) { - const v4Schema = methodSchema; - const v4Def = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def; - methodValue = (_b = v4Def === null || v4Def === void 0 ? void 0 : v4Def.value) !== null && _b !== void 0 ? _b : v4Schema.value; - } - else { - const v3Schema = methodSchema; - const legacyDef = v3Schema._def; - methodValue = (_c = legacyDef === null || legacyDef === void 0 ? void 0 : legacyDef.value) !== null && _c !== void 0 ? _c : v3Schema.value; - } - if (typeof methodValue !== 'string') { - throw new Error('Schema method literal must be a string'); - } - const method = methodValue; - if (method === 'elicitation/create') { - const wrappedHandler = async (request, extra) => { - var _a, _b; - const validatedRequest = (0, zod_compat_js_1.safeParse)(types_js_1.ElicitRequestSchema, request); - if (!validatedRequest.success) { - // Type guard: if success is false, error is guaranteed to exist - const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`); - } - const { params } = validatedRequest.data; - const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation); - if (params.mode === 'form' && !supportsFormMode) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests'); - } - if (params.mode === 'url' && !supportsUrlMode) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests'); - } - const result = await Promise.resolve(handler(request, extra)); - const validationResult = (0, zod_compat_js_1.safeParse)(types_js_1.ElicitResultSchema, result); - if (!validationResult.success) { - // Type guard: if success is false, error is guaranteed to exist - const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`); - } - const validatedResult = validationResult.data; - const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined; - if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) { - if ((_b = (_a = this._capabilities.elicitation) === null || _a === void 0 ? void 0 : _a.form) === null || _b === void 0 ? void 0 : _b.applyDefaults) { - try { - applyElicitationDefaults(requestedSchema, validatedResult.content); - } - catch (_c) { - // gracefully ignore errors in default application - } - } - } - return validatedResult; - }; - // Install the wrapped handler - return super.setRequestHandler(requestSchema, wrappedHandler); - } - // Non-elicitation handlers use default behavior - return super.setRequestHandler(requestSchema, handler); - } - assertCapability(capability, method) { - var _a; - if (!((_a = this._serverCapabilities) === null || _a === void 0 ? void 0 : _a[capability])) { - throw new Error(`Server does not support ${capability} (required for ${method})`); - } - } - async connect(transport, options) { - await super.connect(transport); - // When transport sessionId is already set this means we are trying to reconnect. - // In this case we don't need to initialize again. - if (transport.sessionId !== undefined) { - return; - } - try { - const result = await this.request({ - method: 'initialize', - params: { - protocolVersion: types_js_1.LATEST_PROTOCOL_VERSION, - capabilities: this._capabilities, - clientInfo: this._clientInfo - } - }, types_js_1.InitializeResultSchema, options); - if (result === undefined) { - throw new Error(`Server sent invalid initialize result: ${result}`); - } - if (!types_js_1.SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) { - throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`); - } - this._serverCapabilities = result.capabilities; - this._serverVersion = result.serverInfo; - // HTTP transports must set the protocol version in each header after initialization. - if (transport.setProtocolVersion) { - transport.setProtocolVersion(result.protocolVersion); - } - this._instructions = result.instructions; - await this.notification({ - method: 'notifications/initialized' - }); - } - catch (error) { - // Disconnect if initialization fails. - void this.close(); - throw error; - } - } - /** - * After initialization has completed, this will be populated with the server's reported capabilities. - */ - getServerCapabilities() { - return this._serverCapabilities; - } - /** - * After initialization has completed, this will be populated with information about the server's name and version. - */ - getServerVersion() { - return this._serverVersion; - } - /** - * After initialization has completed, this may be populated with information about the server's instructions. - */ - getInstructions() { - return this._instructions; - } - assertCapabilityForMethod(method) { - var _a, _b, _c, _d, _e; - switch (method) { - case 'logging/setLevel': - if (!((_a = this._serverCapabilities) === null || _a === void 0 ? void 0 : _a.logging)) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case 'prompts/get': - case 'prompts/list': - if (!((_b = this._serverCapabilities) === null || _b === void 0 ? void 0 : _b.prompts)) { - throw new Error(`Server does not support prompts (required for ${method})`); - } - break; - case 'resources/list': - case 'resources/templates/list': - case 'resources/read': - case 'resources/subscribe': - case 'resources/unsubscribe': - if (!((_c = this._serverCapabilities) === null || _c === void 0 ? void 0 : _c.resources)) { - throw new Error(`Server does not support resources (required for ${method})`); - } - if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) { - throw new Error(`Server does not support resource subscriptions (required for ${method})`); - } - break; - case 'tools/call': - case 'tools/list': - if (!((_d = this._serverCapabilities) === null || _d === void 0 ? void 0 : _d.tools)) { - throw new Error(`Server does not support tools (required for ${method})`); - } - break; - case 'completion/complete': - if (!((_e = this._serverCapabilities) === null || _e === void 0 ? void 0 : _e.completions)) { - throw new Error(`Server does not support completions (required for ${method})`); - } - break; - case 'initialize': - // No specific capability required for initialize - break; - case 'ping': - // No specific capability required for ping - break; - } - } - assertNotificationCapability(method) { - var _a; - switch (method) { - case 'notifications/roots/list_changed': - if (!((_a = this._capabilities.roots) === null || _a === void 0 ? void 0 : _a.listChanged)) { - throw new Error(`Client does not support roots list changed notifications (required for ${method})`); - } - break; - case 'notifications/initialized': - // No specific capability required for initialized - break; - case 'notifications/cancelled': - // Cancellation notifications are always allowed - break; - case 'notifications/progress': - // Progress notifications are always allowed - break; - } - } - assertRequestHandlerCapability(method) { - switch (method) { - case 'sampling/createMessage': - if (!this._capabilities.sampling) { - throw new Error(`Client does not support sampling capability (required for ${method})`); - } - break; - case 'elicitation/create': - if (!this._capabilities.elicitation) { - throw new Error(`Client does not support elicitation capability (required for ${method})`); - } - break; - case 'roots/list': - if (!this._capabilities.roots) { - throw new Error(`Client does not support roots capability (required for ${method})`); - } - break; - case 'ping': - // No specific capability required for ping - break; - } - } - async ping(options) { - return this.request({ method: 'ping' }, types_js_1.EmptyResultSchema, options); - } - async complete(params, options) { - return this.request({ method: 'completion/complete', params }, types_js_1.CompleteResultSchema, options); - } - async setLoggingLevel(level, options) { - return this.request({ method: 'logging/setLevel', params: { level } }, types_js_1.EmptyResultSchema, options); - } - async getPrompt(params, options) { - return this.request({ method: 'prompts/get', params }, types_js_1.GetPromptResultSchema, options); - } - async listPrompts(params, options) { - return this.request({ method: 'prompts/list', params }, types_js_1.ListPromptsResultSchema, options); - } - async listResources(params, options) { - return this.request({ method: 'resources/list', params }, types_js_1.ListResourcesResultSchema, options); - } - async listResourceTemplates(params, options) { - return this.request({ method: 'resources/templates/list', params }, types_js_1.ListResourceTemplatesResultSchema, options); - } - async readResource(params, options) { - return this.request({ method: 'resources/read', params }, types_js_1.ReadResourceResultSchema, options); - } - async subscribeResource(params, options) { - return this.request({ method: 'resources/subscribe', params }, types_js_1.EmptyResultSchema, options); - } - async unsubscribeResource(params, options) { - return this.request({ method: 'resources/unsubscribe', params }, types_js_1.EmptyResultSchema, options); - } - async callTool(params, resultSchema = types_js_1.CallToolResultSchema, options) { - const result = await this.request({ method: 'tools/call', params }, resultSchema, options); - // Check if the tool has an outputSchema - const validator = this.getToolOutputValidator(params.name); - if (validator) { - // If tool has outputSchema, it MUST return structuredContent (unless it's an error) - if (!result.structuredContent && !result.isError) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`); - } - // Only validate structured content if present (not when there's an error) - if (result.structuredContent) { - try { - // Validate the structured content against the schema - const validationResult = validator(result.structuredContent); - if (!validationResult.valid) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`); - } - } - catch (error) { - if (error instanceof types_js_1.McpError) { - throw error; - } - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`); - } - } - } - return result; - } - /** - * Cache validators for tool output schemas. - * Called after listTools() to pre-compile validators for better performance. - */ - cacheToolOutputSchemas(tools) { - this._cachedToolOutputValidators.clear(); - for (const tool of tools) { - // If the tool has an outputSchema, create and cache the validator - if (tool.outputSchema) { - const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema); - this._cachedToolOutputValidators.set(tool.name, toolValidator); - } - } - } - /** - * Get cached validator for a tool - */ - getToolOutputValidator(toolName) { - return this._cachedToolOutputValidators.get(toolName); - } - async listTools(params, options) { - const result = await this.request({ method: 'tools/list', params }, types_js_1.ListToolsResultSchema, options); - // Cache the tools and their output schemas for future validation - this.cacheToolOutputSchemas(result.tools); - return result; - } - async sendRootsListChanged() { - return this.notification({ method: 'notifications/roots/list_changed' }); - } -} -exports.Client = Client; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/cjs/client/index.js.map b/dist/cjs/client/index.js.map deleted file mode 100644 index 5a2d96c9ee..0000000000 --- a/dist/cjs/client/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client/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,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;gBACpB,MAAM,aAAa,GAAG,IAAI,CAAC,oBAAoB,CAAC,YAAY,CAAC,IAAI,CAAC,YAA8B,CAAC,CAAC;gBAClG,IAAI,CAAC,2BAA2B,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,EAAE,aAAa,CAAC,CAAC;YACnE,CAAC;QACL,CAAC;IACL,CAAC;IAED;;OAEG;IACK,sBAAsB,CAAC,QAAgB;QAC3C,OAAO,IAAI,CAAC,2BAA2B,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC1D,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,MAAmC,EAAE,OAAwB;QACzE,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,EAAE,gCAAqB,EAAE,OAAO,CAAC,CAAC;QAEpG,iEAAiE;QACjE,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAE1C,OAAO,MAAM,CAAC;IAClB,CAAC;IAED,KAAK,CAAC,oBAAoB;QACtB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,kCAAkC,EAAE,CAAC,CAAC;IAC7E,CAAC;CACJ;AAvaD,wBAuaC"} \ No newline at end of file diff --git a/dist/cjs/client/middleware.d.ts b/dist/cjs/client/middleware.d.ts deleted file mode 100644 index 726ac578ae..0000000000 --- a/dist/cjs/client/middleware.d.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { OAuthClientProvider } from './auth.js'; -import { FetchLike } from '../shared/transport.js'; -/** - * Middleware function that wraps and enhances fetch functionality. - * Takes a fetch handler and returns an enhanced fetch handler. - */ -export type Middleware = (next: FetchLike) => FetchLike; -/** - * Creates a fetch wrapper that handles OAuth authentication automatically. - * - * This wrapper will: - * - Add Authorization headers with access tokens - * - Handle 401 responses by attempting re-authentication - * - Retry the original request after successful auth - * - Handle OAuth errors appropriately (InvalidClientError, etc.) - * - * The baseUrl parameter is optional and defaults to using the domain from the request URL. - * However, you should explicitly provide baseUrl when: - * - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com) - * - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /) - * - The OAuth server is on a different domain than your API requests - * - You want to ensure consistent OAuth behavior regardless of request URLs - * - * For MCP transports, set baseUrl to the same URL you pass to the transport constructor. - * - * Note: This wrapper is designed for general-purpose fetch operations. - * MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling - * and should not need this wrapper. - * - * @param provider - OAuth client provider for authentication - * @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain) - * @returns A fetch middleware function - */ -export declare const withOAuth: (provider: OAuthClientProvider, baseUrl?: string | URL) => Middleware; -/** - * Logger function type for HTTP requests - */ -export type RequestLogger = (input: { - method: string; - url: string | URL; - status: number; - statusText: string; - duration: number; - requestHeaders?: Headers; - responseHeaders?: Headers; - error?: Error; -}) => void; -/** - * Configuration options for the logging middleware - */ -export type LoggingOptions = { - /** - * Custom logger function, defaults to console logging - */ - logger?: RequestLogger; - /** - * Whether to include request headers in logs - * @default false - */ - includeRequestHeaders?: boolean; - /** - * Whether to include response headers in logs - * @default false - */ - includeResponseHeaders?: boolean; - /** - * Status level filter - only log requests with status >= this value - * Set to 0 to log all requests, 400 to log only errors - * @default 0 - */ - statusLevel?: number; -}; -/** - * Creates a fetch middleware that logs HTTP requests and responses. - * - * When called without arguments `withLogging()`, it uses the default logger that: - * - Logs successful requests (2xx) to `console.log` - * - Logs error responses (4xx/5xx) and network errors to `console.error` - * - Logs all requests regardless of status (statusLevel: 0) - * - Does not include request or response headers in logs - * - Measures and displays request duration in milliseconds - * - * Important: the default logger uses both `console.log` and `console.error` so it should not be used with - * `stdio` transports and applications. - * - * @param options - Logging configuration options - * @returns A fetch middleware function - */ -export declare const withLogging: (options?: LoggingOptions) => Middleware; -/** - * Composes multiple fetch middleware functions into a single middleware pipeline. - * Middleware are applied in the order they appear, creating a chain of handlers. - * - * @example - * ```typescript - * // Create a middleware pipeline that handles both OAuth and logging - * const enhancedFetch = applyMiddlewares( - * withOAuth(oauthProvider, 'https://api.example.com'), - * withLogging({ statusLevel: 400 }) - * )(fetch); - * - * // Use the enhanced fetch - it will handle auth and log errors - * const response = await enhancedFetch('https://api.example.com/data'); - * ``` - * - * @param middleware - Array of fetch middleware to compose into a pipeline - * @returns A single composed middleware function - */ -export declare const applyMiddlewares: (...middleware: Middleware[]) => Middleware; -/** - * Helper function to create custom fetch middleware with cleaner syntax. - * Provides the next handler and request details as separate parameters for easier access. - * - * @example - * ```typescript - * // Create custom authentication middleware - * const customAuthMiddleware = createMiddleware(async (next, input, init) => { - * const headers = new Headers(init?.headers); - * headers.set('X-Custom-Auth', 'my-token'); - * - * const response = await next(input, { ...init, headers }); - * - * if (response.status === 401) { - * console.log('Authentication failed'); - * } - * - * return response; - * }); - * - * // Create conditional middleware - * const conditionalMiddleware = createMiddleware(async (next, input, init) => { - * const url = typeof input === 'string' ? input : input.toString(); - * - * // Only add headers for API routes - * if (url.includes('/api/')) { - * const headers = new Headers(init?.headers); - * headers.set('X-API-Version', 'v2'); - * return next(input, { ...init, headers }); - * } - * - * // Pass through for non-API routes - * return next(input, init); - * }); - * - * // Create caching middleware - * const cacheMiddleware = createMiddleware(async (next, input, init) => { - * const cacheKey = typeof input === 'string' ? input : input.toString(); - * - * // Check cache first - * const cached = await getFromCache(cacheKey); - * if (cached) { - * return new Response(cached, { status: 200 }); - * } - * - * // Make request and cache result - * const response = await next(input, init); - * if (response.ok) { - * await saveToCache(cacheKey, await response.clone().text()); - * } - * - * return response; - * }); - * ``` - * - * @param handler - Function that receives the next handler and request parameters - * @returns A fetch middleware function - */ -export declare const createMiddleware: (handler: (next: FetchLike, input: string | URL, init?: RequestInit) => Promise) => Middleware; -//# sourceMappingURL=middleware.d.ts.map \ No newline at end of file diff --git a/dist/cjs/client/middleware.d.ts.map b/dist/cjs/client/middleware.d.ts.map deleted file mode 100644 index 88ac77806d..0000000000 --- a/dist/cjs/client/middleware.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../../src/client/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsC,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AACvG,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,CAAC,IAAI,EAAE,SAAS,KAAK,SAAS,CAAC;AAExD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,eAAO,MAAM,SAAS,aACP,mBAAmB,YAAY,MAAM,GAAG,GAAG,KAAG,UA0DxD,CAAC;AAEN;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,CAAC,KAAK,EAAE;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,GAAG,EAAE,MAAM,GAAG,GAAG,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,KAAK,CAAC,EAAE,KAAK,CAAC;CACjB,KAAK,IAAI,CAAC;AAEX;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IACzB;;OAEG;IACH,MAAM,CAAC,EAAE,aAAa,CAAC;IAEvB;;;OAGG;IACH,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAEhC;;;OAGG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;IAEjC;;;;OAIG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;CACxB,CAAC;AAEF;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,WAAW,aAAa,cAAc,KAAQ,UA6E1D,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,eAAO,MAAM,gBAAgB,kBAAmB,UAAU,EAAE,KAAG,UAI9D,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AACH,eAAO,MAAM,gBAAgB,YAAa,CAAC,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,KAAG,UAE3H,CAAC"} \ No newline at end of file diff --git a/dist/cjs/client/middleware.js b/dist/cjs/client/middleware.js deleted file mode 100644 index f5d9dc3aea..0000000000 --- a/dist/cjs/client/middleware.js +++ /dev/null @@ -1,252 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createMiddleware = exports.applyMiddlewares = exports.withLogging = exports.withOAuth = void 0; -const auth_js_1 = require("./auth.js"); -/** - * Creates a fetch wrapper that handles OAuth authentication automatically. - * - * This wrapper will: - * - Add Authorization headers with access tokens - * - Handle 401 responses by attempting re-authentication - * - Retry the original request after successful auth - * - Handle OAuth errors appropriately (InvalidClientError, etc.) - * - * The baseUrl parameter is optional and defaults to using the domain from the request URL. - * However, you should explicitly provide baseUrl when: - * - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com) - * - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /) - * - The OAuth server is on a different domain than your API requests - * - You want to ensure consistent OAuth behavior regardless of request URLs - * - * For MCP transports, set baseUrl to the same URL you pass to the transport constructor. - * - * Note: This wrapper is designed for general-purpose fetch operations. - * MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling - * and should not need this wrapper. - * - * @param provider - OAuth client provider for authentication - * @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain) - * @returns A fetch middleware function - */ -const withOAuth = (provider, baseUrl) => next => { - return async (input, init) => { - const makeRequest = async () => { - const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers); - // Add authorization header if tokens are available - const tokens = await provider.tokens(); - if (tokens) { - headers.set('Authorization', `Bearer ${tokens.access_token}`); - } - return await next(input, { ...init, headers }); - }; - let response = await makeRequest(); - // Handle 401 responses by attempting re-authentication - if (response.status === 401) { - try { - const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response); - // Use provided baseUrl or extract from request URL - const serverUrl = baseUrl || (typeof input === 'string' ? new URL(input).origin : input.origin); - const result = await (0, auth_js_1.auth)(provider, { - serverUrl, - resourceMetadataUrl, - scope, - fetchFn: next - }); - if (result === 'REDIRECT') { - throw new auth_js_1.UnauthorizedError('Authentication requires user authorization - redirect initiated'); - } - if (result !== 'AUTHORIZED') { - throw new auth_js_1.UnauthorizedError(`Authentication failed with result: ${result}`); - } - // Retry the request with fresh tokens - response = await makeRequest(); - } - catch (error) { - if (error instanceof auth_js_1.UnauthorizedError) { - throw error; - } - throw new auth_js_1.UnauthorizedError(`Failed to re-authenticate: ${error instanceof Error ? error.message : String(error)}`); - } - } - // If we still have a 401 after re-auth attempt, throw an error - if (response.status === 401) { - const url = typeof input === 'string' ? input : input.toString(); - throw new auth_js_1.UnauthorizedError(`Authentication failed for ${url}`); - } - return response; - }; -}; -exports.withOAuth = withOAuth; -/** - * Creates a fetch middleware that logs HTTP requests and responses. - * - * When called without arguments `withLogging()`, it uses the default logger that: - * - Logs successful requests (2xx) to `console.log` - * - Logs error responses (4xx/5xx) and network errors to `console.error` - * - Logs all requests regardless of status (statusLevel: 0) - * - Does not include request or response headers in logs - * - Measures and displays request duration in milliseconds - * - * Important: the default logger uses both `console.log` and `console.error` so it should not be used with - * `stdio` transports and applications. - * - * @param options - Logging configuration options - * @returns A fetch middleware function - */ -const withLogging = (options = {}) => { - const { logger, includeRequestHeaders = false, includeResponseHeaders = false, statusLevel = 0 } = options; - const defaultLogger = input => { - const { method, url, status, statusText, duration, requestHeaders, responseHeaders, error } = input; - let message = error - ? `HTTP ${method} ${url} failed: ${error.message} (${duration}ms)` - : `HTTP ${method} ${url} ${status} ${statusText} (${duration}ms)`; - // Add headers to message if requested - if (includeRequestHeaders && requestHeaders) { - const reqHeaders = Array.from(requestHeaders.entries()) - .map(([key, value]) => `${key}: ${value}`) - .join(', '); - message += `\n Request Headers: {${reqHeaders}}`; - } - if (includeResponseHeaders && responseHeaders) { - const resHeaders = Array.from(responseHeaders.entries()) - .map(([key, value]) => `${key}: ${value}`) - .join(', '); - message += `\n Response Headers: {${resHeaders}}`; - } - if (error || status >= 400) { - // eslint-disable-next-line no-console - console.error(message); - } - else { - // eslint-disable-next-line no-console - console.log(message); - } - }; - const logFn = logger || defaultLogger; - return next => async (input, init) => { - const startTime = performance.now(); - const method = (init === null || init === void 0 ? void 0 : init.method) || 'GET'; - const url = typeof input === 'string' ? input : input.toString(); - const requestHeaders = includeRequestHeaders ? new Headers(init === null || init === void 0 ? void 0 : init.headers) : undefined; - try { - const response = await next(input, init); - const duration = performance.now() - startTime; - // Only log if status meets the log level threshold - if (response.status >= statusLevel) { - logFn({ - method, - url, - status: response.status, - statusText: response.statusText, - duration, - requestHeaders, - responseHeaders: includeResponseHeaders ? response.headers : undefined - }); - } - return response; - } - catch (error) { - const duration = performance.now() - startTime; - // Always log errors regardless of log level - logFn({ - method, - url, - status: 0, - statusText: 'Network Error', - duration, - requestHeaders, - error: error - }); - throw error; - } - }; -}; -exports.withLogging = withLogging; -/** - * Composes multiple fetch middleware functions into a single middleware pipeline. - * Middleware are applied in the order they appear, creating a chain of handlers. - * - * @example - * ```typescript - * // Create a middleware pipeline that handles both OAuth and logging - * const enhancedFetch = applyMiddlewares( - * withOAuth(oauthProvider, 'https://api.example.com'), - * withLogging({ statusLevel: 400 }) - * )(fetch); - * - * // Use the enhanced fetch - it will handle auth and log errors - * const response = await enhancedFetch('https://api.example.com/data'); - * ``` - * - * @param middleware - Array of fetch middleware to compose into a pipeline - * @returns A single composed middleware function - */ -const applyMiddlewares = (...middleware) => { - return next => { - return middleware.reduce((handler, mw) => mw(handler), next); - }; -}; -exports.applyMiddlewares = applyMiddlewares; -/** - * Helper function to create custom fetch middleware with cleaner syntax. - * Provides the next handler and request details as separate parameters for easier access. - * - * @example - * ```typescript - * // Create custom authentication middleware - * const customAuthMiddleware = createMiddleware(async (next, input, init) => { - * const headers = new Headers(init?.headers); - * headers.set('X-Custom-Auth', 'my-token'); - * - * const response = await next(input, { ...init, headers }); - * - * if (response.status === 401) { - * console.log('Authentication failed'); - * } - * - * return response; - * }); - * - * // Create conditional middleware - * const conditionalMiddleware = createMiddleware(async (next, input, init) => { - * const url = typeof input === 'string' ? input : input.toString(); - * - * // Only add headers for API routes - * if (url.includes('/api/')) { - * const headers = new Headers(init?.headers); - * headers.set('X-API-Version', 'v2'); - * return next(input, { ...init, headers }); - * } - * - * // Pass through for non-API routes - * return next(input, init); - * }); - * - * // Create caching middleware - * const cacheMiddleware = createMiddleware(async (next, input, init) => { - * const cacheKey = typeof input === 'string' ? input : input.toString(); - * - * // Check cache first - * const cached = await getFromCache(cacheKey); - * if (cached) { - * return new Response(cached, { status: 200 }); - * } - * - * // Make request and cache result - * const response = await next(input, init); - * if (response.ok) { - * await saveToCache(cacheKey, await response.clone().text()); - * } - * - * return response; - * }); - * ``` - * - * @param handler - Function that receives the next handler and request parameters - * @returns A fetch middleware function - */ -const createMiddleware = (handler) => { - return next => (input, init) => handler(next, input, init); -}; -exports.createMiddleware = createMiddleware; -//# sourceMappingURL=middleware.js.map \ No newline at end of file diff --git a/dist/cjs/client/middleware.js.map b/dist/cjs/client/middleware.js.map deleted file mode 100644 index e68b40c98f..0000000000 --- a/dist/cjs/client/middleware.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../../src/client/middleware.ts"],"names":[],"mappings":";;;AAAA,uCAAuG;AASvG;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACI,MAAM,SAAS,GAClB,CAAC,QAA6B,EAAE,OAAsB,EAAc,EAAE,CACtE,IAAI,CAAC,EAAE;IACH,OAAO,KAAK,EAAE,KA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A7EW,QAAA,WAAW,eA6EtB;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACI,MAAM,gBAAgB,GAAG,CAAC,GAAG,UAAwB,EAAc,EAAE;IACxE,OAAO,IAAI,CAAC,EAAE;QACV,OAAO,UAAU,CAAC,MAAM,CAAC,CAAC,OAAO,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,OAAO,CAAC,EAAE,IAAI,CAAC,CAAC;IACjE,CAAC,CAAC;AACN,CAAC,CAAC;AAJW,QAAA,gBAAgB,oBAI3B;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyDG;AACI,MAAM,gBAAgB,GAAG,CAAC,OAAwF,EAAc,EAAE;IACrI,OAAO,IAAI,CAAC,EAAE,CAAC,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,KAAqB,EAAE,IAAI,CAAC,CAAC;AAC/E,CAAC,CAAC;AAFW,QAAA,gBAAgB,oBAE3B"} \ No newline at end of file diff --git a/dist/cjs/client/sse.d.ts b/dist/cjs/client/sse.d.ts deleted file mode 100644 index acf99f1ea6..0000000000 --- a/dist/cjs/client/sse.d.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { type ErrorEvent, type EventSourceInit } from 'eventsource'; -import { Transport, FetchLike } from '../shared/transport.js'; -import { JSONRPCMessage } from '../types.js'; -import { OAuthClientProvider } from './auth.js'; -export declare class SseError extends Error { - readonly code: number | undefined; - readonly event: ErrorEvent; - constructor(code: number | undefined, message: string | undefined, event: ErrorEvent); -} -/** - * Configuration options for the `SSEClientTransport`. - */ -export type SSEClientTransportOptions = { - /** - * An OAuth client provider to use for authentication. - * - * When an `authProvider` is specified and the SSE connection is started: - * 1. The connection is attempted with any existing access token from the `authProvider`. - * 2. If the access token has expired, the `authProvider` is used to refresh the token. - * 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`. - * - * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `SSEClientTransport.finishAuth` with the authorization code before retrying the connection. - * - * If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown. - * - * `UnauthorizedError` might also be thrown when sending any message over the SSE transport, indicating that the session has expired, and needs to be re-authed and reconnected. - */ - authProvider?: OAuthClientProvider; - /** - * Customizes the initial SSE request to the server (the request that begins the stream). - * - * NOTE: Setting this property will prevent an `Authorization` header from - * being automatically attached to the SSE request, if an `authProvider` is - * also given. This can be worked around by setting the `Authorization` header - * manually. - */ - eventSourceInit?: EventSourceInit; - /** - * Customizes recurring POST requests to the server. - */ - requestInit?: RequestInit; - /** - * Custom fetch implementation used for all network requests. - */ - fetch?: FetchLike; -}; -/** - * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving - * messages and make separate POST requests for sending messages. - * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period. - */ -export declare class SSEClientTransport implements Transport { - private _eventSource?; - private _endpoint?; - private _abortController?; - private _url; - private _resourceMetadataUrl?; - private _scope?; - private _eventSourceInit?; - private _requestInit?; - private _authProvider?; - private _fetch?; - private _fetchWithInit; - private _protocolVersion?; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage) => void; - constructor(url: URL, opts?: SSEClientTransportOptions); - private _authThenStart; - private _commonHeaders; - private _startOrAuth; - start(): Promise; - /** - * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. - */ - finishAuth(authorizationCode: string): Promise; - close(): Promise; - send(message: JSONRPCMessage): Promise; - setProtocolVersion(version: string): void; -} -//# sourceMappingURL=sse.d.ts.map \ No newline at end of file diff --git a/dist/cjs/client/sse.d.ts.map b/dist/cjs/client/sse.d.ts.map deleted file mode 100644 index 3a0053cfc6..0000000000 --- a/d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AC,CAAY;IAC3B,OAAO,CAAC,cAAc,CAAY;IAClC,OAAO,CAAC,gBAAgB,CAAC,CAAS;IAElC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,yBAAyB;YAWxC,cAAc;YAyBd,cAAc;IAe5B,OAAO,CAAC,YAAY;IAyEd,KAAK;IAQX;;OAEG;IACG,UAAU,CAAC,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiBpD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAMtB,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IA8ClD,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;CAG5C"} \ No newline at end of file diff --git a/dist/cjs/client/sse.js b/dist/cjs/client/sse.js deleted file mode 100644 index 7206b6412a..0000000000 --- a/dist/cjs/client/sse.js +++ /dev/null @@ -1,213 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SSEClientTransport = exports.SseError = void 0; -const eventsource_1 = require("eventsource"); -const transport_js_1 = require("../shared/transport.js"); -const types_js_1 = require("../types.js"); -const auth_js_1 = require("./auth.js"); -class SseError extends Error { - constructor(code, message, event) { - super(`SSE error: ${message}`); - this.code = code; - this.event = event; - } -} -exports.SseError = SseError; -/** - * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving - * messages and make separate POST requests for sending messages. - * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period. - */ -class SSEClientTransport { - constructor(url, opts) { - this._url = url; - this._resourceMetadataUrl = undefined; - this._scope = undefined; - this._eventSourceInit = opts === null || opts === void 0 ? void 0 : opts.eventSourceInit; - this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit; - this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider; - this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch; - this._fetchWithInit = (0, transport_js_1.createFetchWithInit)(opts === null || opts === void 0 ? void 0 : opts.fetch, opts === null || opts === void 0 ? void 0 : opts.requestInit); - } - async _authThenStart() { - var _a; - if (!this._authProvider) { - throw new auth_js_1.UnauthorizedError('No auth provider'); - } - let result; - try { - result = await (0, auth_js_1.auth)(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetchWithInit - }); - } - catch (error) { - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - throw error; - } - if (result !== 'AUTHORIZED') { - throw new auth_js_1.UnauthorizedError(); - } - return await this._startOrAuth(); - } - async _commonHeaders() { - var _a; - const headers = {}; - if (this._authProvider) { - const tokens = await this._authProvider.tokens(); - if (tokens) { - headers['Authorization'] = `Bearer ${tokens.access_token}`; - } - } - if (this._protocolVersion) { - headers['mcp-protocol-version'] = this._protocolVersion; - } - return new Headers({ ...headers, ...(_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers }); - } - _startOrAuth() { - var _a, _b, _c; - const fetchImpl = ((_c = (_b = (_a = this === null || this === void 0 ? void 0 : this._eventSourceInit) === null || _a === void 0 ? void 0 : _a.fetch) !== null && _b !== void 0 ? _b : this._fetch) !== null && _c !== void 0 ? _c : fetch); - return new Promise((resolve, reject) => { - this._eventSource = new eventsource_1.EventSource(this._url.href, { - ...this._eventSourceInit, - fetch: async (url, init) => { - const headers = await this._commonHeaders(); - headers.set('Accept', 'text/event-stream'); - const response = await fetchImpl(url, { - ...init, - headers - }); - if (response.status === 401 && response.headers.has('www-authenticate')) { - const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response); - this._resourceMetadataUrl = resourceMetadataUrl; - this._scope = scope; - } - return response; - } - }); - this._abortController = new AbortController(); - this._eventSource.onerror = event => { - var _a; - if (event.code === 401 && this._authProvider) { - this._authThenStart().then(resolve, reject); - return; - } - const error = new SseError(event.code, event.message, event); - reject(error); - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }; - this._eventSource.onopen = () => { - // The connection is open, but we need to wait for the endpoint to be received. - }; - this._eventSource.addEventListener('endpoint', (event) => { - var _a; - const messageEvent = event; - try { - this._endpoint = new URL(messageEvent.data, this._url); - if (this._endpoint.origin !== this._url.origin) { - throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`); - } - } - catch (error) { - reject(error); - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - void this.close(); - return; - } - resolve(); - }); - this._eventSource.onmessage = (event) => { - var _a, _b; - const messageEvent = event; - let message; - try { - message = types_js_1.JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data)); - } - catch (error) { - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - return; - } - (_b = this.onmessage) === null || _b === void 0 ? void 0 : _b.call(this, message); - }; - }); - } - async start() { - if (this._eventSource) { - throw new Error('SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.'); - } - return await this._startOrAuth(); - } - /** - * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. - */ - async finishAuth(authorizationCode) { - if (!this._authProvider) { - throw new auth_js_1.UnauthorizedError('No auth provider'); - } - const result = await (0, auth_js_1.auth)(this._authProvider, { - serverUrl: this._url, - authorizationCode, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetchWithInit - }); - if (result !== 'AUTHORIZED') { - throw new auth_js_1.UnauthorizedError('Failed to authorize'); - } - } - async close() { - var _a, _b, _c; - (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.abort(); - (_b = this._eventSource) === null || _b === void 0 ? void 0 : _b.close(); - (_c = this.onclose) === null || _c === void 0 ? void 0 : _c.call(this); - } - async send(message) { - var _a, _b, _c; - if (!this._endpoint) { - throw new Error('Not connected'); - } - try { - const headers = await this._commonHeaders(); - headers.set('content-type', 'application/json'); - const init = { - ...this._requestInit, - method: 'POST', - headers, - body: JSON.stringify(message), - signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal - }; - const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._endpoint, init); - if (!response.ok) { - if (response.status === 401 && this._authProvider) { - const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response); - this._resourceMetadataUrl = resourceMetadataUrl; - this._scope = scope; - const result = await (0, auth_js_1.auth)(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetchWithInit - }); - if (result !== 'AUTHORIZED') { - throw new auth_js_1.UnauthorizedError(); - } - // Purposely _not_ awaited, so we don't call onerror twice - return this.send(message); - } - const text = await response.text().catch(() => null); - throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); - } - } - catch (error) { - (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error); - throw error; - } - } - setProtocolVersion(version) { - this._protocolVersion = version; - } -} -exports.SSEClientTransport = SSEClientTransport; -//# sourceMappingURL=sse.js.map \ No newline at end of file diff --git a/dist/cjs/client/sse.js.map b/dist/cjs/client/sse.js.map deleted file mode 100644 index a3c4180507..0000000000 --- a/dist/cjs/client/sse.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"sse.js","sourceRoot":"","sources":["../../../src/client/sse.ts"],"names":[],"mappings":";;;AAAA,6CAAiF;AACjF,yDAAmF;AACnF,0CAAmE;AACnE,uCAAmH;AAEnH,MAAa,QAAS,SAAQ,KAAK;IAC/B,YACoB,IAAwB,EACxC,OAA2B,EACX,KAAiB;QAEjC,KAAK,CAAC,cAAc,OAAO,EAAE,CAA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QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,MAAA,IAAI,CAAC,OAAO,qDAAG,KAAc,CAAC,CAAC;YAC/B,MAAM,KAAK,CAAC;QAChB,CAAC;IACL,CAAC;IAED,kBAAkB,CAAC,OAAe;QAC9B,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;IACpC,CAAC;CACJ;AAjOD,gDAiOC"} \ No newline at end of file diff --git a/dist/cjs/client/stdio.d.ts b/dist/cjs/client/stdio.d.ts deleted file mode 100644 index 58d0b6ccba..0000000000 --- a/dist/cjs/client/stdio.d.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { IOType } from 'node:child_process'; -import { Stream } from 'node:stream'; -import { Transport } from '../shared/transport.js'; -import { JSONRPCMessage } from '../types.js'; -export type StdioServerParameters = { - /** - * The executable to run to start the server. - */ - command: string; - /** - * Command line arguments to pass to the executable. - */ - args?: string[]; - /** - * The environment to use when spawning the process. - * - * If not specified, the result of getDefaultEnvironment() will be used. - */ - env?: Record; - /** - * How to handle stderr of the child process. This matches the semantics of Node's `child_process.spawn`. - * - * The default is "inherit", meaning messages to stderr will be printed to the parent process's stderr. - */ - stderr?: IOType | Stream | number; - /** - * The working directory to use when spawning the process. - * - * If not specified, the current working directory will be inherited. - */ - cwd?: string; -}; -/** - * Environment variables to inherit by default, if an environment is not explicitly given. - */ -export declare const DEFAULT_INHERITED_ENV_VARS: string[]; -/** - * Returns a default environment object including only environment variables deemed safe to inherit. - */ -export declare function getDefaultEnvironment(): Record; -/** - * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout. - * - * This transport is only available in Node.js environments. - */ -export declare class StdioClientTransport implements Transport { - private _process?; - private _abortController; - private _readBuffer; - private _serverParams; - private _stderrStream; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage) => void; - constructor(server: StdioServerParameters); - /** - * Starts the server process and prepares to communicate with it. - */ - start(): Promise; - /** - * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". - * - * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to - * attach listeners before the start method is invoked. This prevents loss of any early - * error output emitted by the child process. - */ - get stderr(): Stream | null; - /** - * The child process pid spawned by this transport. - * - * This is only available after the transport has been started. - */ - get pid(): number | null; - private processReadBuffer; - close(): Promise; - send(message: JSONRPCMessage): Promise; -} -//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/dist/cjs/client/stdio.d.ts.map b/dist/cjs/client/stdio.d.ts.map deleted file mode 100644 index 44f6de451b..0000000000 --- a/dist/cjs/client/stdio.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/client/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAG1D,OAAO,EAAE,MAAM,EAAe,MAAM,aAAa,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE7C,MAAM,MAAM,qBAAqB,GAAG;IAChC;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAEhB;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAEhB;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAE7B;;;;OAIG;IACH,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;IAElC;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,0BAA0B,UAiBuB,CAAC;AAE/D;;GAEG;AACH,wBAAgB,qBAAqB,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAkB9D;AAED;;;;GAIG;AACH,qBAAa,oBAAqB,YAAW,SAAS;IAClD,OAAO,CAAC,QAAQ,CAAC,CAAe;IAChC,OAAO,CAAC,gBAAgB,CAA0C;IAClE,OAAO,CAAC,WAAW,CAAgC;IACnD,OAAO,CAAC,aAAa,CAAwB;IAC7C,OAAO,CAAC,aAAa,CAA4B;IAEjD,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,MAAM,EAAE,qBAAqB;IAOzC;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IA4D5B;;;;;;OAMG;IACH,IAAI,MAAM,IAAI,MAAM,GAAG,IAAI,CAM1B;IAED;;;;OAIG;IACH,IAAI,GAAG,IAAI,MAAM,GAAG,IAAI,CAEvB;IAED,OAAO,CAAC,iBAAiB;IAenB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAM5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAc/C"} \ No newline at end of file diff --git a/dist/cjs/client/stdio.js b/dist/cjs/client/stdio.js deleted file mode 100644 index 95d6f94f30..0000000000 --- a/dist/cjs/client/stdio.js +++ /dev/null @@ -1,184 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.StdioClientTransport = exports.DEFAULT_INHERITED_ENV_VARS = void 0; -exports.getDefaultEnvironment = getDefaultEnvironment; -const cross_spawn_1 = __importDefault(require("cross-spawn")); -const node_process_1 = __importDefault(require("node:process")); -const node_stream_1 = require("node:stream"); -const stdio_js_1 = require("../shared/stdio.js"); -/** - * Environment variables to inherit by default, if an environment is not explicitly given. - */ -exports.DEFAULT_INHERITED_ENV_VARS = node_process_1.default.platform === 'win32' - ? [ - 'APPDATA', - 'HOMEDRIVE', - 'HOMEPATH', - 'LOCALAPPDATA', - 'PATH', - 'PROCESSOR_ARCHITECTURE', - 'SYSTEMDRIVE', - 'SYSTEMROOT', - 'TEMP', - 'USERNAME', - 'USERPROFILE', - 'PROGRAMFILES' - ] - : /* list inspired by the default env inheritance of sudo */ - ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER']; -/** - * Returns a default environment object including only environment variables deemed safe to inherit. - */ -function getDefaultEnvironment() { - const env = {}; - for (const key of exports.DEFAULT_INHERITED_ENV_VARS) { - const value = node_process_1.default.env[key]; - if (value === undefined) { - continue; - } - if (value.startsWith('()')) { - // Skip functions, which are a security risk. - continue; - } - env[key] = value; - } - return env; -} -/** - * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout. - * - * This transport is only available in Node.js environments. - */ -class StdioClientTransport { - constructor(server) { - this._abortController = new AbortController(); - this._readBuffer = new stdio_js_1.ReadBuffer(); - this._stderrStream = null; - this._serverParams = server; - if (server.stderr === 'pipe' || server.stderr === 'overlapped') { - this._stderrStream = new node_stream_1.PassThrough(); - } - } - /** - * Starts the server process and prepares to communicate with it. - */ - async start() { - if (this._process) { - throw new Error('StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.'); - } - return new Promise((resolve, reject) => { - var _a, _b, _c, _d, _e; - this._process = (0, cross_spawn_1.default)(this._serverParams.command, (_a = this._serverParams.args) !== null && _a !== void 0 ? _a : [], { - // merge default env with server env because mcp server needs some env vars - env: { - ...getDefaultEnvironment(), - ...this._serverParams.env - }, - stdio: ['pipe', 'pipe', (_b = this._serverParams.stderr) !== null && _b !== void 0 ? _b : 'inherit'], - shell: false, - signal: this._abortController.signal, - windowsHide: node_process_1.default.platform === 'win32' && isElectron(), - cwd: this._serverParams.cwd - }); - this._process.on('error', error => { - var _a, _b; - if (error.name === 'AbortError') { - // Expected when close() is called. - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - return; - } - reject(error); - (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); - }); - this._process.on('spawn', () => { - resolve(); - }); - this._process.on('close', _code => { - var _a; - this._process = undefined; - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - }); - (_c = this._process.stdin) === null || _c === void 0 ? void 0 : _c.on('error', error => { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }); - (_d = this._process.stdout) === null || _d === void 0 ? void 0 : _d.on('data', chunk => { - this._readBuffer.append(chunk); - this.processReadBuffer(); - }); - (_e = this._process.stdout) === null || _e === void 0 ? void 0 : _e.on('error', error => { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }); - if (this._stderrStream && this._process.stderr) { - this._process.stderr.pipe(this._stderrStream); - } - }); - } - /** - * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". - * - * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to - * attach listeners before the start method is invoked. This prevents loss of any early - * error output emitted by the child process. - */ - get stderr() { - var _a, _b; - if (this._stderrStream) { - return this._stderrStream; - } - return (_b = (_a = this._process) === null || _a === void 0 ? void 0 : _a.stderr) !== null && _b !== void 0 ? _b : null; - } - /** - * The child process pid spawned by this transport. - * - * This is only available after the transport has been started. - */ - get pid() { - var _a, _b; - return (_b = (_a = this._process) === null || _a === void 0 ? void 0 : _a.pid) !== null && _b !== void 0 ? _b : null; - } - processReadBuffer() { - var _a, _b; - while (true) { - try { - const message = this._readBuffer.readMessage(); - if (message === null) { - break; - } - (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message); - } - catch (error) { - (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); - } - } - } - async close() { - this._abortController.abort(); - this._process = undefined; - this._readBuffer.clear(); - } - send(message) { - return new Promise(resolve => { - var _a; - if (!((_a = this._process) === null || _a === void 0 ? void 0 : _a.stdin)) { - throw new Error('Not connected'); - } - const json = (0, stdio_js_1.serializeMessage)(message); - if (this._process.stdin.write(json)) { - resolve(); - } - else { - this._process.stdin.once('drain', resolve); - } - }); - } -} -exports.StdioClientTransport = StdioClientTransport; -function isElectron() { - return 'type' in node_process_1.default; -} -//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/dist/cjs/client/stdio.js.map b/dist/cjs/client/stdio.js.map deleted file mode 100644 index 3b84737a12..0000000000 --- a/dist/cjs/client/stdio.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/client/stdio.ts"],"names":[],"mappings":";;;;;;AAkEA,sDAkBC;AAnFD,8DAAgC;AAChC,gEAAmC;AACnC,6CAAkD;AAClD,iDAAkE;AAqClE;;GAEG;AACU,QAAA,0BAA0B,GACnC,sBAAO,CAAC,QAAQ,KAAK,OAAO;IACxB,CAAC,CAAC;QACI,SAAS;QACT,WAAW;QACX,UAAU;QACV,cAAc;QACd,MAAM;QACN,wBAAwB;QACxB,aAAa;QACb,YAAY;QACZ,MAAM;QACN,UAAU;QACV,aAAa;QACb,cAAc;KACjB;IACH,CAAC,CAAC,0DAA0D;QAC1D,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAE/D;;GAEG;AACH,SAAgB,qBAAqB;IACjC,MAAM,GAAG,GAA2B,EAAE,CAAC;IAEvC,KAAK,MAAM,GAAG,IAAI,kCAA0B,EAAE,CAAC;QAC3C,MAAM,KAAK,GAAG,sBAAO,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC/B,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACtB,SAAS;QACb,CAAC;QAED,IAAI,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;YACzB,6CAA6C;YAC7C,SAAS;QACb,CAAC;QAED,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,OAAO,GAAG,CAAC;AACf,CAAC;AAED;;;;G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C,CAAC;YAED,MAAM,IAAI,GAAG,IAAA,2BAAgB,EAAC,OAAO,CAAC,CAAC;YACvC,IAAI,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBAClC,OAAO,EAAE,CAAC;YACd,CAAC;iBAAM,CAAC;gBACJ,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC/C,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AA5ID,oDA4IC;AAED,SAAS,UAAU;IACf,OAAO,MAAM,IAAI,sBAAO,CAAC;AAC7B,CAAC"} \ No newline at end of file diff --git a/dist/cjs/client/streamableHttp.d.ts b/dist/cjs/client/streamableHttp.d.ts deleted file mode 100644 index 6c6a32f473..0000000000 --- a/dist/cjs/client/streamableHttp.d.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { Transport, FetchLike } from '../shared/transport.js'; -import { JSONRPCMessage } from '../types.js'; -import { OAuthClientProvider } from './auth.js'; -export declare class StreamableHTTPError extends Error { - readonly code: number | undefined; - constructor(code: number | undefined, message: string | undefined); -} -/** - * Options for starting or authenticating an SSE connection - */ -export interface StartSSEOptions { - /** - * The resumption token used to continue long-running requests that were interrupted. - * - * This allows clients to reconnect and continue from where they left off. - */ - resumptionToken?: string; - /** - * A callback that is invoked when the resumption token changes. - * - * This allows clients to persist the latest token for potential reconnection. - */ - onresumptiontoken?: (token: string) => void; - /** - * Override Message ID to associate with the replay message - * so that response can be associate with the new resumed request. - */ - replayMessageId?: string | number; -} -/** - * Configuration options for reconnection behavior of the StreamableHTTPClientTransport. - */ -export interface StreamableHTTPReconnectionOptions { - /** - * Maximum backoff time between reconnection attempts in milliseconds. - * Default is 30000 (30 seconds). - */ - maxReconnectionDelay: number; - /** - * Initial backoff time between reconnection attempts in milliseconds. - * Default is 1000 (1 second). - */ - initialReconnectionDelay: number; - /** - * The factor by which the reconnection delay increases after each attempt. - * Default is 1.5. - */ - reconnectionDelayGrowFactor: number; - /** - * Maximum number of reconnection attempts before giving up. - * Default is 2. - */ - maxRetries: number; -} -/** - * Configuration options for the `StreamableHTTPClientTransport`. - */ -export type StreamableHTTPClientTransportOptions = { - /** - * An OAuth client provider to use for authentication. - * - * When an `authProvider` is specified and the connection is started: - * 1. The connection is attempted with any existing access token from the `authProvider`. - * 2. If the access token has expired, the `authProvider` is used to refresh the token. - * 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`. - * - * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `StreamableHTTPClientTransport.finishAuth` with the authorization code before retrying the connection. - * - * If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown. - * - * `UnauthorizedError` might also be thrown when sending any message over the transport, indicating that the session has expired, and needs to be re-authed and reconnected. - */ - authProvider?: OAuthClientProvider; - /** - * Customizes HTTP requests to the server. - */ - requestInit?: RequestInit; - /** - * Custom fetch implementation used for all network requests. - */ - fetch?: FetchLike; - /** - * Options to configure the reconnection behavior. - */ - reconnectionOptions?: StreamableHTTPReconnectionOptions; - /** - * Session ID for the connection. This is used to identify the session on the server. - * When not provided and connecting to a server that supports session IDs, the server will generate a new session ID. - */ - sessionId?: string; -}; -/** - * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. - * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events - * for receiving messages. - */ -export declare class StreamableHTTPClientTransport implements Transport { - private _abortController?; - private _url; - private _resourceMetadataUrl?; - private _scope?; - private _requestInit?; - private _authProvider?; - private _fetch?; - private _fetchWithInit; - private _sessionId?; - private _reconnectionOptions; - private _protocolVersion?; - private _hasCompletedAuthFlow; - private _lastUpscopingHeader?; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage) => void; - constructor(url: URL, opts?: StreamableHTTPClientTransportOptions); - private _authThenStart; - private _commonHeaders; - private _startOrAuthSse; - /** - * Calculates the next reconnection delay using backoff algorithm - * - * @param attempt Current reconnection attempt count for the specific stream - * @returns Time to wait in milliseconds before next reconnection attempt - */ - private _getNextReconnectionDelay; - /** - * Schedule a reconnection attempt with exponential backoff - * - * @param lastEventId The ID of the last received event for resumability - * @param attemptCount Current reconnection attempt count for this specific stream - */ - private _scheduleReconnection; - private _handleSseStream; - start(): Promise; - /** - * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. - */ - finishAuth(authorizationCode: string): Promise; - close(): Promise; - send(message: JSONRPCMessage | JSONRPCMessage[], options?: { - resumptionToken?: string; - onresumptiontoken?: (token: string) => void; - }): Promise; - get sessionId(): string | undefined; - /** - * Terminates the current session by sending a DELETE request to the server. - * - * Clients that no longer need a particular session - * (e.g., because the user is leaving the client application) SHOULD send an - * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly - * terminate the session. - * - * The server MAY respond with HTTP 405 Method Not Allowed, indicating that - * the server does not allow clients to terminate sessions. - */ - terminateSession(): Promise; - setProtocolVersion(version: string): void; - get protocolVersion(): string | undefined; -} -//# sourceMappingURL=streamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/client/streamableHttp.d.ts.map b/dist/cjs/client/streamableHttp.d.ts.map deleted file mode 100644 index cbca11957b..0000000000 --- a/dist/cjs/client/streamableHttp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"streamableHttp.d.ts","sourceRoot":"","sources":["../../../src/client/streamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAyC,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAkE,cAAc,EAAwB,MAAM,aAAa,CAAC;AACnI,OAAO,EAAkD,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AAWnH,qBAAa,mBAAoB,SAAQ,KAAK;aAEtB,IAAI,EAAE,MAAM,GA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AC,UAAU,CAAC,CAAS;IAC5B,OAAO,CAAC,oBAAoB,CAAoC;IAChE,OAAO,CAAC,gBAAgB,CAAC,CAAS;IAClC,OAAO,CAAC,qBAAqB,CAAS;IACtC,OAAO,CAAC,oBAAoB,CAAC,CAAS;IAEtC,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,EAAE,oCAAoC;YAYnD,cAAc;YAyBd,cAAc;YAwBd,eAAe;IAyC7B;;;;;OAKG;IACH,OAAO,CAAC,yBAAyB;IAUjC;;;;;OAKG;IACH,OAAO,CAAC,qBAAqB;IAwB7B,OAAO,CAAC,gBAAgB;IAkElB,KAAK;IAUX;;OAEG;IACG,UAAU,CAAC,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiBpD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAOtB,IAAI,CACN,OAAO,EAAE,cAAc,GAAG,cAAc,EAAE,EAC1C,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,MAAM,CAAC;QAAC,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAA;KAAE,GACpF,OAAO,CAAC,IAAI,CAAC;IAoJhB,IAAI,SAAS,IAAI,MAAM,GAAG,SAAS,CAElC;IAED;;;;;;;;;;OAUG;IACG,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;IA8BvC,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAGzC,IAAI,eAAe,IAAI,MAAM,GAAG,SAAS,CAExC;CACJ"} \ No newline at end of file diff --git a/dist/cjs/client/streamableHttp.js b/dist/cjs/client/streamableHttp.js deleted file mode 100644 index 63c17b8c86..0000000000 --- a/dist/cjs/client/streamableHttp.js +++ /dev/null @@ -1,426 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.StreamableHTTPClientTransport = exports.StreamableHTTPError = void 0; -const transport_js_1 = require("../shared/transport.js"); -const types_js_1 = require("../types.js"); -const auth_js_1 = require("./auth.js"); -const stream_1 = require("eventsource-parser/stream"); -// Default reconnection options for StreamableHTTP connections -const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = { - initialReconnectionDelay: 1000, - maxReconnectionDelay: 30000, - reconnectionDelayGrowFactor: 1.5, - maxRetries: 2 -}; -class StreamableHTTPError extends Error { - constructor(code, message) { - super(`Streamable HTTP error: ${message}`); - this.code = code; - } -} -exports.StreamableHTTPError = StreamableHTTPError; -/** - * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. - * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events - * for receiving messages. - */ -class StreamableHTTPClientTransport { - constructor(url, opts) { - var _a; - this._hasCompletedAuthFlow = false; // Circuit breaker: detect auth success followed by immediate 401 - this._url = url; - this._resourceMetadataUrl = undefined; - this._scope = undefined; - this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit; - this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider; - this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch; - this._fetchWithInit = (0, transport_js_1.createFetchWithInit)(opts === null || opts === void 0 ? void 0 : opts.fetch, opts === null || opts === void 0 ? void 0 : opts.requestInit); - this._sessionId = opts === null || opts === void 0 ? void 0 : opts.sessionId; - this._reconnectionOptions = (_a = opts === null || opts === void 0 ? void 0 : opts.reconnectionOptions) !== null && _a !== void 0 ? _a : DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS; - } - async _authThenStart() { - var _a; - if (!this._authProvider) { - throw new auth_js_1.UnauthorizedError('No auth provider'); - } - let result; - try { - result = await (0, auth_js_1.auth)(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetchWithInit - }); - } - catch (error) { - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - throw error; - } - if (result !== 'AUTHORIZED') { - throw new auth_js_1.UnauthorizedError(); - } - return await this._startOrAuthSse({ resumptionToken: undefined }); - } - async _commonHeaders() { - var _a; - const headers = {}; - if (this._authProvider) { - const tokens = await this._authProvider.tokens(); - if (tokens) { - headers['Authorization'] = `Bearer ${tokens.access_token}`; - } - } - if (this._sessionId) { - headers['mcp-session-id'] = this._sessionId; - } - if (this._protocolVersion) { - headers['mcp-protocol-version'] = this._protocolVersion; - } - const extraHeaders = (0, transport_js_1.normalizeHeaders)((_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers); - return new Headers({ - ...headers, - ...extraHeaders - }); - } - async _startOrAuthSse(options) { - var _a, _b, _c; - const { resumptionToken } = options; - try { - // Try to open an initial SSE stream with GET to listen for server messages - // This is optional according to the spec - server may not support it - const headers = await this._commonHeaders(); - headers.set('Accept', 'text/event-stream'); - // Include Last-Event-ID header for resumable streams if provided - if (resumptionToken) { - headers.set('last-event-id', resumptionToken); - } - const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(this._url, { - method: 'GET', - headers, - signal: (_b = this._abortController) === null || _b === void 0 ? void 0 : _b.signal - }); - if (!response.ok) { - if (response.status === 401 && this._authProvider) { - // Need to authenticate - return await this._authThenStart(); - } - // 405 indicates that the server does not offer an SSE stream at GET endpoint - // This is an expected case that should not trigger an error - if (response.status === 405) { - return; - } - throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`); - } - this._handleSseStream(response.body, options, true); - } - catch (error) { - (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error); - throw error; - } - } - /** - * Calculates the next reconnection delay using backoff algorithm - * - * @param attempt Current reconnection attempt count for the specific stream - * @returns Time to wait in milliseconds before next reconnection attempt - */ - _getNextReconnectionDelay(attempt) { - // Access default values directly, ensuring they're never undefined - const initialDelay = this._reconnectionOptions.initialReconnectionDelay; - const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor; - const maxDelay = this._reconnectionOptions.maxReconnectionDelay; - // Cap at maximum delay - return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay); - } - /** - * Schedule a reconnection attempt with exponential backoff - * - * @param lastEventId The ID of the last received event for resumability - * @param attemptCount Current reconnection attempt count for this specific stream - */ - _scheduleReconnection(options, attemptCount = 0) { - var _a; - // Use provided options or default options - const maxRetries = this._reconnectionOptions.maxRetries; - // Check if we've exceeded maximum retry attempts - if (maxRetries > 0 && attemptCount >= maxRetries) { - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`)); - return; - } - // Calculate next delay based on current attempt count - const delay = this._getNextReconnectionDelay(attemptCount); - // Schedule the reconnection - setTimeout(() => { - // Use the last event ID to resume where we left off - this._startOrAuthSse(options).catch(error => { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`)); - // Schedule another attempt if this one failed, incrementing the attempt counter - this._scheduleReconnection(options, attemptCount + 1); - }); - }, delay); - } - _handleSseStream(stream, options, isReconnectable) { - if (!stream) { - return; - } - const { onresumptiontoken, replayMessageId } = options; - let lastEventId; - const processStream = async () => { - var _a, _b, _c, _d; - // this is the closest we can get to trying to catch network errors - // if something happens reader will throw - try { - // Create a pipeline: binary stream -> text decoder -> SSE parser - const reader = stream - .pipeThrough(new TextDecoderStream()) - .pipeThrough(new stream_1.EventSourceParserStream()) - .getReader(); - while (true) { - const { value: event, done } = await reader.read(); - if (done) { - break; - } - // Update last event ID if provided - if (event.id) { - lastEventId = event.id; - onresumptiontoken === null || onresumptiontoken === void 0 ? void 0 : onresumptiontoken(event.id); - } - if (!event.event || event.event === 'message') { - try { - const message = types_js_1.JSONRPCMessageSchema.parse(JSON.parse(event.data)); - if (replayMessageId !== undefined && (0, types_js_1.isJSONRPCResponse)(message)) { - message.id = replayMessageId; - } - (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message); - } - catch (error) { - (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); - } - } - } - } - catch (error) { - // Handle stream errors - likely a network disconnect - (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, new Error(`SSE stream disconnected: ${error}`)); - // Attempt to reconnect if the stream disconnects unexpectedly and we aren't closing - if (isReconnectable && this._abortController && !this._abortController.signal.aborted) { - // Use the exponential backoff reconnection strategy - try { - this._scheduleReconnection({ - resumptionToken: lastEventId, - onresumptiontoken, - replayMessageId - }, 0); - } - catch (error) { - (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`)); - } - } - } - }; - processStream(); - } - async start() { - if (this._abortController) { - throw new Error('StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.'); - } - this._abortController = new AbortController(); - } - /** - * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. - */ - async finishAuth(authorizationCode) { - if (!this._authProvider) { - throw new auth_js_1.UnauthorizedError('No auth provider'); - } - const result = await (0, auth_js_1.auth)(this._authProvider, { - serverUrl: this._url, - authorizationCode, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetchWithInit - }); - if (result !== 'AUTHORIZED') { - throw new auth_js_1.UnauthorizedError('Failed to authorize'); - } - } - async close() { - var _a, _b; - // Abort any pending requests - (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.abort(); - (_b = this.onclose) === null || _b === void 0 ? void 0 : _b.call(this); - } - async send(message, options) { - var _a, _b, _c, _d; - try { - const { resumptionToken, onresumptiontoken } = options || {}; - if (resumptionToken) { - // If we have at last event ID, we need to reconnect the SSE stream - this._startOrAuthSse({ resumptionToken, replayMessageId: (0, types_js_1.isJSONRPCRequest)(message) ? message.id : undefined }).catch(err => { var _a; return (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, err); }); - return; - } - const headers = await this._commonHeaders(); - headers.set('content-type', 'application/json'); - headers.set('accept', 'application/json, text/event-stream'); - const init = { - ...this._requestInit, - method: 'POST', - headers, - body: JSON.stringify(message), - signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal - }; - const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._url, init); - // Handle session ID received during initialization - const sessionId = response.headers.get('mcp-session-id'); - if (sessionId) { - this._sessionId = sessionId; - } - if (!response.ok) { - if (response.status === 401 && this._authProvider) { - // Prevent infinite recursion when server returns 401 after successful auth - if (this._hasCompletedAuthFlow) { - throw new StreamableHTTPError(401, 'Server returned 401 after successful authentication'); - } - const { resourceMetadataUrl, scope } = (0, auth_js_1.extractWWWAuthenticateParams)(response); - this._resourceMetadataUrl = resourceMetadataUrl; - this._scope = scope; - const result = await (0, auth_js_1.auth)(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetchWithInit - }); - if (result !== 'AUTHORIZED') { - throw new auth_js_1.UnauthorizedError(); - } - // Mark that we completed auth flow - this._hasCompletedAuthFlow = true; - // Purposely _not_ awaited, so we don't call onerror twice - return this.send(message); - } - if (response.status === 403 && this._authProvider) { - const { resourceMetadataUrl, scope, error } = (0, auth_js_1.extractWWWAuthenticateParams)(response); - if (error === 'insufficient_scope') { - const wwwAuthHeader = response.headers.get('WWW-Authenticate'); - // Check if we've already tried upscoping with this header to prevent infinite loops. - if (this._lastUpscopingHeader === wwwAuthHeader) { - throw new StreamableHTTPError(403, 'Server returned 403 after trying upscoping'); - } - if (scope) { - this._scope = scope; - } - if (resourceMetadataUrl) { - this._resourceMetadataUrl = resourceMetadataUrl; - } - // Mark that upscoping was tried. - this._lastUpscopingHeader = wwwAuthHeader !== null && wwwAuthHeader !== void 0 ? wwwAuthHeader : undefined; - const result = await (0, auth_js_1.auth)(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetch - }); - if (result !== 'AUTHORIZED') { - throw new auth_js_1.UnauthorizedError(); - } - return this.send(message); - } - } - const text = await response.text().catch(() => null); - throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); - } - // Reset auth loop flag on successful response - this._hasCompletedAuthFlow = false; - this._lastUpscopingHeader = undefined; - // If the response is 202 Accepted, there's no body to process - if (response.status === 202) { - // if the accepted notification is initialized, we start the SSE stream - // if it's supported by the server - if ((0, types_js_1.isInitializedNotification)(message)) { - // Start without a lastEventId since this is a fresh connection - this._startOrAuthSse({ resumptionToken: undefined }).catch(err => { var _a; return (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, err); }); - } - return; - } - // Get original message(s) for detecting request IDs - const messages = Array.isArray(message) ? message : [message]; - const hasRequests = messages.filter(msg => 'method' in msg && 'id' in msg && msg.id !== undefined).length > 0; - // Check the response type - const contentType = response.headers.get('content-type'); - if (hasRequests) { - if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('text/event-stream')) { - // Handle SSE stream responses for requests - // We use the same handler as standalone streams, which now supports - // reconnection with the last event ID - this._handleSseStream(response.body, { onresumptiontoken }, false); - } - else if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) { - // For non-streaming servers, we might get direct JSON responses - const data = await response.json(); - const responseMessages = Array.isArray(data) - ? data.map(msg => types_js_1.JSONRPCMessageSchema.parse(msg)) - : [types_js_1.JSONRPCMessageSchema.parse(data)]; - for (const msg of responseMessages) { - (_c = this.onmessage) === null || _c === void 0 ? void 0 : _c.call(this, msg); - } - } - else { - throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`); - } - } - } - catch (error) { - (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error); - throw error; - } - } - get sessionId() { - return this._sessionId; - } - /** - * Terminates the current session by sending a DELETE request to the server. - * - * Clients that no longer need a particular session - * (e.g., because the user is leaving the client application) SHOULD send an - * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly - * terminate the session. - * - * The server MAY respond with HTTP 405 Method Not Allowed, indicating that - * the server does not allow clients to terminate sessions. - */ - async terminateSession() { - var _a, _b, _c; - if (!this._sessionId) { - return; // No session to terminate - } - try { - const headers = await this._commonHeaders(); - const init = { - ...this._requestInit, - method: 'DELETE', - headers, - signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal - }; - const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._url, init); - // We specifically handle 405 as a valid response according to the spec, - // meaning the server does not support explicit session termination - if (!response.ok && response.status !== 405) { - throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`); - } - this._sessionId = undefined; - } - catch (error) { - (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error); - throw error; - } - } - setProtocolVersion(version) { - this._protocolVersion = version; - } - get protocolVersion() { - return this._protocolVersion; - } -} -exports.StreamableHTTPClientTransport = StreamableHTTPClientTransport; -//# sourceMappingURL=streamableHttp.js.map \ No newline at end of file diff --git a/dist/cjs/client/streamableHttp.js.map b/dist/cjs/client/streamableHttp.js.map deleted file mode 100644 index d48b32683f..0000000000 --- a/dist/cjs/client/streamableHttp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"streamableHttp.js","sourceRoot":"","sources":["../../../src/client/streamableHttp.ts"],"names":[],"mappings":";;;AAAA,yDAAqG;AACrG,0CAAmI;AACnI,uCAAmH;AACnH,sDAAoE;AAEpE,8DAA8D;AAC9D,MAAM,4CAA4C,GAAsC;IACpF,wBAAwB,EAAE,IAAI;IAC9B,oBAAoB,EAAE,KAAK;IAC3B,2BAA2B,EAAE,GAAG;IAChC,UAAU,EAAE,CAAC;CAChB,CAAC;AAEF,MAAa,mBAAoB,SAAQ,KAAK;IAC1C,YACoB,IAAwB,EACxC,O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D,sEAwdC"} \ No newline at end of file diff --git a/dist/cjs/client/websocket.d.ts b/dist/cjs/client/websocket.d.ts deleted file mode 100644 index 78f95de3b9..0000000000 --- a/dist/cjs/client/websocket.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Transport } from '../shared/transport.js'; -import { JSONRPCMessage } from '../types.js'; -/** - * Client transport for WebSocket: this will connect to a server over the WebSocket protocol. - */ -export declare class WebSocketClientTransport implements Transport { - private _socket?; - private _url; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage) => void; - constructor(url: URL); - start(): Promise; - close(): Promise; - send(message: JSONRPCMessage): Promise; -} -//# sourceMappingURL=websocket.d.ts.map \ No newline at end of file diff --git a/dist/cjs/client/websocket.d.ts.map b/dist/cjs/client/websocket.d.ts.map deleted file mode 100644 index 2882d98226..0000000000 --- a/dist/cjs/client/websocket.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../../../src/client/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AAInE;;GAEG;AACH,qBAAa,wBAAyB,YAAW,SAAS;IACtD,OAAO,CAAC,OAAO,CAAC,CAAY;IAC5B,OAAO,CAAC,IAAI,CAAM;IAElB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,GAAG,EAAE,GAAG;IAIpB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAsChB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAW/C"} \ No newline at end of file diff --git a/dist/cjs/client/websocket.js b/dist/cjs/client/websocket.js deleted file mode 100644 index e2c94d0651..0000000000 --- a/dist/cjs/client/websocket.js +++ /dev/null @@ -1,63 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.WebSocketClientTransport = void 0; -const types_js_1 = require("../types.js"); -const SUBPROTOCOL = 'mcp'; -/** - * Client transport for WebSocket: this will connect to a server over the WebSocket protocol. - */ -class WebSocketClientTransport { - constructor(url) { - this._url = url; - } - start() { - if (this._socket) { - throw new Error('WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.'); - } - return new Promise((resolve, reject) => { - this._socket = new WebSocket(this._url, SUBPROTOCOL); - this._socket.onerror = event => { - var _a; - const error = 'error' in event ? event.error : new Error(`WebSocket error: ${JSON.stringify(event)}`); - reject(error); - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }; - this._socket.onopen = () => { - resolve(); - }; - this._socket.onclose = () => { - var _a; - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - }; - this._socket.onmessage = (event) => { - var _a, _b; - let message; - try { - message = types_js_1.JSONRPCMessageSchema.parse(JSON.parse(event.data)); - } - catch (error) { - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - return; - } - (_b = this.onmessage) === null || _b === void 0 ? void 0 : _b.call(this, message); - }; - }); - } - async close() { - var _a; - (_a = this._socket) === null || _a === void 0 ? void 0 : _a.close(); - } - send(message) { - return new Promise((resolve, reject) => { - var _a; - if (!this._socket) { - reject(new Error('Not connected')); - return; - } - (_a = this._socket) === null || _a === void 0 ? void 0 : _a.send(JSON.stringify(message)); - resolve(); - }); - } -} -exports.WebSocketClientTransport = WebSocketClientTransport; -//# sourceMappingURL=websocket.js.map \ No newline at end of file diff --git a/dist/cjs/client/websocket.js.map b/dist/cjs/client/websocket.js.map deleted file mode 100644 index 4094d2a22b..0000000000 --- a/dist/cjs/client/websocket.js.map +++ /dev/null @@ -1 +0,0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,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;gBACjE,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACb,MAAA,IAAI,CAAC,OAAO,qDAAG,KAAc,CAAC,CAAC;oBAC/B,OAAO;gBACX,CAAC;gBAED,MAAA,IAAI,CAAC,SAAS,qDAAG,OAAO,CAAC,CAAC;YAC9B,CAAC,CAAC;QACN,CAAC,CAAC,CAAC;IACP,CAAC;IAED,KAAK,CAAC,KAAK;;QACP,MAAA,IAAI,CAAC,OAAO,0CAAE,KAAK,EAAE,CAAC;IAC1B,CAAC;IAED,IAAI,CAAC,OAAuB;QACxB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;;YACnC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;gBAChB,MAAM,CAAC,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC,CAAC;gBACnC,OAAO;YACX,CAAC;YAED,MAAA,IAAI,CAAC,OAAO,0CAAE,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;YAC5C,OAAO,EAAE,CAAC;QACd,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAjED,4DAiEC"} \ No newline at end of file diff --git a/dist/cjs/examples/client/elicitationUrlExample.d.ts b/dist/cjs/examples/client/elicitationUrlExample.d.ts deleted file mode 100644 index 611f6eba22..0000000000 --- a/dist/cjs/examples/client/elicitationUrlExample.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=elicitationUrlExample.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/client/elicitationUrlExample.d.ts.map b/dist/cjs/examples/client/elicitationUrlExample.d.ts.map deleted file mode 100644 index e749adfb95..0000000000 --- a/dist/cjs/examples/client/elicitationUrlExample.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"elicitationUrlExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/elicitationUrlExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/client/elicitationUrlExample.js b/dist/cjs/examples/client/elicitationUrlExample.js deleted file mode 100644 index fac53f0489..0000000000 --- a/dist/cjs/examples/client/elicitationUrlExample.js +++ /dev/null @@ -1,693 +0,0 @@ -"use strict"; -// Run with: npx tsx src/examples/client/elicitationUrlExample.ts -// -// This example demonstrates how to use URL elicitation to securely -// collect user input in a remote (HTTP) server. -// URL elicitation allows servers to prompt the end-user to open a URL in their browser -// to collect sensitive information. -Object.defineProperty(exports, "__esModule", { value: true }); -const index_js_1 = require("../../client/index.js"); -const streamableHttp_js_1 = require("../../client/streamableHttp.js"); -const node_readline_1 = require("node:readline"); -const types_js_1 = require("../../types.js"); -const metadataUtils_js_1 = require("../../shared/metadataUtils.js"); -const node_child_process_1 = require("node:child_process"); -const simpleOAuthClientProvider_js_1 = require("./simpleOAuthClientProvider.js"); -const auth_js_1 = require("../../client/auth.js"); -const node_http_1 = require("node:http"); -// Set up OAuth (required for this example) -const OAUTH_CALLBACK_PORT = 8090; // Use different port than auth server (3001) -const OAUTH_CALLBACK_URL = `http://localhost:${OAUTH_CALLBACK_PORT}/callback`; -let oauthProvider = undefined; -console.log('Getting OAuth token...'); -const clientMetadata = { - client_name: 'Elicitation MCP Client', - redirect_uris: [OAUTH_CALLBACK_URL], - grant_types: ['authorization_code', 'refresh_token'], - response_types: ['code'], - token_endpoint_auth_method: 'client_secret_post', - scope: 'mcp:tools' -}; -oauthProvider = new simpleOAuthClientProvider_js_1.InMemoryOAuthClientProvider(OAUTH_CALLBACK_URL, clientMetadata, (redirectUrl) => { - console.log(`🌐 Opening browser for OAuth redirect: ${redirectUrl.toString()}`); - openBrowser(redirectUrl.toString()); -}); -// Create readline interface for user input -const readline = (0, node_readline_1.createInterface)({ - input: process.stdin, - output: process.stdout -}); -let abortCommand = new AbortController(); -// Global client and transport for interactive commands -let client = null; -let transport = null; -let serverUrl = 'http://localhost:3000/mcp'; -let sessionId = undefined; -let isProcessingCommand = false; -let isProcessingElicitations = false; -const elicitationQueue = []; -let elicitationQueueSignal = null; -let elicitationsCompleteSignal = null; -// Map to track pending URL elicitations waiting for completion notifications -const pendingURLElicitations = new Map(); -async function main() { - console.log('MCP Interactive Client'); - console.log('====================='); - // Connect to server immediately with default settings - await connect(); - // Start the elicitation loop in the background - elicitationLoop().catch(error => { - console.error('Unexpected error in elicitation loop:', error); - process.exit(1); - }); - // Short delay allowing the server to send any SSE elicitations on connection - await new Promise(resolve => setTimeout(resolve, 200)); - // Wait until we are done processing any initial elicitations - await waitForElicitationsToComplete(); - // Print help and start the command loop - printHelp(); - await commandLoop(); -} -async function waitForElicitationsToComplete() { - // Wait until the queue is empty and nothing is being processed - while (elicitationQueue.length > 0 || isProcessingElicitations) { - await new Promise(resolve => setTimeout(resolve, 100)); - } -} -function printHelp() { - console.log('\nAvailable commands:'); - console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)'); - console.log(' disconnect - Disconnect from server'); - console.log(' terminate-session - Terminate the current session'); - console.log(' reconnect - Reconnect to the server'); - console.log(' list-tools - List available tools'); - console.log(' call-tool [args] - Call a tool with optional JSON arguments'); - console.log(' payment-confirm - Test URL elicitation via error response with payment-confirm tool'); - console.log(' third-party-auth - Test tool that requires third-party OAuth credentials'); - console.log(' help - Show this help'); - console.log(' quit - Exit the program'); -} -async function commandLoop() { - await new Promise(resolve => { - if (!isProcessingElicitations) { - resolve(); - } - else { - elicitationsCompleteSignal = resolve; - } - }); - readline.question('\n> ', { signal: abortCommand.signal }, async (input) => { - var _a; - isProcessingCommand = true; - const args = input.trim().split(/\s+/); - const command = (_a = args[0]) === null || _a === void 0 ? void 0 : _a.toLowerCase(); - try { - switch (command) { - case 'connect': - await connect(args[1]); - break; - case 'disconnect': - await disconnect(); - break; - case 'terminate-session': - await terminateSession(); - break; - case 'reconnect': - await reconnect(); - break; - case 'list-tools': - await listTools(); - break; - case 'call-tool': - if (args.length < 2) { - console.log('Usage: call-tool [args]'); - } - else { - const toolName = args[1]; - let toolArgs = {}; - if (args.length > 2) { - try { - toolArgs = JSON.parse(args.slice(2).join(' ')); - } - catch (_b) { - console.log('Invalid JSON arguments. Using empty args.'); - } - } - await callTool(toolName, toolArgs); - } - break; - case 'payment-confirm': - await callPaymentConfirmTool(); - break; - case 'third-party-auth': - await callThirdPartyAuthTool(); - break; - case 'help': - printHelp(); - break; - case 'quit': - case 'exit': - await cleanup(); - return; - default: - if (command) { - console.log(`Unknown command: ${command}`); - } - break; - } - } - catch (error) { - console.error(`Error executing command: ${error}`); - } - finally { - isProcessingCommand = false; - } - // Process another command after we've processed the this one - await commandLoop(); - }); -} -async function elicitationLoop() { - while (true) { - // Wait until we have elicitations to process - await new Promise(resolve => { - if (elicitationQueue.length > 0) { - resolve(); - } - else { - elicitationQueueSignal = resolve; - } - }); - isProcessingElicitations = true; - abortCommand.abort(); // Abort the command loop if it's running - // Process all queued elicitations - while (elicitationQueue.length > 0) { - const queued = elicitationQueue.shift(); - console.log(`📤 Processing queued elicitation (${elicitationQueue.length} remaining)`); - try { - const result = await handleElicitationRequest(queued.request); - queued.resolve(result); - } - catch (error) { - queued.reject(error instanceof Error ? error : new Error(String(error))); - } - } - console.log('✅ All queued elicitations processed. Resuming command loop...\n'); - isProcessingElicitations = false; - // Reset the abort controller for the next command loop - abortCommand = new AbortController(); - // Resume the command loop - if (elicitationsCompleteSignal) { - elicitationsCompleteSignal(); - elicitationsCompleteSignal = null; - } - } -} -async function openBrowser(url) { - const command = `open "${url}"`; - (0, node_child_process_1.exec)(command, error => { - if (error) { - console.error(`Failed to open browser: ${error.message}`); - console.log(`Please manually open: ${url}`); - } - }); -} -/** - * Enqueues an elicitation request and returns the result. - * - * This function is used so that our CLI (which can only handle one input request at a time) - * can handle elicitation requests and the command loop. - * - * @param request - The elicitation request to be handled - * @returns The elicitation result - */ -async function elicitationRequestHandler(request) { - // If we are processing a command, handle this elicitation immediately - if (isProcessingCommand) { - console.log('📋 Processing elicitation immediately (during command execution)'); - return await handleElicitationRequest(request); - } - // Otherwise, queue the request to be handled by the elicitation loop - console.log(`📥 Queueing elicitation request (queue size will be: ${elicitationQueue.length + 1})`); - return new Promise((resolve, reject) => { - elicitationQueue.push({ - request, - resolve, - reject - }); - // Signal the elicitation loop that there's work to do - if (elicitationQueueSignal) { - elicitationQueueSignal(); - elicitationQueueSignal = null; - } - }); -} -/** - * Handles an elicitation request. - * - * This function is used to handle the elicitation request and return the result. - * - * @param request - The elicitation request to be handled - * @returns The elicitation result - */ -async function handleElicitationRequest(request) { - const mode = request.params.mode; - console.log('\n🔔 Elicitation Request Received:'); - console.log(`Mode: ${mode}`); - if (mode === 'url') { - return { - action: await handleURLElicitation(request.params) - }; - } - else { - // Should not happen because the client declares its capabilities to the server, - // but being defensive is a good practice: - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Unsupported elicitation mode: ${mode}`); - } -} -/** - * Handles a URL elicitation by opening the URL in the browser. - * - * Note: This is a shared code for both request handlers and error handlers. - * As a result of sharing schema, there is no big forking of logic for the client. - * - * @param params - The URL elicitation request parameters - * @returns The action to take (accept, cancel, or decline) - */ -async function handleURLElicitation(params) { - const url = params.url; - const elicitationId = params.elicitationId; - const message = params.message; - console.log(`🆔 Elicitation ID: ${elicitationId}`); // Print for illustration - // Parse URL to show domain for security - let domain = 'unknown domain'; - try { - const parsedUrl = new URL(url); - domain = parsedUrl.hostname; - } - catch (_a) { - console.error('Invalid URL provided by server'); - return 'decline'; - } - // Example security warning to help prevent phishing attacks - console.log('\n⚠️ \x1b[33mSECURITY WARNING\x1b[0m ⚠️'); - console.log('\x1b[33mThe server is requesting you to open an external URL.\x1b[0m'); - console.log('\x1b[33mOnly proceed if you trust this server and understand why it needs this.\x1b[0m\n'); - console.log(`🌐 Target domain: \x1b[36m${domain}\x1b[0m`); - console.log(`🔗 Full URL: \x1b[36m${url}\x1b[0m`); - console.log(`\nℹ️ Server's reason:\n\n\x1b[36m${message}\x1b[0m\n`); - // 1. Ask for user consent to open the URL - const consent = await new Promise(resolve => { - readline.question('\nDo you want to open this URL in your browser? (y/n): ', input => { - resolve(input.trim().toLowerCase()); - }); - }); - // 2. If user did not consent, return appropriate result - if (consent === 'no' || consent === 'n') { - console.log('❌ URL navigation declined.'); - return 'decline'; - } - else if (consent !== 'yes' && consent !== 'y') { - console.log('🚫 Invalid response. Cancelling elicitation.'); - return 'cancel'; - } - // 3. Wait for completion notification in the background - const completionPromise = new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - pendingURLElicitations.delete(elicitationId); - console.log(`\x1b[31m❌ Elicitation ${elicitationId} timed out waiting for completion.\x1b[0m`); - reject(new Error('Elicitation completion timeout')); - }, 5 * 60 * 1000); // 5 minute timeout - pendingURLElicitations.set(elicitationId, { - resolve: () => { - clearTimeout(timeout); - resolve(); - }, - reject, - timeout - }); - }); - completionPromise.catch(error => { - console.error('Background completion wait failed:', error); - }); - // 4. Open the URL in the browser - console.log(`\n🚀 Opening browser to: ${url}`); - await openBrowser(url); - console.log('\n⏳ Waiting for you to complete the interaction in your browser...'); - console.log(' The server will send a notification once you complete the action.'); - // 5. Acknowledge the user accepted the elicitation - return 'accept'; -} -/** - * Example OAuth callback handler - in production, use a more robust approach - * for handling callbacks and storing tokens - */ -/** - * Starts a temporary HTTP server to receive the OAuth callback - */ -async function waitForOAuthCallback() { - return new Promise((resolve, reject) => { - const server = (0, node_http_1.createServer)((req, res) => { - // Ignore favicon requests - if (req.url === '/favicon.ico') { - res.writeHead(404); - res.end(); - return; - } - console.log(`📥 Received callback: ${req.url}`); - const parsedUrl = new URL(req.url || '', 'http://localhost'); - const code = parsedUrl.searchParams.get('code'); - const error = parsedUrl.searchParams.get('error'); - if (code) { - console.log(`✅ Authorization code received: ${code === null || code === void 0 ? void 0 : code.substring(0, 10)}...`); - res.writeHead(200, { 'Content-Type': 'text/html' }); - res.end(` - - -

Authorization Successful!

-

This simulates successful authorization of the MCP client, which now has an access token for the MCP server.

-

This window will close automatically in 10 seconds.

- - - - `); - resolve(code); - setTimeout(() => server.close(), 15000); - } - else if (error) { - console.log(`❌ Authorization error: ${error}`); - res.writeHead(400, { 'Content-Type': 'text/html' }); - res.end(` - - -

Authorization Failed

-

Error: ${error}

- - - `); - reject(new Error(`OAuth authorization failed: ${error}`)); - } - else { - console.log(`❌ No authorization code or error in callback`); - res.writeHead(400); - res.end('Bad request'); - reject(new Error('No authorization code provided')); - } - }); - server.listen(OAUTH_CALLBACK_PORT, () => { - console.log(`OAuth callback server started on http://localhost:${OAUTH_CALLBACK_PORT}`); - }); - }); -} -/** - * Attempts to connect to the MCP server with OAuth authentication. - * Handles OAuth flow recursively if authorization is required. - */ -async function attemptConnection(oauthProvider) { - console.log('🚢 Creating transport with OAuth provider...'); - const baseUrl = new URL(serverUrl); - transport = new streamableHttp_js_1.StreamableHTTPClientTransport(baseUrl, { - sessionId: sessionId, - authProvider: oauthProvider - }); - console.log('🚢 Transport created'); - try { - console.log('🔌 Attempting connection (this will trigger OAuth redirect if needed)...'); - await client.connect(transport); - sessionId = transport.sessionId; - console.log('Transport created with session ID:', sessionId); - console.log('✅ Connected successfully'); - } - catch (error) { - if (error instanceof auth_js_1.UnauthorizedError) { - console.log('🔐 OAuth required - waiting for authorization...'); - const callbackPromise = waitForOAuthCallback(); - const authCode = await callbackPromise; - await transport.finishAuth(authCode); - console.log('🔐 Authorization code received:', authCode); - console.log('🔌 Reconnecting with authenticated transport...'); - // Recursively retry connection after OAuth completion - await attemptConnection(oauthProvider); - } - else { - console.error('❌ Connection failed with non-auth error:', error); - throw error; - } - } -} -async function connect(url) { - if (client) { - console.log('Already connected. Disconnect first.'); - return; - } - if (url) { - serverUrl = url; - } - console.log(`🔗 Attempting to connect to ${serverUrl}...`); - // Create a new client with elicitation capability - console.log('👤 Creating MCP client...'); - client = new index_js_1.Client({ - name: 'example-client', - version: '1.0.0' - }, { - capabilities: { - elicitation: { - // Only URL elicitation is supported in this demo - // (see server/elicitationExample.ts for a demo of form mode elicitation) - url: {} - } - } - }); - console.log('👤 Client created'); - // Set up elicitation request handler with proper validation - client.setRequestHandler(types_js_1.ElicitRequestSchema, elicitationRequestHandler); - // Set up notification handler for elicitation completion - client.setNotificationHandler(types_js_1.ElicitationCompleteNotificationSchema, notification => { - const { elicitationId } = notification.params; - const pending = pendingURLElicitations.get(elicitationId); - if (pending) { - clearTimeout(pending.timeout); - pendingURLElicitations.delete(elicitationId); - console.log(`\x1b[32m✅ Elicitation ${elicitationId} completed!\x1b[0m`); - pending.resolve(); - } - else { - // Shouldn't happen - discard it! - console.warn(`Received completion notification for unknown elicitation: ${elicitationId}`); - } - }); - try { - console.log('🔐 Starting OAuth flow...'); - await attemptConnection(oauthProvider); - console.log('Connected to MCP server'); - // Set up error handler after connection is established so we don't double log errors - client.onerror = error => { - console.error('\x1b[31mClient error:', error, '\x1b[0m'); - }; - } - catch (error) { - console.error('Failed to connect:', error); - client = null; - transport = null; - return; - } -} -async function disconnect() { - if (!client || !transport) { - console.log('Not connected.'); - return; - } - try { - await transport.close(); - console.log('Disconnected from MCP server'); - client = null; - transport = null; - } - catch (error) { - console.error('Error disconnecting:', error); - } -} -async function terminateSession() { - if (!client || !transport) { - console.log('Not connected.'); - return; - } - try { - console.log('Terminating session with ID:', transport.sessionId); - await transport.terminateSession(); - console.log('Session terminated successfully'); - // Check if sessionId was cleared after termination - if (!transport.sessionId) { - console.log('Session ID has been cleared'); - sessionId = undefined; - // Also close the transport and clear client objects - await transport.close(); - console.log('Transport closed after session termination'); - client = null; - transport = null; - } - else { - console.log('Server responded with 405 Method Not Allowed (session termination not supported)'); - console.log('Session ID is still active:', transport.sessionId); - } - } - catch (error) { - console.error('Error terminating session:', error); - } -} -async function reconnect() { - if (client) { - await disconnect(); - } - await connect(); -} -async function listTools() { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const toolsRequest = { - method: 'tools/list', - params: {} - }; - const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema); - console.log('Available tools:'); - if (toolsResult.tools.length === 0) { - console.log(' No tools available'); - } - else { - for (const tool of toolsResult.tools) { - console.log(` - id: ${tool.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(tool)}, description: ${tool.description}`); - } - } - } - catch (error) { - console.log(`Tools not supported by this server (${error})`); - } -} -async function callTool(name, args) { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const request = { - method: 'tools/call', - params: { - name, - arguments: args - } - }; - console.log(`Calling tool '${name}' with args:`, args); - const result = await client.request(request, types_js_1.CallToolResultSchema); - console.log('Tool result:'); - const resourceLinks = []; - result.content.forEach(item => { - if (item.type === 'text') { - console.log(` ${item.text}`); - } - else if (item.type === 'resource_link') { - const resourceLink = item; - resourceLinks.push(resourceLink); - console.log(` 📁 Resource Link: ${resourceLink.name}`); - console.log(` URI: ${resourceLink.uri}`); - if (resourceLink.mimeType) { - console.log(` Type: ${resourceLink.mimeType}`); - } - if (resourceLink.description) { - console.log(` Description: ${resourceLink.description}`); - } - } - else if (item.type === 'resource') { - console.log(` [Embedded Resource: ${item.resource.uri}]`); - } - else if (item.type === 'image') { - console.log(` [Image: ${item.mimeType}]`); - } - else if (item.type === 'audio') { - console.log(` [Audio: ${item.mimeType}]`); - } - else { - console.log(` [Unknown content type]:`, item); - } - }); - // Offer to read resource links - if (resourceLinks.length > 0) { - console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource ' to read their content.`); - } - } - catch (error) { - if (error instanceof types_js_1.UrlElicitationRequiredError) { - console.log('\n🔔 Elicitation Required Error Received:'); - console.log(`Message: ${error.message}`); - for (const e of error.elicitations) { - await handleURLElicitation(e); // For the error handler, we discard the action result because we don't respond to an error response - } - return; - } - console.log(`Error calling tool ${name}: ${error}`); - } -} -async function cleanup() { - if (client && transport) { - try { - // First try to terminate the session gracefully - if (transport.sessionId) { - try { - console.log('Terminating session before exit...'); - await transport.terminateSession(); - console.log('Session terminated successfully'); - } - catch (error) { - console.error('Error terminating session:', error); - } - } - // Then close the transport - await transport.close(); - } - catch (error) { - console.error('Error closing transport:', error); - } - } - process.stdin.setRawMode(false); - readline.close(); - console.log('\nGoodbye!'); - process.exit(0); -} -async function callPaymentConfirmTool() { - console.log('Calling payment-confirm tool...'); - await callTool('payment-confirm', { cartId: 'cart_123' }); -} -async function callThirdPartyAuthTool() { - console.log('Calling third-party-auth tool...'); - await callTool('third-party-auth', { param1: 'test' }); -} -// Set up raw mode for keyboard input to capture Escape key -process.stdin.setRawMode(true); -process.stdin.on('data', async (data) => { - // Check for Escape key (27) - if (data.length === 1 && data[0] === 27) { - console.log('\nESC key pressed. Disconnecting from server...'); - // Abort current operation and disconnect from server - if (client && transport) { - await disconnect(); - console.log('Disconnected. Press Enter to continue.'); - } - else { - console.log('Not connected to server.'); - } - // Re-display the prompt - process.stdout.write('> '); - } -}); -// Handle Ctrl+C -process.on('SIGINT', async () => { - console.log('\nReceived SIGINT. Cleaning up...'); - await cleanup(); -}); -// Start the interactive client -main().catch((error) => { - console.error('Error running MCP client:', error); - process.exit(1); -}); -//# sourceMappingURL=elicitationUrlExample.js.map \ No newline at end of file diff --git a/dist/cjs/examples/client/elicitationUrlExample.js.map b/dist/cjs/examples/client/elicitationUrlExample.js.map deleted file mode 100644 index b17808ca78..0000000000 --- a/dist/cjs/examples/client/elicitationUrlExample.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"elicitationUrlExample.js","sourceRoot":"","sources":["../../../../src/examples/client/elicitationUrlExample.ts"],"names":[],"mappings":";AAAA,iEAAiE;AACjE,EAAE;AACF,mEAAmE;AACnE,gDAAgD;AAChD,uFAAuF;AACvF,oCAAoC;;AAEpC,oDAA+C;AAC/C,sEAA+E;AAC/E,iDAAgD;AAChD,6CAcwB;AACxB,oEAA+D;AAE/D,2DAA0C;AAC1C,iFAA6E;AAC7E,kDAAyD;AACzD,yCAAyC;AAEzC,2CAA2C;AAC3C,MAAM,mBAAmB,GAAG,IAAI,CAAC,CAAC,6CAA6C;AAC/E,MAAM,kBAA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IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/client/multipleClientsParallel.d.ts b/dist/cjs/examples/client/multipleClientsParallel.d.ts deleted file mode 100644 index 0ac5af8e56..0000000000 --- a/dist/cjs/examples/client/multipleClientsParallel.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=multipleClientsParallel.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/client/multipleClientsParallel.d.ts.map b/dist/cjs/examples/client/multipleClientsParallel.d.ts.map deleted file mode 100644 index 91051dc946..0000000000 --- a/dist/cjs/examples/client/multipleClientsParallel.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"multipleClientsParallel.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/multipleClientsParallel.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/client/multipleClientsParallel.js b/dist/cjs/examples/client/multipleClientsParallel.js deleted file mode 100644 index 5cfbb2f4d5..0000000000 --- a/dist/cjs/examples/client/multipleClientsParallel.js +++ /dev/null @@ -1,134 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const index_js_1 = require("../../client/index.js"); -const streamableHttp_js_1 = require("../../client/streamableHttp.js"); -const types_js_1 = require("../../types.js"); -/** - * Multiple Clients MCP Example - * - * This client demonstrates how to: - * 1. Create multiple MCP clients in parallel - * 2. Each client calls a single tool - * 3. Track notifications from each client independently - */ -// Command line args processing -const args = process.argv.slice(2); -const serverUrl = args[0] || 'http://localhost:3000/mcp'; -async function createAndRunClient(config) { - console.log(`[${config.id}] Creating client: ${config.name}`); - const client = new index_js_1.Client({ - name: config.name, - version: '1.0.0' - }); - const transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(serverUrl)); - // Set up client-specific error handler - client.onerror = error => { - console.error(`[${config.id}] Client error:`, error); - }; - // Set up client-specific notification handler - client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => { - console.log(`[${config.id}] Notification: ${notification.params.data}`); - }); - try { - // Connect to the server - await client.connect(transport); - console.log(`[${config.id}] Connected to MCP server`); - // Call the specified tool - console.log(`[${config.id}] Calling tool: ${config.toolName}`); - const toolRequest = { - method: 'tools/call', - params: { - name: config.toolName, - arguments: { - ...config.toolArguments, - // Add client ID to arguments for identification in notifications - caller: config.id - } - } - }; - const result = await client.request(toolRequest, types_js_1.CallToolResultSchema); - console.log(`[${config.id}] Tool call completed`); - // Keep the connection open for a bit to receive notifications - await new Promise(resolve => setTimeout(resolve, 5000)); - // Disconnect - await transport.close(); - console.log(`[${config.id}] Disconnected from MCP server`); - return { id: config.id, result }; - } - catch (error) { - console.error(`[${config.id}] Error:`, error); - throw error; - } -} -async function main() { - console.log('MCP Multiple Clients Example'); - console.log('============================'); - console.log(`Server URL: ${serverUrl}`); - console.log(''); - try { - // Define client configurations - const clientConfigs = [ - { - id: 'client1', - name: 'basic-client-1', - toolName: 'start-notification-stream', - toolArguments: { - interval: 3, // 1 second between notifications - count: 5 // Send 5 notifications - } - }, - { - id: 'client2', - name: 'basic-client-2', - toolName: 'start-notification-stream', - toolArguments: { - interval: 2, // 2 seconds between notifications - count: 3 // Send 3 notifications - } - }, - { - id: 'client3', - name: 'basic-client-3', - toolName: 'start-notification-stream', - toolArguments: { - interval: 1, // 0.5 second between notifications - count: 8 // Send 8 notifications - } - } - ]; - // Start all clients in parallel - console.log(`Starting ${clientConfigs.length} clients in parallel...`); - console.log(''); - const clientPromises = clientConfigs.map(config => createAndRunClient(config)); - const results = await Promise.all(clientPromises); - // Display results from all clients - console.log('\n=== Final Results ==='); - results.forEach(({ id, result }) => { - console.log(`\n[${id}] Tool result:`); - if (Array.isArray(result.content)) { - result.content.forEach((item) => { - if (item.type === 'text' && item.text) { - console.log(` ${item.text}`); - } - else { - console.log(` ${item.type} content:`, item); - } - }); - } - else { - console.log(` Unexpected result format:`, result); - } - }); - console.log('\n=== All clients completed successfully ==='); - } - catch (error) { - console.error('Error running multiple clients:', error); - process.exit(1); - } -} -// Start the example -main().catch((error) => { - console.error('Error running MCP multiple clients example:', error); - process.exit(1); -}); -//# sourceMappingURL=multipleClientsParallel.js.map \ No newline at end of file diff --git a/dist/cjs/examples/client/multipleClientsParallel.js.map b/dist/cjs/examples/client/multipleClientsParallel.js.map deleted file mode 100644 index 05812d11ad..0000000000 --- a/dist/cjs/examples/client/multipleClientsParallel.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"multipleClientsParallel.js","sourceRoot":"","sources":["../../../../src/examples/client/multipleClientsParallel.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,sEAA+E;AAC/E,6CAAyH;AAEzH;;;;;;;GAOG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AASzD,KAAK,UAAU,kBAAkB,CAAC,MAAoB;IAClD,OAAO,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,EAAE,sBAAsB,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;IAE9D,MAAM,MAAM,GAAG,IAAI,iBAAM,CAAC;QACtB,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,OAAO,EAAE,OAAO;KACnB,CAAC,CAAC;IAEH,MAAM,SAAS,GAAG,IAAI,iDAA6B,CAAC,IAAI,GAAG,CAAC,SAAS,CAAC,CAAC,CAAC;IAExE,uCAAuC;IACvC,MAAM,CAAC,OAAO,GAAG,KAAK,CAAC,EAAE;QACrB,OAAO,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,EAAE,iBAAiB,EAAE,KAAK,CAAC,CAAC;IACzD,CAAC,CAAC;IAEF,8CAA8C;IAC9C,MAAM,CAAC,sBAAsB,CAAC,2CAAgC,EAAE,YAAY,CAAC,E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,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/client/parallelToolCallsClient.d.ts b/dist/cjs/examples/client/parallelToolCallsClient.d.ts deleted file mode 100644 index e93d4d69d2..0000000000 --- a/dist/cjs/examples/client/parallelToolCallsClient.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=parallelToolCallsClient.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/client/parallelToolCallsClient.d.ts.map b/dist/cjs/examples/client/parallelToolCallsClient.d.ts.map deleted file mode 100644 index 25a3b820cf..0000000000 --- a/dist/cjs/examples/client/parallelToolCallsClient.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"parallelToolCallsClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/parallelToolCallsClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/client/parallelToolCallsClient.js b/dist/cjs/examples/client/parallelToolCallsClient.js deleted file mode 100644 index e5a9829e9e..0000000000 --- a/dist/cjs/examples/client/parallelToolCallsClient.js +++ /dev/null @@ -1,176 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const index_js_1 = require("../../client/index.js"); -const streamableHttp_js_1 = require("../../client/streamableHttp.js"); -const types_js_1 = require("../../types.js"); -/** - * Parallel Tool Calls MCP Client - * - * This client demonstrates how to: - * 1. Start multiple tool calls in parallel - * 2. Track notifications from each tool call using a caller parameter - */ -// Command line args processing -const args = process.argv.slice(2); -const serverUrl = args[0] || 'http://localhost:3000/mcp'; -async function main() { - console.log('MCP Parallel Tool Calls Client'); - console.log('=============================='); - console.log(`Connecting to server at: ${serverUrl}`); - let client; - let transport; - try { - // Create client with streamable HTTP transport - client = new index_js_1.Client({ - name: 'parallel-tool-calls-client', - version: '1.0.0' - }); - client.onerror = error => { - console.error('Client error:', error); - }; - // Connect to the server - transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(serverUrl)); - await client.connect(transport); - console.log('Successfully connected to MCP server'); - // Set up notification handler with caller identification - client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => { - console.log(`Notification: ${notification.params.data}`); - }); - console.log('List tools'); - const toolsRequest = await listTools(client); - console.log('Tools: ', toolsRequest); - // 2. Start multiple notification tools in parallel - console.log('\n=== Starting Multiple Notification Streams in Parallel ==='); - const toolResults = await startParallelNotificationTools(client); - // Log the results from each tool call - for (const [caller, result] of Object.entries(toolResults)) { - console.log(`\n=== Tool result for ${caller} ===`); - result.content.forEach((item) => { - if (item.type === 'text') { - console.log(` ${item.text}`); - } - else { - console.log(` ${item.type} content:`, item); - } - }); - } - // 3. Wait for all notifications (10 seconds) - console.log('\n=== Waiting for all notifications ==='); - await new Promise(resolve => setTimeout(resolve, 10000)); - // 4. Disconnect - console.log('\n=== Disconnecting ==='); - await transport.close(); - console.log('Disconnected from MCP server'); - } - catch (error) { - console.error('Error running client:', error); - process.exit(1); - } -} -/** - * List available tools on the server - */ -async function listTools(client) { - try { - const toolsRequest = { - method: 'tools/list', - params: {} - }; - const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema); - console.log('Available tools:'); - if (toolsResult.tools.length === 0) { - console.log(' No tools available'); - } - else { - for (const tool of toolsResult.tools) { - console.log(` - ${tool.name}: ${tool.description}`); - } - } - } - catch (error) { - console.log(`Tools not supported by this server: ${error}`); - } -} -/** - * Start multiple notification tools in parallel with different configurations - * Each tool call includes a caller parameter to identify its notifications - */ -async function startParallelNotificationTools(client) { - try { - // Define multiple tool calls with different configurations - const toolCalls = [ - { - caller: 'fast-notifier', - request: { - method: 'tools/call', - params: { - name: 'start-notification-stream', - arguments: { - interval: 2, // 0.5 second between notifications - count: 10, // Send 10 notifications - caller: 'fast-notifier' // Identify this tool call - } - } - } - }, - { - caller: 'slow-notifier', - request: { - method: 'tools/call', - params: { - name: 'start-notification-stream', - arguments: { - interval: 5, // 2 seconds between notifications - count: 5, // Send 5 notifications - caller: 'slow-notifier' // Identify this tool call - } - } - } - }, - { - caller: 'burst-notifier', - request: { - method: 'tools/call', - params: { - name: 'start-notification-stream', - arguments: { - interval: 1, // 0.1 second between notifications - count: 3, // Send just 3 notifications - caller: 'burst-notifier' // Identify this tool call - } - } - } - } - ]; - console.log(`Starting ${toolCalls.length} notification tools in parallel...`); - // Start all tool calls in parallel - const toolPromises = toolCalls.map(({ caller, request }) => { - console.log(`Starting tool call for ${caller}...`); - return client - .request(request, types_js_1.CallToolResultSchema) - .then(result => ({ caller, result })) - .catch(error => { - console.error(`Error in tool call for ${caller}:`, error); - throw error; - }); - }); - // Wait for all tool calls to complete - const results = await Promise.all(toolPromises); - // Organize results by caller - const resultsByTool = {}; - results.forEach(({ caller, result }) => { - resultsByTool[caller] = result; - }); - return resultsByTool; - } - catch (error) { - console.error(`Error starting parallel notification tools:`, error); - throw error; - } -} -// Start the client -main().catch((error) => { - console.error('Error running MCP client:', error); - process.exit(1); -}); -//# sourceMappingURL=parallelToolCallsClient.js.map \ No newline at end of file diff --git a/dist/cjs/examples/client/parallelToolCallsClient.js.map b/dist/cjs/examples/client/parallelToolCallsClient.js.map deleted file mode 100644 index dabdf4895b..0000000000 --- a/dist/cjs/examples/client/parallelToolCallsClient.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"parallelToolCallsClient.js","sourceRoot":"","sources":["../../../../src/examples/client/parallelToolCallsClient.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,sEAA+E;AAC/E,6CAMwB;AAExB;;;;;;GAMG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AAEzD,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;IAC9C,OAAO,CAAC,GAAG,CAAC,gCAAgC,CA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K,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleOAuthClient.d.ts b/dist/cjs/examples/client/simpleOAuthClient.d.ts deleted file mode 100644 index e4b43dbc01..0000000000 --- a/dist/cjs/examples/client/simpleOAuthClient.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env node -export {}; -//# sourceMappingURL=simpleOAuthClient.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleOAuthClient.d.ts.map b/dist/cjs/examples/client/simpleOAuthClient.d.ts.map deleted file mode 100644 index c09eef86ea..0000000000 --- a/dist/cjs/examples/client/simpleOAuthClient.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleOAuthClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleOAuthClient.js b/dist/cjs/examples/client/simpleOAuthClient.js deleted file mode 100644 index 726201937c..0000000000 --- a/dist/cjs/examples/client/simpleOAuthClient.js +++ /dev/null @@ -1,337 +0,0 @@ -#!/usr/bin/env node -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const node_http_1 = require("node:http"); -const node_readline_1 = require("node:readline"); -const node_url_1 = require("node:url"); -const node_child_process_1 = require("node:child_process"); -const index_js_1 = require("../../client/index.js"); -const streamableHttp_js_1 = require("../../client/streamableHttp.js"); -const types_js_1 = require("../../types.js"); -const auth_js_1 = require("../../client/auth.js"); -const simpleOAuthClientProvider_js_1 = require("./simpleOAuthClientProvider.js"); -// Configuration -const DEFAULT_SERVER_URL = 'http://localhost:3000/mcp'; -const CALLBACK_PORT = 8090; // Use different port than auth server (3001) -const CALLBACK_URL = `http://localhost:${CALLBACK_PORT}/callback`; -/** - * Interactive MCP client with OAuth authentication - * Demonstrates the complete OAuth flow with browser-based authorization - */ -class InteractiveOAuthClient { - constructor(serverUrl, clientMetadataUrl) { - this.serverUrl = serverUrl; - this.clientMetadataUrl = clientMetadataUrl; - this.client = null; - this.rl = (0, node_readline_1.createInterface)({ - input: process.stdin, - output: process.stdout - }); - } - /** - * Prompts user for input via readline - */ - async question(query) { - return new Promise(resolve => { - this.rl.question(query, resolve); - }); - } - /** - * Opens the authorization URL in the user's default browser - */ - async openBrowser(url) { - console.log(`🌐 Opening browser for authorization: ${url}`); - const command = `open "${url}"`; - (0, node_child_process_1.exec)(command, error => { - if (error) { - console.error(`Failed to open browser: ${error.message}`); - console.log(`Please manually open: ${url}`); - } - }); - } - /** - * Example OAuth callback handler - in production, use a more robust approach - * for handling callbacks and storing tokens - */ - /** - * Starts a temporary HTTP server to receive the OAuth callback - */ - async waitForOAuthCallback() { - return new Promise((resolve, reject) => { - const server = (0, node_http_1.createServer)((req, res) => { - // Ignore favicon requests - if (req.url === '/favicon.ico') { - res.writeHead(404); - res.end(); - return; - } - console.log(`📥 Received callback: ${req.url}`); - const parsedUrl = new node_url_1.URL(req.url || '', 'http://localhost'); - const code = parsedUrl.searchParams.get('code'); - const error = parsedUrl.searchParams.get('error'); - if (code) { - console.log(`✅ Authorization code received: ${code === null || code === void 0 ? void 0 : code.substring(0, 10)}...`); - res.writeHead(200, { 'Content-Type': 'text/html' }); - res.end(` - - -

Authorization Successful!

-

You can close this window and return to the terminal.

- - - - `); - resolve(code); - setTimeout(() => server.close(), 3000); - } - else if (error) { - console.log(`❌ Authorization error: ${error}`); - res.writeHead(400, { 'Content-Type': 'text/html' }); - res.end(` - - -

Authorization Failed

-

Error: ${error}

- - - `); - reject(new Error(`OAuth authorization failed: ${error}`)); - } - else { - console.log(`❌ No authorization code or error in callback`); - res.writeHead(400); - res.end('Bad request'); - reject(new Error('No authorization code provided')); - } - }); - server.listen(CALLBACK_PORT, () => { - console.log(`OAuth callback server started on http://localhost:${CALLBACK_PORT}`); - }); - }); - } - async attemptConnection(oauthProvider) { - console.log('🚢 Creating transport with OAuth provider...'); - const baseUrl = new node_url_1.URL(this.serverUrl); - const transport = new streamableHttp_js_1.StreamableHTTPClientTransport(baseUrl, { - authProvider: oauthProvider - }); - console.log('🚢 Transport created'); - try { - console.log('🔌 Attempting connection (this will trigger OAuth redirect)...'); - await this.client.connect(transport); - console.log('✅ Connected successfully'); - } - catch (error) { - if (error instanceof auth_js_1.UnauthorizedError) { - console.log('🔐 OAuth required - waiting for authorization...'); - const callbackPromise = this.waitForOAuthCallback(); - const authCode = await callbackPromise; - await transport.finishAuth(authCode); - console.log('🔐 Authorization code received:', authCode); - console.log('🔌 Reconnecting with authenticated transport...'); - await this.attemptConnection(oauthProvider); - } - else { - console.error('❌ Connection failed with non-auth error:', error); - throw error; - } - } - } - /** - * Establishes connection to the MCP server with OAuth authentication - */ - async connect() { - console.log(`🔗 Attempting to connect to ${this.serverUrl}...`); - const clientMetadata = { - client_name: 'Simple OAuth MCP Client', - redirect_uris: [CALLBACK_URL], - grant_types: ['authorization_code', 'refresh_token'], - response_types: ['code'], - token_endpoint_auth_method: 'client_secret_post' - }; - console.log('🔐 Creating OAuth provider...'); - const oauthProvider = new simpleOAuthClientProvider_js_1.InMemoryOAuthClientProvider(CALLBACK_URL, clientMetadata, (redirectUrl) => { - console.log(`📌 OAuth redirect handler called - opening browser`); - console.log(`Opening browser to: ${redirectUrl.toString()}`); - this.openBrowser(redirectUrl.toString()); - }, this.clientMetadataUrl); - console.log('🔐 OAuth provider created'); - console.log('👤 Creating MCP client...'); - this.client = new index_js_1.Client({ - name: 'simple-oauth-client', - version: '1.0.0' - }, { capabilities: {} }); - console.log('👤 Client created'); - console.log('🔐 Starting OAuth flow...'); - await this.attemptConnection(oauthProvider); - // Start interactive loop - await this.interactiveLoop(); - } - /** - * Main interactive loop for user commands - */ - async interactiveLoop() { - console.log('\n🎯 Interactive MCP Client with OAuth'); - console.log('Commands:'); - console.log(' list - List available tools'); - console.log(' call [args] - Call a tool'); - console.log(' quit - Exit the client'); - console.log(); - while (true) { - try { - const command = await this.question('mcp> '); - if (!command.trim()) { - continue; - } - if (command === 'quit') { - console.log('\n👋 Goodbye!'); - this.close(); - process.exit(0); - } - else if (command === 'list') { - await this.listTools(); - } - else if (command.startsWith('call ')) { - await this.handleCallTool(command); - } - else { - console.log("❌ Unknown command. Try 'list', 'call ', or 'quit'"); - } - } - catch (error) { - if (error instanceof Error && error.message === 'SIGINT') { - console.log('\n\n👋 Goodbye!'); - break; - } - console.error('❌ Error:', error); - } - } - } - async listTools() { - if (!this.client) { - console.log('❌ Not connected to server'); - return; - } - try { - const request = { - method: 'tools/list', - params: {} - }; - const result = await this.client.request(request, types_js_1.ListToolsResultSchema); - if (result.tools && result.tools.length > 0) { - console.log('\n📋 Available tools:'); - result.tools.forEach((tool, index) => { - console.log(`${index + 1}. ${tool.name}`); - if (tool.description) { - console.log(` Description: ${tool.description}`); - } - console.log(); - }); - } - else { - console.log('No tools available'); - } - } - catch (error) { - console.error('❌ Failed to list tools:', error); - } - } - async handleCallTool(command) { - const parts = command.split(/\s+/); - const toolName = parts[1]; - if (!toolName) { - console.log('❌ Please specify a tool name'); - return; - } - // Parse arguments (simple JSON-like format) - let toolArgs = {}; - if (parts.length > 2) { - const argsString = parts.slice(2).join(' '); - try { - toolArgs = JSON.parse(argsString); - } - catch (_a) { - console.log('❌ Invalid arguments format (expected JSON)'); - return; - } - } - await this.callTool(toolName, toolArgs); - } - async callTool(toolName, toolArgs) { - if (!this.client) { - console.log('❌ Not connected to server'); - return; - } - try { - const request = { - method: 'tools/call', - params: { - name: toolName, - arguments: toolArgs - } - }; - const result = await this.client.request(request, types_js_1.CallToolResultSchema); - console.log(`\n🔧 Tool '${toolName}' result:`); - if (result.content) { - result.content.forEach(content => { - if (content.type === 'text') { - console.log(content.text); - } - else { - console.log(content); - } - }); - } - else { - console.log(result); - } - } - catch (error) { - console.error(`❌ Failed to call tool '${toolName}':`, error); - } - } - close() { - this.rl.close(); - if (this.client) { - // Note: Client doesn't have a close method in the current implementation - // This would typically close the transport connection - } - } -} -/** - * Main entry point - */ -async function main() { - const args = process.argv.slice(2); - const serverUrl = args[0] || DEFAULT_SERVER_URL; - const clientMetadataUrl = args[1]; - console.log('🚀 Simple MCP OAuth Client'); - console.log(`Connecting to: ${serverUrl}`); - if (clientMetadataUrl) { - console.log(`Client Metadata URL: ${clientMetadataUrl}`); - } - console.log(); - const client = new InteractiveOAuthClient(serverUrl, clientMetadataUrl); - // Handle graceful shutdown - process.on('SIGINT', () => { - console.log('\n\n👋 Goodbye!'); - client.close(); - process.exit(0); - }); - try { - await client.connect(); - } - catch (error) { - console.error('Failed to start client:', error); - process.exit(1); - } - finally { - client.close(); - } -} -// Run if this file is executed directly -main().catch(error => { - console.error('Unhandled error:', error); - process.exit(1); -}); -//# sourceMappingURL=simpleOAuthClient.js.map \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleOAuthClient.js.map b/dist/cjs/examples/client/simpleOAuthClient.js.map deleted file mode 100644 index 10f698c529..0000000000 --- a/dist/cjs/examples/client/simpleOAuthClient.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleOAuthClient.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClient.ts"],"names":[],"mappings":";;;AAEA,yCAAyC;AACzC,iDAAgD;AAChD,uCAA+B;AAC/B,2DAA0C;AAC1C,oDAA+C;AAC/C,sEAA+E;AAE/E,6CAAgH;AAChH,kDAAyD;AACzD,iFAA6E;AAE7E,gBAAgB;AAChB,MAAM,kBAAkB,GAAG,2BAA2B,CAAC;AACvD,MAAM,aAAa,GAAG,IAAI,CAAC,CAAC,6CAA6C;AACzE,MAAM,YAAY,GAAG,oBAAoB,aAAa,WAAW,CAAC;AAElE;;;GAGG;AACH,MAAM,sBAAsB;IAOxB,YACY,SAAiB,EACjB,iBAA0B;QAD1B,cAAS,GAAT,S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EAAE,CAAC;QACpB,OAAO,CAAC,GAAG,CAAC,wBAAwB,iBAAiB,EAAE,CAAC,CAAC;IAC7D,CAAC;IACD,OAAO,CAAC,GAAG,EAAE,CAAC;IAEd,MAAM,MAAM,GAAG,IAAI,sBAAsB,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC;IAExE,2BAA2B;IAC3B,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;QACtB,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;QAC/B,MAAM,CAAC,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC;QACD,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;YAAS,CAAC;QACP,MAAM,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;AACL,CAAC;AAED,wCAAwC;AACxC,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;IACzC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts b/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts deleted file mode 100644 index 092616cf5c..0000000000 --- a/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { OAuthClientProvider } from '../../client/auth.js'; -import { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from '../../shared/auth.js'; -/** - * In-memory OAuth client provider for demonstration purposes - * In production, you should persist tokens securely - */ -export declare class InMemoryOAuthClientProvider implements OAuthClientProvider { - private readonly _redirectUrl; - private readonly _clientMetadata; - readonly clientMetadataUrl?: string | undefined; - private _clientInformation?; - private _tokens?; - private _codeVerifier?; - constructor(_redirectUrl: string | URL, _clientMetadata: OAuthClientMetadata, onRedirect?: (url: URL) => void, clientMetadataUrl?: string | undefined); - private _onRedirect; - get redirectUrl(): string | URL; - get clientMetadata(): OAuthClientMetadata; - clientInformation(): OAuthClientInformationMixed | undefined; - saveClientInformation(clientInformation: OAuthClientInformationMixed): void; - tokens(): OAuthTokens | undefined; - saveTokens(tokens: OAuthTokens): void; - redirectToAuthorization(authorizationUrl: URL): void; - saveCodeVerifier(codeVerifier: string): void; - codeVerifier(): string; -} -//# sourceMappingURL=simpleOAuthClientProvider.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts.map b/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts.map deleted file mode 100644 index 21efe9444a..0000000000 --- a/dist/cjs/examples/client/simpleOAuthClientProvider.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleOAuthClientProvider.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClientProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,2BAA2B,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAErG;;;GAGG;AACH,qBAAa,2BAA4B,YAAW,mBAAmB;IAM/D,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,eAAe;aAEhB,iBAAiB,CAAC,EAAE,MAAM;IAR9C,OAAO,CAAC,kBAAkB,CAAC,CAA8B;IACzD,OAAO,CAAC,OAAO,CAAC,CAAc;IAC9B,OAAO,CAAC,aAAa,CAAC,CAAS;gBAGV,YAAY,EAAE,MAAM,GAAG,GAAG,EAC1B,eAAe,EAAE,mBAAmB,EACrD,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,EACf,iBAAiB,CAAC,EAAE,MAAM,YAAA;IAS9C,OAAO,CAAC,WAAW,CAAqB;IAExC,IAAI,WAAW,IAAI,MAAM,GAAG,GAAG,CAE9B;IAED,IAAI,cAAc,IAAI,mBAAmB,CAExC;IAED,iBAAiB,IAAI,2BAA2B,GAAG,SAAS;IAI5D,qBAAqB,CAAC,iBAAiB,EAAE,2BAA2B,GAAG,IAAI;IAI3E,MAAM,IAAI,WAAW,GAAG,SAAS;IAIjC,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI;IAIrC,uBAAuB,CAAC,gBAAgB,EAAE,GAAG,GAAG,IAAI;IAIpD,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI;IAI5C,YAAY,IAAI,MAAM;CAMzB"} \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleOAuthClientProvider.js b/dist/cjs/examples/client/simpleOAuthClientProvider.js deleted file mode 100644 index 58959bbfcc..0000000000 --- a/dist/cjs/examples/client/simpleOAuthClientProvider.js +++ /dev/null @@ -1,51 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InMemoryOAuthClientProvider = void 0; -/** - * In-memory OAuth client provider for demonstration purposes - * In production, you should persist tokens securely - */ -class InMemoryOAuthClientProvider { - constructor(_redirectUrl, _clientMetadata, onRedirect, clientMetadataUrl) { - this._redirectUrl = _redirectUrl; - this._clientMetadata = _clientMetadata; - this.clientMetadataUrl = clientMetadataUrl; - this._onRedirect = - onRedirect || - (url => { - console.log(`Redirect to: ${url.toString()}`); - }); - } - get redirectUrl() { - return this._redirectUrl; - } - get clientMetadata() { - return this._clientMetadata; - } - clientInformation() { - return this._clientInformation; - } - saveClientInformation(clientInformation) { - this._clientInformation = clientInformation; - } - tokens() { - return this._tokens; - } - saveTokens(tokens) { - this._tokens = tokens; - } - redirectToAuthorization(authorizationUrl) { - this._onRedirect(authorizationUrl); - } - saveCodeVerifier(codeVerifier) { - this._codeVerifier = codeVerifier; - } - codeVerifier() { - if (!this._codeVerifier) { - throw new Error('No code verifier saved'); - } - return this._codeVerifier; - } -} -exports.InMemoryOAuthClientProvider = InMemoryOAuthClientProvider; -//# sourceMappingURL=simpleOAuthClientProvider.js.map \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleOAuthClientProvider.js.map b/dist/cjs/examples/client/simpleOAuthClientProvider.js.map deleted file mode 100644 index 10771f8e52..0000000000 --- a/dist/cjs/examples/client/simpleOAuthClientProvider.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleOAuthClientProvider.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClientProvider.ts"],"names":[],"mappings":";;;AAGA;;;GAGG;AACH,MAAa,2BAA2B;IAKpC,YACqB,YAA0B,EAC1B,eAAoC,EACrD,UAA+B,EACf,iBAA0B;QAHzB,iBAAY,GAAZ,YAAY,CAAc;QAC1B,oBAAe,GAAf,eAAe,CAAqB;QAErC,sBAAiB,GAAjB,iBAAiB,CAAS;QAE1C,IAAI,CAAC,WAAW;YACZ,UAAU;gBACV,CAAC,GAAG,CAAC,EAAE;oBACH,OAAO,CAAC,GAAG,CAAC,gBAAgB,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;gBAClD,CAAC,CAAC,CAAC;IACX,CAAC;IAID,IAAI,WAAW;QACX,OAAO,IAAI,CAAC,YAAY,CAAC;IAC7B,CAAC;IAED,IAAI,cAAc;QACd,OAAO,IAAI,CAAC,eAAe,CAAC;IAChC,CAAC;IAED,iBAAiB;QACb,OAAO,IAAI,CAAC,kBAAkB,CAAC;IACnC,CAAC;IAED,qBAAqB,CAAC,iBAA8C;QAChE,IAAI,CAAC,kBAAkB,GAAG,iBAAiB,CAAC;IAChD,CAAC;IAED,MAAM;QACF,OAAO,IAAI,CAAC,OAAO,CAAC;IACxB,CAAC;IAED,UAAU,CAAC,MAAmB;QAC1B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IAC1B,CAAC;IAED,uBAAuB,CAAC,gBAAqB;QACzC,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC;IACvC,CAAC;IAED,gBAAgB,CAAC,YAAoB;QACjC,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;IACtC,CAAC;IAED,YAAY;QACR,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACtB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC9C,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC;IAC9B,CAAC;CACJ;AA1DD,kEA0DC"} \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleStreamableHttp.d.ts b/dist/cjs/examples/client/simpleStreamableHttp.d.ts deleted file mode 100644 index a20be42ca4..0000000000 --- a/dist/cjs/examples/client/simpleStreamableHttp.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=simpleStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleStreamableHttp.d.ts.map b/dist/cjs/examples/client/simpleStreamableHttp.d.ts.map deleted file mode 100644 index 28406b0c1e..0000000000 --- a/dist/cjs/examples/client/simpleStreamableHttp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleStreamableHttp.js b/dist/cjs/examples/client/simpleStreamableHttp.js deleted file mode 100644 index efdff0a125..0000000000 --- a/dist/cjs/examples/client/simpleStreamableHttp.js +++ /dev/null @@ -1,749 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const index_js_1 = require("../../client/index.js"); -const streamableHttp_js_1 = require("../../client/streamableHttp.js"); -const node_readline_1 = require("node:readline"); -const types_js_1 = require("../../types.js"); -const metadataUtils_js_1 = require("../../shared/metadataUtils.js"); -const ajv_1 = require("ajv"); -// Create readline interface for user input -const readline = (0, node_readline_1.createInterface)({ - input: process.stdin, - output: process.stdout -}); -// Track received notifications for debugging resumability -let notificationCount = 0; -// Global client and transport for interactive commands -let client = null; -let transport = null; -let serverUrl = 'http://localhost:3000/mcp'; -let notificationsToolLastEventId = undefined; -let sessionId = undefined; -async function main() { - console.log('MCP Interactive Client'); - console.log('====================='); - // Connect to server immediately with default settings - await connect(); - // Print help and start the command loop - printHelp(); - commandLoop(); -} -function printHelp() { - console.log('\nAvailable commands:'); - console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)'); - console.log(' disconnect - Disconnect from server'); - console.log(' terminate-session - Terminate the current session'); - console.log(' reconnect - Reconnect to the server'); - console.log(' list-tools - List available tools'); - console.log(' call-tool [args] - Call a tool with optional JSON arguments'); - console.log(' greet [name] - Call the greet tool'); - console.log(' multi-greet [name] - Call the multi-greet tool with notifications'); - console.log(' collect-info [type] - Test form elicitation with collect-user-info tool (contact/preferences/feedback)'); - console.log(' start-notifications [interval] [count] - Start periodic notifications'); - console.log(' run-notifications-tool-with-resumability [interval] [count] - Run notification tool with resumability'); - console.log(' list-prompts - List available prompts'); - console.log(' get-prompt [name] [args] - Get a prompt with optional JSON arguments'); - console.log(' list-resources - List available resources'); - console.log(' read-resource - Read a specific resource by URI'); - console.log(' help - Show this help'); - console.log(' quit - Exit the program'); -} -function commandLoop() { - readline.question('\n> ', async (input) => { - var _a; - const args = input.trim().split(/\s+/); - const command = (_a = args[0]) === null || _a === void 0 ? void 0 : _a.toLowerCase(); - try { - switch (command) { - case 'connect': - await connect(args[1]); - break; - case 'disconnect': - await disconnect(); - break; - case 'terminate-session': - await terminateSession(); - break; - case 'reconnect': - await reconnect(); - break; - case 'list-tools': - await listTools(); - break; - case 'call-tool': - if (args.length < 2) { - console.log('Usage: call-tool [args]'); - } - else { - const toolName = args[1]; - let toolArgs = {}; - if (args.length > 2) { - try { - toolArgs = JSON.parse(args.slice(2).join(' ')); - } - catch (_b) { - console.log('Invalid JSON arguments. Using empty args.'); - } - } - await callTool(toolName, toolArgs); - } - break; - case 'greet': - await callGreetTool(args[1] || 'MCP User'); - break; - case 'multi-greet': - await callMultiGreetTool(args[1] || 'MCP User'); - break; - case 'collect-info': - await callCollectInfoTool(args[1] || 'contact'); - break; - case 'start-notifications': { - const interval = args[1] ? parseInt(args[1], 10) : 2000; - const count = args[2] ? parseInt(args[2], 10) : 10; - await startNotifications(interval, count); - break; - } - case 'run-notifications-tool-with-resumability': { - const interval = args[1] ? parseInt(args[1], 10) : 2000; - const count = args[2] ? parseInt(args[2], 10) : 10; - await runNotificationsToolWithResumability(interval, count); - break; - } - case 'list-prompts': - await listPrompts(); - break; - case 'get-prompt': - if (args.length < 2) { - console.log('Usage: get-prompt [args]'); - } - else { - const promptName = args[1]; - let promptArgs = {}; - if (args.length > 2) { - try { - promptArgs = JSON.parse(args.slice(2).join(' ')); - } - catch (_c) { - console.log('Invalid JSON arguments. Using empty args.'); - } - } - await getPrompt(promptName, promptArgs); - } - break; - case 'list-resources': - await listResources(); - break; - case 'read-resource': - if (args.length < 2) { - console.log('Usage: read-resource '); - } - else { - await readResource(args[1]); - } - break; - case 'help': - printHelp(); - break; - case 'quit': - case 'exit': - await cleanup(); - return; - default: - if (command) { - console.log(`Unknown command: ${command}`); - } - break; - } - } - catch (error) { - console.error(`Error executing command: ${error}`); - } - // Continue the command loop - commandLoop(); - }); -} -async function connect(url) { - if (client) { - console.log('Already connected. Disconnect first.'); - return; - } - if (url) { - serverUrl = url; - } - console.log(`Connecting to ${serverUrl}...`); - try { - // Create a new client with form elicitation capability - client = new index_js_1.Client({ - name: 'example-client', - version: '1.0.0' - }, { - capabilities: { - elicitation: { - form: {} - } - } - }); - client.onerror = error => { - console.error('\x1b[31mClient error:', error, '\x1b[0m'); - }; - // Set up elicitation request handler with proper validation - client.setRequestHandler(types_js_1.ElicitRequestSchema, async (request) => { - var _a; - if (request.params.mode !== 'form') { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Unsupported elicitation mode: ${request.params.mode}`); - } - console.log('\n🔔 Elicitation (form) Request Received:'); - console.log(`Message: ${request.params.message}`); - console.log('Requested Schema:'); - console.log(JSON.stringify(request.params.requestedSchema, null, 2)); - const schema = request.params.requestedSchema; - const properties = schema.properties; - const required = schema.required || []; - // Set up AJV validator for the requested schema - const ajv = new ajv_1.Ajv(); - const validate = ajv.compile(schema); - let attempts = 0; - const maxAttempts = 3; - while (attempts < maxAttempts) { - attempts++; - console.log(`\nPlease provide the following information (attempt ${attempts}/${maxAttempts}):`); - const content = {}; - let inputCancelled = false; - // Collect input for each field - for (const [fieldName, fieldSchema] of Object.entries(properties)) { - const field = fieldSchema; - const isRequired = required.includes(fieldName); - let prompt = `${field.title || fieldName}`; - // Add helpful information to the prompt - if (field.description) { - prompt += ` (${field.description})`; - } - if (field.enum) { - prompt += ` [options: ${field.enum.join(', ')}]`; - } - if (field.type === 'number' || field.type === 'integer') { - if (field.minimum !== undefined && field.maximum !== undefined) { - prompt += ` [${field.minimum}-${field.maximum}]`; - } - else if (field.minimum !== undefined) { - prompt += ` [min: ${field.minimum}]`; - } - else if (field.maximum !== undefined) { - prompt += ` [max: ${field.maximum}]`; - } - } - if (field.type === 'string' && field.format) { - prompt += ` [format: ${field.format}]`; - } - if (isRequired) { - prompt += ' *required*'; - } - if (field.default !== undefined) { - prompt += ` [default: ${field.default}]`; - } - prompt += ': '; - const answer = await new Promise(resolve => { - readline.question(prompt, input => { - resolve(input.trim()); - }); - }); - // Check for cancellation - if (answer.toLowerCase() === 'cancel' || answer.toLowerCase() === 'c') { - inputCancelled = true; - break; - } - // Parse and validate the input - try { - if (answer === '' && field.default !== undefined) { - content[fieldName] = field.default; - } - else if (answer === '' && !isRequired) { - // Skip optional empty fields - continue; - } - else if (answer === '') { - throw new Error(`${fieldName} is required`); - } - else { - // Parse the value based on type - let parsedValue; - if (field.type === 'boolean') { - parsedValue = answer.toLowerCase() === 'true' || answer.toLowerCase() === 'yes' || answer === '1'; - } - else if (field.type === 'number') { - parsedValue = parseFloat(answer); - if (isNaN(parsedValue)) { - throw new Error(`${fieldName} must be a valid number`); - } - } - else if (field.type === 'integer') { - parsedValue = parseInt(answer, 10); - if (isNaN(parsedValue)) { - throw new Error(`${fieldName} must be a valid integer`); - } - } - else if (field.enum) { - if (!field.enum.includes(answer)) { - throw new Error(`${fieldName} must be one of: ${field.enum.join(', ')}`); - } - parsedValue = answer; - } - else { - parsedValue = answer; - } - content[fieldName] = parsedValue; - } - } - catch (error) { - console.log(`❌ Error: ${error}`); - // Continue to next attempt - break; - } - } - if (inputCancelled) { - return { action: 'cancel' }; - } - // If we didn't complete all fields due to an error, try again - if (Object.keys(content).length !== - Object.keys(properties).filter(name => required.includes(name) || content[name] !== undefined).length) { - if (attempts < maxAttempts) { - console.log('Please try again...'); - continue; - } - else { - console.log('Maximum attempts reached. Declining request.'); - return { action: 'decline' }; - } - } - // Validate the complete object against the schema - const isValid = validate(content); - if (!isValid) { - console.log('❌ Validation errors:'); - (_a = validate.errors) === null || _a === void 0 ? void 0 : _a.forEach(error => { - console.log(` - ${error.instancePath || 'root'}: ${error.message}`); - }); - if (attempts < maxAttempts) { - console.log('Please correct the errors and try again...'); - continue; - } - else { - console.log('Maximum attempts reached. Declining request.'); - return { action: 'decline' }; - } - } - // Show the collected data and ask for confirmation - console.log('\n✅ Collected data:'); - console.log(JSON.stringify(content, null, 2)); - const confirmAnswer = await new Promise(resolve => { - readline.question('\nSubmit this information? (yes/no/cancel): ', input => { - resolve(input.trim().toLowerCase()); - }); - }); - if (confirmAnswer === 'yes' || confirmAnswer === 'y') { - return { - action: 'accept', - content - }; - } - else if (confirmAnswer === 'cancel' || confirmAnswer === 'c') { - return { action: 'cancel' }; - } - else if (confirmAnswer === 'no' || confirmAnswer === 'n') { - if (attempts < maxAttempts) { - console.log('Please re-enter the information...'); - continue; - } - else { - return { action: 'decline' }; - } - } - } - console.log('Maximum attempts reached. Declining request.'); - return { action: 'decline' }; - }); - transport = new streamableHttp_js_1.StreamableHTTPClientTransport(new URL(serverUrl), { - sessionId: sessionId - }); - // Set up notification handlers - client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => { - notificationCount++; - console.log(`\nNotification #${notificationCount}: ${notification.params.level} - ${notification.params.data}`); - // Re-display the prompt - process.stdout.write('> '); - }); - client.setNotificationHandler(types_js_1.ResourceListChangedNotificationSchema, async (_) => { - console.log(`\nResource list changed notification received!`); - try { - if (!client) { - console.log('Client disconnected, cannot fetch resources'); - return; - } - const resourcesResult = await client.request({ - method: 'resources/list', - params: {} - }, types_js_1.ListResourcesResultSchema); - console.log('Available resources count:', resourcesResult.resources.length); - } - catch (_a) { - console.log('Failed to list resources after change notification'); - } - // Re-display the prompt - process.stdout.write('> '); - }); - // Connect the client - await client.connect(transport); - sessionId = transport.sessionId; - console.log('Transport created with session ID:', sessionId); - console.log('Connected to MCP server'); - } - catch (error) { - console.error('Failed to connect:', error); - client = null; - transport = null; - } -} -async function disconnect() { - if (!client || !transport) { - console.log('Not connected.'); - return; - } - try { - await transport.close(); - console.log('Disconnected from MCP server'); - client = null; - transport = null; - } - catch (error) { - console.error('Error disconnecting:', error); - } -} -async function terminateSession() { - if (!client || !transport) { - console.log('Not connected.'); - return; - } - try { - console.log('Terminating session with ID:', transport.sessionId); - await transport.terminateSession(); - console.log('Session terminated successfully'); - // Check if sessionId was cleared after termination - if (!transport.sessionId) { - console.log('Session ID has been cleared'); - sessionId = undefined; - // Also close the transport and clear client objects - await transport.close(); - console.log('Transport closed after session termination'); - client = null; - transport = null; - } - else { - console.log('Server responded with 405 Method Not Allowed (session termination not supported)'); - console.log('Session ID is still active:', transport.sessionId); - } - } - catch (error) { - console.error('Error terminating session:', error); - } -} -async function reconnect() { - if (client) { - await disconnect(); - } - await connect(); -} -async function listTools() { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const toolsRequest = { - method: 'tools/list', - params: {} - }; - const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema); - console.log('Available tools:'); - if (toolsResult.tools.length === 0) { - console.log(' No tools available'); - } - else { - for (const tool of toolsResult.tools) { - console.log(` - id: ${tool.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(tool)}, description: ${tool.description}`); - } - } - } - catch (error) { - console.log(`Tools not supported by this server (${error})`); - } -} -async function callTool(name, args) { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const request = { - method: 'tools/call', - params: { - name, - arguments: args - } - }; - console.log(`Calling tool '${name}' with args:`, args); - const result = await client.request(request, types_js_1.CallToolResultSchema); - console.log('Tool result:'); - const resourceLinks = []; - result.content.forEach(item => { - if (item.type === 'text') { - console.log(` ${item.text}`); - } - else if (item.type === 'resource_link') { - const resourceLink = item; - resourceLinks.push(resourceLink); - console.log(` 📁 Resource Link: ${resourceLink.name}`); - console.log(` URI: ${resourceLink.uri}`); - if (resourceLink.mimeType) { - console.log(` Type: ${resourceLink.mimeType}`); - } - if (resourceLink.description) { - console.log(` Description: ${resourceLink.description}`); - } - } - else if (item.type === 'resource') { - console.log(` [Embedded Resource: ${item.resource.uri}]`); - } - else if (item.type === 'image') { - console.log(` [Image: ${item.mimeType}]`); - } - else if (item.type === 'audio') { - console.log(` [Audio: ${item.mimeType}]`); - } - else { - console.log(` [Unknown content type]:`, item); - } - }); - // Offer to read resource links - if (resourceLinks.length > 0) { - console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource ' to read their content.`); - } - } - catch (error) { - console.log(`Error calling tool ${name}: ${error}`); - } -} -async function callGreetTool(name) { - await callTool('greet', { name }); -} -async function callMultiGreetTool(name) { - console.log('Calling multi-greet tool with notifications...'); - await callTool('multi-greet', { name }); -} -async function callCollectInfoTool(infoType) { - console.log(`Testing form elicitation with collect-user-info tool (${infoType})...`); - await callTool('collect-user-info', { infoType }); -} -async function startNotifications(interval, count) { - console.log(`Starting notification stream: interval=${interval}ms, count=${count || 'unlimited'}`); - await callTool('start-notification-stream', { interval, count }); -} -async function runNotificationsToolWithResumability(interval, count) { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - console.log(`Starting notification stream with resumability: interval=${interval}ms, count=${count || 'unlimited'}`); - console.log(`Using resumption token: ${notificationsToolLastEventId || 'none'}`); - const request = { - method: 'tools/call', - params: { - name: 'start-notification-stream', - arguments: { interval, count } - } - }; - const onLastEventIdUpdate = (event) => { - notificationsToolLastEventId = event; - console.log(`Updated resumption token: ${event}`); - }; - const result = await client.request(request, types_js_1.CallToolResultSchema, { - resumptionToken: notificationsToolLastEventId, - onresumptiontoken: onLastEventIdUpdate - }); - console.log('Tool result:'); - result.content.forEach(item => { - if (item.type === 'text') { - console.log(` ${item.text}`); - } - else { - console.log(` ${item.type} content:`, item); - } - }); - } - catch (error) { - console.log(`Error starting notification stream: ${error}`); - } -} -async function listPrompts() { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const promptsRequest = { - method: 'prompts/list', - params: {} - }; - const promptsResult = await client.request(promptsRequest, types_js_1.ListPromptsResultSchema); - console.log('Available prompts:'); - if (promptsResult.prompts.length === 0) { - console.log(' No prompts available'); - } - else { - for (const prompt of promptsResult.prompts) { - console.log(` - id: ${prompt.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(prompt)}, description: ${prompt.description}`); - } - } - } - catch (error) { - console.log(`Prompts not supported by this server (${error})`); - } -} -async function getPrompt(name, args) { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const promptRequest = { - method: 'prompts/get', - params: { - name, - arguments: args - } - }; - const promptResult = await client.request(promptRequest, types_js_1.GetPromptResultSchema); - console.log('Prompt template:'); - promptResult.messages.forEach((msg, index) => { - console.log(` [${index + 1}] ${msg.role}: ${msg.content.type === 'text' ? msg.content.text : JSON.stringify(msg.content)}`); - }); - } - catch (error) { - console.log(`Error getting prompt ${name}: ${error}`); - } -} -async function listResources() { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const resourcesRequest = { - method: 'resources/list', - params: {} - }; - const resourcesResult = await client.request(resourcesRequest, types_js_1.ListResourcesResultSchema); - console.log('Available resources:'); - if (resourcesResult.resources.length === 0) { - console.log(' No resources available'); - } - else { - for (const resource of resourcesResult.resources) { - console.log(` - id: ${resource.name}, name: ${(0, metadataUtils_js_1.getDisplayName)(resource)}, description: ${resource.uri}`); - } - } - } - catch (error) { - console.log(`Resources not supported by this server (${error})`); - } -} -async function readResource(uri) { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const request = { - method: 'resources/read', - params: { uri } - }; - console.log(`Reading resource: ${uri}`); - const result = await client.request(request, types_js_1.ReadResourceResultSchema); - console.log('Resource contents:'); - for (const content of result.contents) { - console.log(` URI: ${content.uri}`); - if (content.mimeType) { - console.log(` Type: ${content.mimeType}`); - } - if ('text' in content && typeof content.text === 'string') { - console.log(' Content:'); - console.log(' ---'); - console.log(content.text - .split('\n') - .map((line) => ' ' + line) - .join('\n')); - console.log(' ---'); - } - else if ('blob' in content && typeof content.blob === 'string') { - console.log(` [Binary data: ${content.blob.length} bytes]`); - } - } - } - catch (error) { - console.log(`Error reading resource ${uri}: ${error}`); - } -} -async function cleanup() { - if (client && transport) { - try { - // First try to terminate the session gracefully - if (transport.sessionId) { - try { - console.log('Terminating session before exit...'); - await transport.terminateSession(); - console.log('Session terminated successfully'); - } - catch (error) { - console.error('Error terminating session:', error); - } - } - // Then close the transport - await transport.close(); - } - catch (error) { - console.error('Error closing transport:', error); - } - } - process.stdin.setRawMode(false); - readline.close(); - console.log('\nGoodbye!'); - process.exit(0); -} -// Set up raw mode for keyboard input to capture Escape key -process.stdin.setRawMode(true); -process.stdin.on('data', async (data) => { - // Check for Escape key (27) - if (data.length === 1 && data[0] === 27) { - console.log('\nESC key pressed. Disconnecting from server...'); - // Abort current operation and disconnect from server - if (client && transport) { - await disconnect(); - console.log('Disconnected. Press Enter to continue.'); - } - else { - console.log('Not connected to server.'); - } - // Re-display the prompt - process.stdout.write('> '); - } -}); -// Handle Ctrl+C -process.on('SIGINT', async () => { - console.log('\nReceived SIGINT. Cleaning up...'); - await cleanup(); -}); -// Start the interactive client -main().catch((error) => { - console.error('Error running MCP client:', error); - process.exit(1); -}); -//# sourceMappingURL=simpleStreamableHttp.js.map \ No newline at end of file diff --git a/dist/cjs/examples/client/simpleStreamableHttp.js.map b/dist/cjs/examples/client/simpleStreamableHttp.js.map deleted file mode 100644 index 699665c84d..0000000000 --- a/dist/cjs/examples/client/simpleStreamableHttp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleStreamableHttp.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,sEAA+E;AAC/E,iDAAgD;AAChD,6CAmBwB;AACxB,oEAA+D;AAC/D,6BAA0B;AAE1B,2CAA2C;AAC3C,MAAM,QAAQ,GAAG,IAAA,+BAAe,EAAC;IAC7B,KAAK,EAAE,OAAO,CAAC,KAAK;IACpB,MAAM,EAAE,OAAO,CAAC,MAAM;CACzB,CAAC,CAAC;AAEH,0DAA0D;AAC1D,IAAI,iBAAiB,GAAG,CAAC,CAAC;AAE1B,uDAAuD;AACvD,IAAI,MAAM,GAAkB,IAAI,CAAC;AACjC,IAAI,SAAS,GAAyC,IAAI,CAAC;AAC3D,IAAI,SAAS,GAAG,2BAA2B,CAAC;AAC5C,IAAI,4BAA4B,GAAuB,SAAS,CAAC;AACjE,IAAI,SAAS,GAAuB,SAAS,CAAC;AAE9C,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC;IACtC,OAAO,CAAC,GAAG,CAAC,uBAAuB,CAAC,CAAC;IAErC,sDAAsD;IACtD,MAAM,OAAO,EAAE,CAAC;IAEhB,wCAAwC;IACxC,SAAS,EAAE,CAAC;IACZ,WAAW,EAAE,CAAC;AAClB,CAAC;AAED,SAAS,SAAS;IACd,OAAO,CAAC,GAAG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,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAC/B,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,EAAC,IAAI,EAAC,EAAE;IAClC,4BAA4B;IAC5B,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;QACtC,OAAO,CAAC,GAAG,CAAC,iDAAiD,CAAC,CAAC;QAE/D,qDAAqD;QACrD,IAAI,MAAM,IAAI,SAAS,EAAE,CAAC;YACtB,MAAM,UAAU,EAAE,CAAC;YACnB,OAAO,CAAC,GAAG,CAAC,wCAAwC,CAAC,CAAC;QAC1D,CAAC;aAAM,CAAC;YACJ,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;QAC5C,CAAC;QAED,wBAAwB;QACxB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,gBAAgB;AAChB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;IACjD,MAAM,OAAO,EAAE,CAAC;AACpB,CAAC,CAAC,CAAC;AAEH,+BAA+B;AAC/B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts b/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts deleted file mode 100644 index c2679e6694..0000000000 --- a/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=streamableHttpWithSseFallbackClient.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts.map b/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts.map deleted file mode 100644 index b79ae2a72c..0000000000 --- a/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"streamableHttpWithSseFallbackClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/streamableHttpWithSseFallbackClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js b/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js deleted file mode 100644 index bf3e9a885c..0000000000 --- a/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js +++ /dev/null @@ -1,168 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -const index_js_1 = require("../../client/index.js"); -const streamableHttp_js_1 = require("../../client/streamableHttp.js"); -const sse_js_1 = require("../../client/sse.js"); -const types_js_1 = require("../../types.js"); -/** - * Simplified Backwards Compatible MCP Client - * - * This client demonstrates backward compatibility with both: - * 1. Modern servers using Streamable HTTP transport (protocol version 2025-03-26) - * 2. Older servers using HTTP+SSE transport (protocol version 2024-11-05) - * - * Following the MCP specification for backwards compatibility: - * - Attempts to POST an initialize request to the server URL first (modern transport) - * - If that fails with 4xx status, falls back to GET request for SSE stream (older transport) - */ -// Command line args processing -const args = process.argv.slice(2); -const serverUrl = args[0] || 'http://localhost:3000/mcp'; -async function main() { - console.log('MCP Backwards Compatible Client'); - console.log('==============================='); - console.log(`Connecting to server at: ${serverUrl}`); - let client; - let transport; - try { - // Try connecting with automatic transport detection - const connection = await connectWithBackwardsCompatibility(serverUrl); - client = connection.client; - transport = connection.transport; - // Set up notification handler - client.setNotificationHandler(types_js_1.LoggingMessageNotificationSchema, notification => { - console.log(`Notification: ${notification.params.level} - ${notification.params.data}`); - }); - // DEMO WORKFLOW: - // 1. List available tools - console.log('\n=== Listing Available Tools ==='); - await listTools(client); - // 2. Call the notification tool - console.log('\n=== Starting Notification Stream ==='); - await startNotificationTool(client); - // 3. Wait for all notifications (5 seconds) - console.log('\n=== Waiting for all notifications ==='); - await new Promise(resolve => setTimeout(resolve, 5000)); - // 4. Disconnect - console.log('\n=== Disconnecting ==='); - await transport.close(); - console.log('Disconnected from MCP server'); - } - catch (error) { - console.error('Error running client:', error); - process.exit(1); - } -} -/** - * Connect to an MCP server with backwards compatibility - * Following the spec for client backward compatibility - */ -async function connectWithBackwardsCompatibility(url) { - console.log('1. Trying Streamable HTTP transport first...'); - // Step 1: Try Streamable HTTP transport first - const client = new index_js_1.Client({ - name: 'backwards-compatible-client', - version: '1.0.0' - }); - client.onerror = error => { - console.error('Client error:', error); - }; - const baseUrl = new URL(url); - try { - // Create modern transport - const streamableTransport = new streamableHttp_js_1.StreamableHTTPClientTransport(baseUrl); - await client.connect(streamableTransport); - console.log('Successfully connected using modern Streamable HTTP transport.'); - return { - client, - transport: streamableTransport, - transportType: 'streamable-http' - }; - } - catch (error) { - // Step 2: If transport fails, try the older SSE transport - console.log(`StreamableHttp transport connection failed: ${error}`); - console.log('2. Falling back to deprecated HTTP+SSE transport...'); - try { - // Create SSE transport pointing to /sse endpoint - const sseTransport = new sse_js_1.SSEClientTransport(baseUrl); - const sseClient = new index_js_1.Client({ - name: 'backwards-compatible-client', - version: '1.0.0' - }); - await sseClient.connect(sseTransport); - console.log('Successfully connected using deprecated HTTP+SSE transport.'); - return { - client: sseClient, - transport: sseTransport, - transportType: 'sse' - }; - } - catch (sseError) { - console.error(`Failed to connect with either transport method:\n1. Streamable HTTP error: ${error}\n2. SSE error: ${sseError}`); - throw new Error('Could not connect to server with any available transport'); - } - } -} -/** - * List available tools on the server - */ -async function listTools(client) { - try { - const toolsRequest = { - method: 'tools/list', - params: {} - }; - const toolsResult = await client.request(toolsRequest, types_js_1.ListToolsResultSchema); - console.log('Available tools:'); - if (toolsResult.tools.length === 0) { - console.log(' No tools available'); - } - else { - for (const tool of toolsResult.tools) { - console.log(` - ${tool.name}: ${tool.description}`); - } - } - } - catch (error) { - console.log(`Tools not supported by this server: ${error}`); - } -} -/** - * Start a notification stream by calling the notification tool - */ -async function startNotificationTool(client) { - try { - // Call the notification tool using reasonable defaults - const request = { - method: 'tools/call', - params: { - name: 'start-notification-stream', - arguments: { - interval: 1000, // 1 second between notifications - count: 5 // Send 5 notifications - } - } - }; - console.log('Calling notification tool...'); - const result = await client.request(request, types_js_1.CallToolResultSchema); - console.log('Tool result:'); - result.content.forEach(item => { - if (item.type === 'text') { - console.log(` ${item.text}`); - } - else { - console.log(` ${item.type} content:`, item); - } - }); - } - catch (error) { - console.log(`Error calling notification tool: ${error}`); - } -} -// Start the client -main().catch((error) => { - console.error('Error running MCP client:', error); - process.exit(1); -}); -//# sourceMappingURL=streamableHttpWithSseFallbackClient.js.map \ No newline at end of file diff --git a/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js.map b/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js.map deleted file mode 100644 index f3bec99c5f..0000000000 --- a/dist/cjs/examples/client/streamableHttpWithSseFallbackClient.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"streamableHttpWithSseFallbackClient.js","sourceRoot":"","sources":["../../../../src/examples/client/streamableHttpWithSseFallbackClient.ts"],"names":[],"mappings":";;AAAA,oDAA+C;AAC/C,sEAA+E;AAC/E,gDAAyD;AACzD,6CAMwB;AAExB;;;;;;;;;;GAUG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AAEzD,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,C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ACjC,SAAS,EAAE;oBACP,QAAQ,EAAE,IAAI,EAAE,iCAAiC;oBACjD,KAAK,EAAE,CAAC,CAAC,uBAAuB;iBACnC;aACJ;SACJ,CAAC;QAEF,OAAO,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC;QAC5C,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,+BAAoB,CAAC,CAAC;QAEnE,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC;QAC5B,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;YAC1B,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gBACvB,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;YAClC,CAAC;iBAAM,CAAC;gBACJ,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,WAAW,EAAE,IAAI,CAAC,CAAC;YACjD,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,GAAG,CAAC,oCAAoC,KAAK,EAAE,CAAC,CAAC;IAC7D,CAAC;AACL,CAAC;AAED,mBAAmB;AACnB,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts b/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts deleted file mode 100644 index 218aeac8b2..0000000000 --- a/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { AuthorizationParams, OAuthServerProvider } from '../../server/auth/provider.js'; -import { OAuthRegisteredClientsStore } from '../../server/auth/clients.js'; -import { OAuthClientInformationFull, OAuthMetadata, OAuthTokens } from '../../shared/auth.js'; -import { Response } from 'express'; -import { AuthInfo } from '../../server/auth/types.js'; -export declare class DemoInMemoryClientsStore implements OAuthRegisteredClientsStore { - private clients; - getClient(clientId: string): Promise<{ - redirect_uris: string[]; - client_id: string; - token_endpoint_auth_method?: string | undefined; - grant_types?: string[] | undefined; - response_types?: string[] | undefined; - client_name?: string | undefined; - client_uri?: string | undefined; - logo_uri?: string | undefined; - scope?: string | undefined; - contacts?: string[] | undefined; - tos_uri?: string | undefined; - policy_uri?: string | undefined; - jwks_uri?: string | undefined; - jwks?: any; - software_id?: string | undefined; - software_version?: string | undefined; - software_statement?: string | undefined; - client_secret?: string | undefined; - client_id_issued_at?: number | undefined; - client_secret_expires_at?: number | undefined; - } | undefined>; - registerClient(clientMetadata: OAuthClientInformationFull): Promise<{ - redirect_uris: string[]; - client_id: string; - token_endpoint_auth_method?: string | undefined; - grant_types?: string[] | undefined; - response_types?: string[] | undefined; - client_name?: string | undefined; - client_uri?: string | undefined; - logo_uri?: string | undefined; - scope?: string | undefined; - contacts?: string[] | undefined; - tos_uri?: string | undefined; - policy_uri?: string | undefined; - jwks_uri?: string | undefined; - jwks?: any; - software_id?: string | undefined; - software_version?: string | undefined; - software_statement?: string | undefined; - client_secret?: string | undefined; - client_id_issued_at?: number | undefined; - client_secret_expires_at?: number | undefined; - }>; -} -/** - * 🚨 DEMO ONLY - NOT FOR PRODUCTION - * - * This example demonstrates MCP OAuth flow but lacks some of the features required for production use, - * for example: - * - Persistent token storage - * - Rate limiting - */ -export declare class DemoInMemoryAuthProvider implements OAuthServerProvider { - private validateResource?; - clientsStore: DemoInMemoryClientsStore; - private codes; - private tokens; - constructor(validateResource?: ((resource?: URL) => boolean) | undefined); - authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; - challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise; - exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, _codeVerifier?: string): Promise; - exchangeRefreshToken(_client: OAuthClientInformationFull, _refreshToken: string, _scopes?: string[], _resource?: URL): Promise; - verifyAccessToken(token: string): Promise; -} -export declare const setupAuthServer: ({ authServerUrl, mcpServerUrl, strictResource }: { - authServerUrl: URL; - mcpServerUrl: URL; - strictResource: boolean; -}) => OAuthMetadata; -//# sourceMappingURL=demoInMemoryOAuthProvider.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts.map b/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts.map deleted file mode 100644 index 8a4a43fe8d..0000000000 --- a/dist/cjs/examples/server/demoInMemoryOAuthProvider.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"demoInMemoryOAuthProvider.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/demoInMemoryOAuthProvider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACzF,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAgB,EAAW,QAAQ,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAKtD,qBAAa,wBAAyB,YAAW,2BAA2B;IACxE,OAAO,CAAC,OAAO,CAAiD;IAE1D,SAAS,CAAC,QAAQ,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;IAI1B,cAAc,CAAC,cAAc,EAAE,0BAA0B;;;;;;;;;;;;;;;;;;;;;;CAIlE;AAED;;;;;;;GAOG;AACH,qBAAa,wBAAyB,YAAW,mBAAmB;IAWpD,OAAO,CAAC,gBAAgB,CAAC;IAVrC,YAAY,2BAAkC;IAC9C,OAAO,CAAC,KAAK,CAMT;IACJ,OAAO,CAAC,MAAM,CAA+B;gBAEzB,gBAAgB,CAAC,GAAE,CAAC,QAAQ,CAAC,EAAE,GAAG,KAAK,OAAO,aAAA;IAE5D,SAAS,CAAC,MAAM,EAAE,0BAA0B,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAwCxG,6BAA6B,CAAC,MAAM,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAU7G,yBAAyB,CAC3B,MAAM,EAAE,0BAA0B,EAClC,iBAAiB,EAAE,MAAM,EAGzB,aAAa,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,WAAW,CAAC;IAoCjB,oBAAoB,CACtB,OAAO,EAAE,0BAA0B,EACnC,aAAa,EAAE,MAAM,EACrB,OAAO,CAAC,EAAE,MAAM,EAAE,EAClB,SAAS,CAAC,EAAE,GAAG,GAChB,OAAO,CAAC,WAAW,CAAC;IAIjB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;CAc5D;AAED,eAAO,MAAM,eAAe,oDAIzB;IACC,aAAa,EAAE,GAAG,CAAC;IACnB,YAAY,EAAE,GAAG,CAAC;IAClB,cAAc,EAAE,OAAO,CAAC;CAC3B,KAAG,aA+EH,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/demoInMemoryOAuthProvider.js b/dist/cjs/examples/server/demoInMemoryOAuthProvider.js deleted file mode 100644 index c439a34039..0000000000 --- a/dist/cjs/examples/server/demoInMemoryOAuthProvider.js +++ /dev/null @@ -1,205 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.setupAuthServer = exports.DemoInMemoryAuthProvider = exports.DemoInMemoryClientsStore = void 0; -const node_crypto_1 = require("node:crypto"); -const express_1 = __importDefault(require("express")); -const router_js_1 = require("../../server/auth/router.js"); -const auth_utils_js_1 = require("../../shared/auth-utils.js"); -const errors_js_1 = require("../../server/auth/errors.js"); -class DemoInMemoryClientsStore { - constructor() { - this.clients = new Map(); - } - async getClient(clientId) { - return this.clients.get(clientId); - } - async registerClient(clientMetadata) { - this.clients.set(clientMetadata.client_id, clientMetadata); - return clientMetadata; - } -} -exports.DemoInMemoryClientsStore = DemoInMemoryClientsStore; -/** - * 🚨 DEMO ONLY - NOT FOR PRODUCTION - * - * This example demonstrates MCP OAuth flow but lacks some of the features required for production use, - * for example: - * - Persistent token storage - * - Rate limiting - */ -class DemoInMemoryAuthProvider { - constructor(validateResource) { - this.validateResource = validateResource; - this.clientsStore = new DemoInMemoryClientsStore(); - this.codes = new Map(); - this.tokens = new Map(); - } - async authorize(client, params, res) { - const code = (0, node_crypto_1.randomUUID)(); - const searchParams = new URLSearchParams({ - code - }); - if (params.state !== undefined) { - searchParams.set('state', params.state); - } - this.codes.set(code, { - client, - params - }); - // Simulate a user login - // Set a secure HTTP-only session cookie with authorization info - if (res.cookie) { - const authCookieData = { - userId: 'demo_user', - name: 'Demo User', - timestamp: Date.now() - }; - res.cookie('demo_session', JSON.stringify(authCookieData), { - httpOnly: true, - secure: false, // In production, this should be true - sameSite: 'lax', - maxAge: 24 * 60 * 60 * 1000, // 24 hours - for demo purposes - path: '/' // Available to all routes - }); - } - if (!client.redirect_uris.includes(params.redirectUri)) { - throw new errors_js_1.InvalidRequestError('Unregistered redirect_uri'); - } - const targetUrl = new URL(params.redirectUri); - targetUrl.search = searchParams.toString(); - res.redirect(targetUrl.toString()); - } - async challengeForAuthorizationCode(client, authorizationCode) { - // Store the challenge with the code data - const codeData = this.codes.get(authorizationCode); - if (!codeData) { - throw new Error('Invalid authorization code'); - } - return codeData.params.codeChallenge; - } - async exchangeAuthorizationCode(client, authorizationCode, - // Note: code verifier is checked in token.ts by default - // it's unused here for that reason. - _codeVerifier) { - const codeData = this.codes.get(authorizationCode); - if (!codeData) { - throw new Error('Invalid authorization code'); - } - if (codeData.client.client_id !== client.client_id) { - throw new Error(`Authorization code was not issued to this client, ${codeData.client.client_id} != ${client.client_id}`); - } - if (this.validateResource && !this.validateResource(codeData.params.resource)) { - throw new Error(`Invalid resource: ${codeData.params.resource}`); - } - this.codes.delete(authorizationCode); - const token = (0, node_crypto_1.randomUUID)(); - const tokenData = { - token, - clientId: client.client_id, - scopes: codeData.params.scopes || [], - expiresAt: Date.now() + 3600000, // 1 hour - resource: codeData.params.resource, - type: 'access' - }; - this.tokens.set(token, tokenData); - return { - access_token: token, - token_type: 'bearer', - expires_in: 3600, - scope: (codeData.params.scopes || []).join(' ') - }; - } - async exchangeRefreshToken(_client, _refreshToken, _scopes, _resource) { - throw new Error('Not implemented for example demo'); - } - async verifyAccessToken(token) { - const tokenData = this.tokens.get(token); - if (!tokenData || !tokenData.expiresAt || tokenData.expiresAt < Date.now()) { - throw new Error('Invalid or expired token'); - } - return { - token, - clientId: tokenData.clientId, - scopes: tokenData.scopes, - expiresAt: Math.floor(tokenData.expiresAt / 1000), - resource: tokenData.resource - }; - } -} -exports.DemoInMemoryAuthProvider = DemoInMemoryAuthProvider; -const setupAuthServer = ({ authServerUrl, mcpServerUrl, strictResource }) => { - // Create separate auth server app - // NOTE: This is a separate app on a separate port to illustrate - // how to separate an OAuth Authorization Server from a Resource - // server in the SDK. The SDK is not intended to be provide a standalone - // authorization server. - const validateResource = strictResource - ? (resource) => { - if (!resource) - return false; - const expectedResource = (0, auth_utils_js_1.resourceUrlFromServerUrl)(mcpServerUrl); - return resource.toString() === expectedResource.toString(); - } - : undefined; - const provider = new DemoInMemoryAuthProvider(validateResource); - const authApp = (0, express_1.default)(); - authApp.use(express_1.default.json()); - // For introspection requests - authApp.use(express_1.default.urlencoded()); - // Add OAuth routes to the auth server - // NOTE: this will also add a protected resource metadata route, - // but it won't be used, so leave it. - authApp.use((0, router_js_1.mcpAuthRouter)({ - provider, - issuerUrl: authServerUrl, - scopesSupported: ['mcp:tools'] - })); - authApp.post('/introspect', async (req, res) => { - try { - const { token } = req.body; - if (!token) { - res.status(400).json({ error: 'Token is required' }); - return; - } - const tokenInfo = await provider.verifyAccessToken(token); - res.json({ - active: true, - client_id: tokenInfo.clientId, - scope: tokenInfo.scopes.join(' '), - exp: tokenInfo.expiresAt, - aud: tokenInfo.resource - }); - return; - } - catch (error) { - res.status(401).json({ - active: false, - error: 'Unauthorized', - error_description: `Invalid token: ${error}` - }); - } - }); - const auth_port = authServerUrl.port; - // Start the auth server - authApp.listen(auth_port, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`OAuth Authorization Server listening on port ${auth_port}`); - }); - // Note: we could fetch this from the server, but then we end up - // with some top level async which gets annoying. - const oauthMetadata = (0, router_js_1.createOAuthMetadata)({ - provider, - issuerUrl: authServerUrl, - scopesSupported: ['mcp:tools'] - }); - oauthMetadata.introspection_endpoint = new URL('/introspect', authServerUrl).href; - return oauthMetadata; -}; -exports.setupAuthServer = setupAuthServer; -//# sourceMappingURL=demoInMemoryOAuthProvider.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/demoInMemoryOAuthProvider.js.map b/dist/cjs/examples/server/demoInMemoryOAuthProvider.js.map deleted file mode 100644 index e19a20db90..0000000000 --- a/dist/cjs/examples/server/demoInMemoryOAuthProvider.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"demoInMemoryOAuthProvider.js","sourceRoot":"","sources":["../../../../src/examples/server/demoInMemoryOAuthProvider.ts"],"names":[],"mappings":";;;;;;AAAA,6CAAyC;AAIzC,sDAAqD;AAErD,2DAAiF;AACjF,8DAAsE;AACtE,2DAAkE;AAElE,MAAa,wBAAwB;IAArC;QACY,YAAO,GAAG,IAAI,GAAG,EAAsC,CAAC;IAUpE,CAAC;IARG,KAAK,CAAC,SAAS,CAAC,QAAgB;QAC5B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,C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,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;YAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACpB,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,gDAAgD,SAAS,EAAE,CAAC,CAAC;IAC7E,CAAC,CAAC,CAAC;IAEH,gEAAgE;IAChE,iDAAiD;IACjD,MAAM,aAAa,GAAkB,IAAA,+BAAmB,EAAC;QACrD,QAAQ;QACR,SAAS,EAAE,aAAa;QACxB,eAAe,EAAE,CAAC,WAAW,CAAC;KACjC,CAAC,CAAC;IAEH,aAAa,CAAC,sBAAsB,GAAG,IAAI,GAAG,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC,IAAI,CAAC;IAElF,OAAO,aAAa,CAAC;AACzB,CAAC,CAAC;AAvFW,QAAA,eAAe,mBAuF1B"} \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationFormExample.d.ts b/dist/cjs/examples/server/elicitationFormExample.d.ts deleted file mode 100644 index e4b736e0f2..0000000000 --- a/dist/cjs/examples/server/elicitationFormExample.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=elicitationFormExample.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationFormExample.d.ts.map b/dist/cjs/examples/server/elicitationFormExample.d.ts.map deleted file mode 100644 index c569df428d..0000000000 --- a/dist/cjs/examples/server/elicitationFormExample.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"elicitationFormExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/elicitationFormExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationFormExample.js b/dist/cjs/examples/server/elicitationFormExample.js deleted file mode 100644 index e25ac92059..0000000000 --- a/dist/cjs/examples/server/elicitationFormExample.js +++ /dev/null @@ -1,441 +0,0 @@ -"use strict"; -// Run with: npx tsx src/examples/server/elicitationFormExample.ts -// -// This example demonstrates how to use form elicitation to collect structured user input -// with JSON Schema validation via a local HTTP server with SSE streaming. -// Form elicitation allows servers to request *non-sensitive* user input through the client -// with schema-based validation. -// Note: See also elicitationUrlExample.ts for an example of using URL elicitation -// to collect *sensitive* user input via a browser. -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const node_crypto_1 = require("node:crypto"); -const cors_1 = __importDefault(require("cors")); -const express_1 = __importDefault(require("express")); -const mcp_js_1 = require("../../server/mcp.js"); -const streamableHttp_js_1 = require("../../server/streamableHttp.js"); -const types_js_1 = require("../../types.js"); -// Create MCP server - it will automatically use AjvJsonSchemaValidator with sensible defaults -// The validator supports format validation (email, date, etc.) if ajv-formats is installed -const mcpServer = new mcp_js_1.McpServer({ - name: 'form-elicitation-example-server', - version: '1.0.0' -}, { - capabilities: {} -}); -/** - * Example 1: Simple user registration tool - * Collects username, email, and password from the user - */ -mcpServer.registerTool('register_user', { - description: 'Register a new user account by collecting their information', - inputSchema: {} -}, async () => { - try { - // Request user information through form elicitation - const result = await mcpServer.server.elicitInput({ - mode: 'form', - message: 'Please provide your registration information:', - requestedSchema: { - type: 'object', - properties: { - username: { - type: 'string', - title: 'Username', - description: 'Your desired username (3-20 characters)', - minLength: 3, - maxLength: 20 - }, - email: { - type: 'string', - title: 'Email', - description: 'Your email address', - format: 'email' - }, - password: { - type: 'string', - title: 'Password', - description: 'Your password (min 8 characters)', - minLength: 8 - }, - newsletter: { - type: 'boolean', - title: 'Newsletter', - description: 'Subscribe to newsletter?', - default: false - } - }, - required: ['username', 'email', 'password'] - } - }); - // Handle the different possible actions - if (result.action === 'accept' && result.content) { - const { username, email, newsletter } = result.content; - return { - content: [ - { - type: 'text', - text: `Registration successful!\n\nUsername: ${username}\nEmail: ${email}\nNewsletter: ${newsletter ? 'Yes' : 'No'}` - } - ] - }; - } - else if (result.action === 'decline') { - return { - content: [ - { - type: 'text', - text: 'Registration cancelled by user.' - } - ] - }; - } - else { - return { - content: [ - { - type: 'text', - text: 'Registration was cancelled.' - } - ] - }; - } - } - catch (error) { - return { - content: [ - { - type: 'text', - text: `Registration failed: ${error instanceof Error ? error.message : String(error)}` - } - ], - isError: true - }; - } -}); -/** - * Example 2: Multi-step workflow with multiple form elicitation requests - * Demonstrates how to collect information in multiple steps - */ -mcpServer.registerTool('create_event', { - description: 'Create a calendar event by collecting event details', - inputSchema: {} -}, async () => { - try { - // Step 1: Collect basic event information - const basicInfo = await mcpServer.server.elicitInput({ - mode: 'form', - message: 'Step 1: Enter basic event information', - requestedSchema: { - type: 'object', - properties: { - title: { - type: 'string', - title: 'Event Title', - description: 'Name of the event', - minLength: 1 - }, - description: { - type: 'string', - title: 'Description', - description: 'Event description (optional)' - } - }, - required: ['title'] - } - }); - if (basicInfo.action !== 'accept' || !basicInfo.content) { - return { - content: [{ type: 'text', text: 'Event creation cancelled.' }] - }; - } - // Step 2: Collect date and time - const dateTime = await mcpServer.server.elicitInput({ - mode: 'form', - message: 'Step 2: Enter date and time', - requestedSchema: { - type: 'object', - properties: { - date: { - type: 'string', - title: 'Date', - description: 'Event date', - format: 'date' - }, - startTime: { - type: 'string', - title: 'Start Time', - description: 'Event start time (HH:MM)' - }, - duration: { - type: 'integer', - title: 'Duration', - description: 'Duration in minutes', - minimum: 15, - maximum: 480 - } - }, - required: ['date', 'startTime', 'duration'] - } - }); - if (dateTime.action !== 'accept' || !dateTime.content) { - return { - content: [{ type: 'text', text: 'Event creation cancelled.' }] - }; - } - // Combine all collected information - const event = { - ...basicInfo.content, - ...dateTime.content - }; - return { - content: [ - { - type: 'text', - text: `Event created successfully!\n\n${JSON.stringify(event, null, 2)}` - } - ] - }; - } - catch (error) { - return { - content: [ - { - type: 'text', - text: `Event creation failed: ${error instanceof Error ? error.message : String(error)}` - } - ], - isError: true - }; - } -}); -/** - * Example 3: Collecting address information - * Demonstrates validation with patterns and optional fields - */ -mcpServer.registerTool('update_shipping_address', { - description: 'Update shipping address with validation', - inputSchema: {} -}, async () => { - try { - const result = await mcpServer.server.elicitInput({ - mode: 'form', - message: 'Please provide your shipping address:', - requestedSchema: { - type: 'object', - properties: { - name: { - type: 'string', - title: 'Full Name', - description: 'Recipient name', - minLength: 1 - }, - street: { - type: 'string', - title: 'Street Address', - minLength: 1 - }, - city: { - type: 'string', - title: 'City', - minLength: 1 - }, - state: { - type: 'string', - title: 'State/Province', - minLength: 2, - maxLength: 2 - }, - zipCode: { - type: 'string', - title: 'ZIP/Postal Code', - description: '5-digit ZIP code' - }, - phone: { - type: 'string', - title: 'Phone Number (optional)', - description: 'Contact phone number' - } - }, - required: ['name', 'street', 'city', 'state', 'zipCode'] - } - }); - if (result.action === 'accept' && result.content) { - return { - content: [ - { - type: 'text', - text: `Address updated successfully!\n\n${JSON.stringify(result.content, null, 2)}` - } - ] - }; - } - else if (result.action === 'decline') { - return { - content: [{ type: 'text', text: 'Address update cancelled by user.' }] - }; - } - else { - return { - content: [{ type: 'text', text: 'Address update was cancelled.' }] - }; - } - } - catch (error) { - return { - content: [ - { - type: 'text', - text: `Address update failed: ${error instanceof Error ? error.message : String(error)}` - } - ], - isError: true - }; - } -}); -async function main() { - const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000; - const app = (0, express_1.default)(); - app.use(express_1.default.json()); - // Allow CORS for all domains, expose the Mcp-Session-Id header - app.use((0, cors_1.default)({ - origin: '*', - exposedHeaders: ['Mcp-Session-Id'] - })); - // Map to store transports by session ID - const transports = {}; - // MCP POST endpoint - const mcpPostHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (sessionId) { - console.log(`Received MCP request for session: ${sessionId}`); - } - try { - let transport; - if (sessionId && transports[sessionId]) { - // Reuse existing transport for this session - transport = transports[sessionId]; - } - else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) { - // New initialization request - create new transport - transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ - sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - console.log(`Session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - } - }); - // Set up onclose handler to clean up transport when closed - transport.onclose = () => { - const sid = transport.sessionId; - if (sid && transports[sid]) { - console.log(`Transport closed for session ${sid}, removing from transports map`); - delete transports[sid]; - } - }; - // Connect the transport to the MCP server BEFORE handling the request - await mcpServer.connect(transport); - await transport.handleRequest(req, res, req.body); - return; - } - else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - // Handle the request with existing transport - await transport.handleRequest(req, res, req.body); - } - catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } - }; - app.post('/mcp', mcpPostHandler); - // Handle GET requests for SSE streams - const mcpGetHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - console.log(`Establishing SSE stream for session ${sessionId}`); - const transport = transports[sessionId]; - await transport.handleRequest(req, res); - }; - app.get('/mcp', mcpGetHandler); - // Handle DELETE requests for session termination - const mcpDeleteHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - console.log(`Received session termination request for session ${sessionId}`); - try { - const transport = transports[sessionId]; - await transport.handleRequest(req, res); - } - catch (error) { - console.error('Error handling session termination:', error); - if (!res.headersSent) { - res.status(500).send('Error processing session termination'); - } - } - }; - app.delete('/mcp', mcpDeleteHandler); - // Start listening - app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`Form elicitation example server is running on http://localhost:${PORT}/mcp`); - console.log('Available tools:'); - console.log(' - register_user: Collect user registration information'); - console.log(' - create_event: Multi-step event creation'); - console.log(' - update_shipping_address: Collect and validate address'); - console.log('\nConnect your MCP client to this server using the HTTP transport.'); - }); - // Handle server shutdown - process.on('SIGINT', async () => { - console.log('Shutting down server...'); - // Close all active transports to properly clean up resources - for (const sessionId in transports) { - try { - console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId].close(); - delete transports[sessionId]; - } - catch (error) { - console.error(`Error closing transport for session ${sessionId}:`, error); - } - } - console.log('Server shutdown complete'); - process.exit(0); - }); -} -main().catch(error => { - console.error('Server error:', error); - process.exit(1); -}); -//# sourceMappingURL=elicitationFormExample.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationFormExample.js.map b/dist/cjs/examples/server/elicitationFormExample.js.map deleted file mode 100644 index fc5ebcd472..0000000000 --- a/dist/cjs/examples/server/elicitationFormExample.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"elicitationFormExample.js","sourceRoot":"","sources":["../../../../src/examples/server/elicitationFormExample.ts"],"names":[],"mappings":";AAAA,kEAAkE;AAClE,EAAE;AACF,yFAAyF;AACzF,0EAA0E;AAC1E,2FAA2F;AAC3F,gCAAgC;AAChC,kFAAkF;AAClF,mDAAmD;;;;;AAEnD,6CAAyC;AACzC,gDAAwB;AACxB,sDAA+D;AAC/D,gDAAgD;AAChD,sEAA+E;AAC/E,6CAAqD;AAErD,8FAA8F;AAC9F,2FAA2F;AAC3F,MAAM,SAAS,GAAG,IAAI,kBAAS,CAC3B;IACI,IAAI,EAAE,iCAAiC;IACvC,OAAO,EAAE,OAAO;CACnB,EACD;IACI,YAAY,EAAE,EAAE;CACnB,CACJ,CAAC;AAEF;;;GAGG;AACH,SAAS,CAAC,YAAY,CAClB,eAAe,EACf;IACI,WAAW,EAAE,6DAA6D;IAC1E,WAAW,EAAE,EAAE;CAClB,EACD,KAAK,IAAI,EAAE;IACP,IAAI,CAAC;QACD,oDAAoD;QACpD,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,MAAM,CAAC,WAAW,CAAC;YAC9C,IAAI,EA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AS,CAAC,CAAC,KAAK,EAAE,CAAC;gBACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;YACjC,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;YAC9E,CAAC;QACL,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;QACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationUrlExample.d.ts b/dist/cjs/examples/server/elicitationUrlExample.d.ts deleted file mode 100644 index 611f6eba22..0000000000 --- a/dist/cjs/examples/server/elicitationUrlExample.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=elicitationUrlExample.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationUrlExample.d.ts.map b/dist/cjs/examples/server/elicitationUrlExample.d.ts.map deleted file mode 100644 index 04acd6664d..0000000000 --- a/dist/cjs/examples/server/elicitationUrlExample.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"elicitationUrlExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/elicitationUrlExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationUrlExample.js b/dist/cjs/examples/server/elicitationUrlExample.js deleted file mode 100644 index e828ccae4f..0000000000 --- a/dist/cjs/examples/server/elicitationUrlExample.js +++ /dev/null @@ -1,655 +0,0 @@ -"use strict"; -// Run with: npx tsx src/examples/server/elicitationUrlExample.ts -// -// This example demonstrates how to use URL elicitation to securely collect -// *sensitive* user input in a remote (HTTP) server. -// URL elicitation allows servers to prompt the end-user to open a URL in their browser -// to collect sensitive information. -// Note: See also elicitationFormExample.ts for an example of using form (not URL) elicitation -// to collect *non-sensitive* user input with a structured schema. -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const express_1 = __importDefault(require("express")); -const node_crypto_1 = require("node:crypto"); -const zod_1 = require("zod"); -const mcp_js_1 = require("../../server/mcp.js"); -const streamableHttp_js_1 = require("../../server/streamableHttp.js"); -const router_js_1 = require("../../server/auth/router.js"); -const bearerAuth_js_1 = require("../../server/auth/middleware/bearerAuth.js"); -const types_js_1 = require("../../types.js"); -const inMemoryEventStore_js_1 = require("../shared/inMemoryEventStore.js"); -const demoInMemoryOAuthProvider_js_1 = require("./demoInMemoryOAuthProvider.js"); -const auth_utils_js_1 = require("../../shared/auth-utils.js"); -const cors_1 = __importDefault(require("cors")); -// Create an MCP server with implementation details -const getServer = () => { - const mcpServer = new mcp_js_1.McpServer({ - name: 'url-elicitation-http-server', - version: '1.0.0' - }, { - capabilities: { logging: {} } - }); - mcpServer.registerTool('payment-confirm', { - description: 'A tool that confirms a payment directly with a user', - inputSchema: { - cartId: zod_1.z.string().describe('The ID of the cart to confirm') - } - }, async ({ cartId }, extra) => { - /* - In a real world scenario, there would be some logic here to check if the user has the provided cartId. - For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to confirm payment) - */ - const sessionId = extra.sessionId; - if (!sessionId) { - throw new Error('Expected a Session ID'); - } - // Create and track the elicitation - const elicitationId = generateTrackedElicitation(sessionId, elicitationId => mcpServer.server.createElicitationCompletionNotifier(elicitationId)); - throw new types_js_1.UrlElicitationRequiredError([ - { - mode: 'url', - message: 'This tool requires a payment confirmation. Open the link to confirm payment!', - url: `http://localhost:${MCP_PORT}/confirm-payment?session=${sessionId}&elicitation=${elicitationId}&cartId=${encodeURIComponent(cartId)}`, - elicitationId - } - ]); - }); - mcpServer.registerTool('third-party-auth', { - description: 'A demo tool that requires third-party OAuth credentials', - inputSchema: { - param1: zod_1.z.string().describe('First parameter') - } - }, async (_, extra) => { - /* - In a real world scenario, there would be some logic here to check if we already have a valid access token for the user. - Auth info (with a subject or `sub` claim) can be typically be found in `extra.authInfo`. - If we do, we can just return the result of the tool call. - If we don't, we can throw an ElicitationRequiredError to request the user to authenticate. - For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to authenticate). - */ - const sessionId = extra.sessionId; - if (!sessionId) { - throw new Error('Expected a Session ID'); - } - // Create and track the elicitation - const elicitationId = generateTrackedElicitation(sessionId, elicitationId => mcpServer.server.createElicitationCompletionNotifier(elicitationId)); - // Simulate OAuth callback and token exchange after 5 seconds - // In a real app, this would be called from your OAuth callback handler - setTimeout(() => { - console.log(`Simulating OAuth token received for elicitation ${elicitationId}`); - completeURLElicitation(elicitationId); - }, 5000); - throw new types_js_1.UrlElicitationRequiredError([ - { - mode: 'url', - message: 'This tool requires access to your example.com account. Open the link to authenticate!', - url: 'https://www.example.com/oauth/authorize', - elicitationId - } - ]); - }); - return mcpServer; -}; -const elicitationsMap = new Map(); -// Clean up old elicitations after 1 hour to prevent memory leaks -const ELICITATION_TTL_MS = 60 * 60 * 1000; // 1 hour -const CLEANUP_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes -function cleanupOldElicitations() { - const now = new Date(); - for (const [id, metadata] of elicitationsMap.entries()) { - if (now.getTime() - metadata.createdAt.getTime() > ELICITATION_TTL_MS) { - elicitationsMap.delete(id); - console.log(`Cleaned up expired elicitation: ${id}`); - } - } -} -setInterval(cleanupOldElicitations, CLEANUP_INTERVAL_MS); -/** - * Elicitation IDs must be unique strings within the MCP session - * UUIDs are used in this example for simplicity - */ -function generateElicitationId() { - return (0, node_crypto_1.randomUUID)(); -} -/** - * Helper function to create and track a new elicitation. - */ -function generateTrackedElicitation(sessionId, createCompletionNotifier) { - const elicitationId = generateElicitationId(); - // Create a Promise and its resolver for tracking completion - let completeResolver; - const completedPromise = new Promise(resolve => { - completeResolver = resolve; - }); - const completionNotifier = createCompletionNotifier ? createCompletionNotifier(elicitationId) : undefined; - // Store the elicitation in our map - elicitationsMap.set(elicitationId, { - status: 'pending', - completedPromise, - completeResolver: completeResolver, - createdAt: new Date(), - sessionId, - completionNotifier - }); - return elicitationId; -} -/** - * Helper function to complete an elicitation. - */ -function completeURLElicitation(elicitationId) { - const elicitation = elicitationsMap.get(elicitationId); - if (!elicitation) { - console.warn(`Attempted to complete unknown elicitation: ${elicitationId}`); - return; - } - if (elicitation.status === 'complete') { - console.warn(`Elicitation already complete: ${elicitationId}`); - return; - } - // Update metadata - elicitation.status = 'complete'; - // Send completion notification to the client - if (elicitation.completionNotifier) { - console.log(`Sending notifications/elicitation/complete notification for elicitation ${elicitationId}`); - elicitation.completionNotifier().catch(error => { - console.error(`Failed to send completion notification for elicitation ${elicitationId}:`, error); - }); - } - // Resolve the promise to unblock any waiting code - elicitation.completeResolver(); -} -const MCP_PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; -const AUTH_PORT = process.env.MCP_AUTH_PORT ? parseInt(process.env.MCP_AUTH_PORT, 10) : 3001; -const app = (0, express_1.default)(); -app.use(express_1.default.json()); -// Allow CORS all domains, expose the Mcp-Session-Id header -app.use((0, cors_1.default)({ - origin: '*', // Allow all origins - exposedHeaders: ['Mcp-Session-Id'], - credentials: true // Allow cookies to be sent cross-origin -})); -// Set up OAuth (required for this example) -let authMiddleware = null; -// Create auth middleware for MCP endpoints -const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`); -const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); -const oauthMetadata = (0, demoInMemoryOAuthProvider_js_1.setupAuthServer)({ authServerUrl, mcpServerUrl, strictResource: true }); -const tokenVerifier = { - verifyAccessToken: async (token) => { - const endpoint = oauthMetadata.introspection_endpoint; - if (!endpoint) { - throw new Error('No token verification endpoint available in metadata'); - } - const response = await fetch(endpoint, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: new URLSearchParams({ - token: token - }).toString() - }); - if (!response.ok) { - throw new Error(`Invalid or expired token: ${await response.text()}`); - } - const data = await response.json(); - if (!data.aud) { - throw new Error(`Resource Indicator (RFC8707) missing`); - } - if (!(0, auth_utils_js_1.checkResourceAllowed)({ requestedResource: data.aud, configuredResource: mcpServerUrl })) { - throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); - } - // Convert the response to AuthInfo format - return { - token, - clientId: data.client_id, - scopes: data.scope ? data.scope.split(' ') : [], - expiresAt: data.exp - }; - } -}; -// Add metadata routes to the main MCP server -app.use((0, router_js_1.mcpAuthMetadataRouter)({ - oauthMetadata, - resourceServerUrl: mcpServerUrl, - scopesSupported: ['mcp:tools'], - resourceName: 'MCP Demo Server' -})); -authMiddleware = (0, bearerAuth_js_1.requireBearerAuth)({ - verifier: tokenVerifier, - requiredScopes: [], - resourceMetadataUrl: (0, router_js_1.getOAuthProtectedResourceMetadataUrl)(mcpServerUrl) -}); -/** - * API Key Form Handling - * - * Many servers today require an API key to operate, but there's no scalable way to do this dynamically for remote servers within MCP protocol. - * URL-mode elicitation enables the server to host a simple form and get the secret data securely from the user without involving the LLM or client. - **/ -async function sendApiKeyElicitation(sessionId, sender, createCompletionNotifier) { - if (!sessionId) { - console.error('No session ID provided'); - throw new Error('Expected a Session ID to track elicitation'); - } - console.log('🔑 URL elicitation demo: Requesting API key from client...'); - const elicitationId = generateTrackedElicitation(sessionId, createCompletionNotifier); - try { - const result = await sender({ - mode: 'url', - message: 'Please provide your API key to authenticate with this server', - // Host the form on the same server. In a real app, you might coordinate passing these state variables differently. - url: `http://localhost:${MCP_PORT}/api-key-form?session=${sessionId}&elicitation=${elicitationId}`, - elicitationId - }); - switch (result.action) { - case 'accept': - console.log('🔑 URL elicitation demo: Client accepted the API key elicitation (now pending form submission)'); - // Wait for the API key to be submitted via the form - // The form submission will complete the elicitation - break; - default: - console.log('🔑 URL elicitation demo: Client declined to provide an API key'); - // In a real app, this might close the connection, but for the demo, we'll continue - break; - } - } - catch (error) { - console.error('Error during API key elicitation:', error); - } -} -// API Key Form endpoint - serves a simple HTML form -app.get('/api-key-form', (req, res) => { - const mcpSessionId = req.query.session; - const elicitationId = req.query.elicitation; - if (!mcpSessionId || !elicitationId) { - res.status(400).send('

Error

Missing required parameters

'); - return; - } - // Check for user session cookie - // In production, this is often handled by some user auth middleware to ensure the user has a valid session - // This session is different from the MCP session. - // This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in. - const userSession = getUserSessionCookie(req.headers.cookie); - if (!userSession) { - res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); - return; - } - // Serve a simple HTML form - res.send(` - - - - Submit Your API Key - - - -

API Key Required

-
✓ Logged in as: ${userSession.name}
-
- - - - -
-
This is a demo showing how a server can securely elicit sensitive data from a user using a URL.
- - - `); -}); -// Handle API key form submission -app.post('/api-key-form', express_1.default.urlencoded(), (req, res) => { - const { session: sessionId, apiKey, elicitation: elicitationId } = req.body; - if (!sessionId || !apiKey || !elicitationId) { - res.status(400).send('

Error

Missing required parameters

'); - return; - } - // Check for user session cookie here too - const userSession = getUserSessionCookie(req.headers.cookie); - if (!userSession) { - res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); - return; - } - // A real app might store this API key to be used later for the user. - console.log(`🔑 Received API key \x1b[32m${apiKey}\x1b[0m for session ${sessionId}`); - // If we have an elicitationId, complete the elicitation - completeURLElicitation(elicitationId); - // Send a success response - res.send(` - - - - Success - - - -
-

Success ✓

-

API key received.

-
-

You can close this window and return to your MCP client.

- - - `); -}); -// Helper to get the user session from the demo_session cookie -function getUserSessionCookie(cookieHeader) { - if (!cookieHeader) - return null; - const cookies = cookieHeader.split(';'); - for (const cookie of cookies) { - const [name, value] = cookie.trim().split('='); - if (name === 'demo_session' && value) { - try { - return JSON.parse(decodeURIComponent(value)); - } - catch (error) { - console.error('Failed to parse demo_session cookie:', error); - return null; - } - } - } - return null; -} -/** - * Payment Confirmation Form Handling - * - * This demonstrates how a server can use URL-mode elicitation to get user confirmation - * for sensitive operations like payment processing. - **/ -// Payment Confirmation Form endpoint - serves a simple HTML form -app.get('/confirm-payment', (req, res) => { - const mcpSessionId = req.query.session; - const elicitationId = req.query.elicitation; - const cartId = req.query.cartId; - if (!mcpSessionId || !elicitationId) { - res.status(400).send('

Error

Missing required parameters

'); - return; - } - // Check for user session cookie - // In production, this is often handled by some user auth middleware to ensure the user has a valid session - // This session is different from the MCP session. - // This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in. - const userSession = getUserSessionCookie(req.headers.cookie); - if (!userSession) { - res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); - return; - } - // Serve a simple HTML form - res.send(` - - - - Confirm Payment - - - -

Confirm Payment

-
✓ Logged in as: ${userSession.name}
- ${cartId ? `
Cart ID: ${cartId}
` : ''} -
- ⚠️ Please review your order before confirming. -
-
- - - ${cartId ? `` : ''} - - -
-
This is a demo showing how a server can securely get user confirmation for sensitive operations using URL-mode elicitation.
- - - `); -}); -// Handle Payment Confirmation form submission -app.post('/confirm-payment', express_1.default.urlencoded(), (req, res) => { - const { session: sessionId, elicitation: elicitationId, cartId, action } = req.body; - if (!sessionId || !elicitationId) { - res.status(400).send('

Error

Missing required parameters

'); - return; - } - // Check for user session cookie here too - const userSession = getUserSessionCookie(req.headers.cookie); - if (!userSession) { - res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); - return; - } - if (action === 'confirm') { - // A real app would process the payment here - console.log(`💳 Payment confirmed for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`); - // Complete the elicitation - completeURLElicitation(elicitationId); - // Send a success response - res.send(` - - - - Payment Confirmed - - - -
-

Payment Confirmed ✓

-

Your payment has been successfully processed.

- ${cartId ? `

Cart ID: ${cartId}

` : ''} -
-

You can close this window and return to your MCP client.

- - - `); - } - else if (action === 'cancel') { - console.log(`💳 Payment cancelled for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`); - // The client will still receive a notifications/elicitation/complete notification, - // which indicates that the out-of-band interaction is complete (but not necessarily successful) - completeURLElicitation(elicitationId); - res.send(` - - - - Payment Cancelled - - - -
-

Payment Cancelled

-

Your payment has been cancelled.

-
-

You can close this window and return to your MCP client.

- - - `); - } - else { - res.status(400).send('

Error

Invalid action

'); - } -}); -// Map to store transports by session ID -const transports = {}; -const sessionsNeedingElicitation = {}; -// MCP POST endpoint -const mcpPostHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - console.debug(`Received MCP POST for session: ${sessionId || 'unknown'}`); - try { - let transport; - if (sessionId && transports[sessionId]) { - // Reuse existing transport - transport = transports[sessionId]; - } - else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) { - const server = getServer(); - // New initialization request - const eventStore = new inMemoryEventStore_js_1.InMemoryEventStore(); - transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ - sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), - eventStore, // Enable resumability - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - // This avoids race conditions where requests might come in before the session is stored - console.log(`Session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - sessionsNeedingElicitation[sessionId] = { - elicitationSender: params => server.server.elicitInput(params), - createCompletionNotifier: elicitationId => server.server.createElicitationCompletionNotifier(elicitationId) - }; - } - }); - // Set up onclose handler to clean up transport when closed - transport.onclose = () => { - const sid = transport.sessionId; - if (sid && transports[sid]) { - console.log(`Transport closed for session ${sid}, removing from transports map`); - delete transports[sid]; - delete sessionsNeedingElicitation[sid]; - } - }; - // Connect the transport to the MCP server BEFORE handling the request - // so responses can flow back through the same transport - await server.connect(transport); - await transport.handleRequest(req, res, req.body); - return; // Already handled - } - else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - // Handle the request with existing transport - no need to reconnect - // The existing transport is already connected to the server - await transport.handleRequest(req, res, req.body); - } - catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}; -// Set up routes with auth middleware -app.post('/mcp', authMiddleware, mcpPostHandler); -// Handle GET requests for SSE streams (using built-in support from StreamableHTTP) -const mcpGetHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - // Check for Last-Event-ID header for resumability - const lastEventId = req.headers['last-event-id']; - if (lastEventId) { - console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`); - } - else { - console.log(`Establishing new SSE stream for session ${sessionId}`); - } - const transport = transports[sessionId]; - await transport.handleRequest(req, res); - if (sessionsNeedingElicitation[sessionId]) { - const { elicitationSender, createCompletionNotifier } = sessionsNeedingElicitation[sessionId]; - // Send an elicitation request to the client in the background - sendApiKeyElicitation(sessionId, elicitationSender, createCompletionNotifier) - .then(() => { - // Only delete on successful send for this demo - delete sessionsNeedingElicitation[sessionId]; - console.log(`🔑 URL elicitation demo: Finished sending API key elicitation request for session ${sessionId}`); - }) - .catch(error => { - console.error('Error sending API key elicitation:', error); - // Keep in map to potentially retry on next reconnect - }); - } -}; -// Set up GET route with conditional auth middleware -app.get('/mcp', authMiddleware, mcpGetHandler); -// Handle DELETE requests for session termination (according to MCP spec) -const mcpDeleteHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - console.log(`Received session termination request for session ${sessionId}`); - try { - const transport = transports[sessionId]; - await transport.handleRequest(req, res); - } - catch (error) { - console.error('Error handling session termination:', error); - if (!res.headersSent) { - res.status(500).send('Error processing session termination'); - } - } -}; -// Set up DELETE route with auth middleware -app.delete('/mcp', authMiddleware, mcpDeleteHandler); -app.listen(MCP_PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`MCP Streamable HTTP Server listening on port ${MCP_PORT}`); -}); -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - // Close all active transports to properly clean up resources - for (const sessionId in transports) { - try { - console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId].close(); - delete transports[sessionId]; - delete sessionsNeedingElicitation[sessionId]; - } - catch (error) { - console.error(`Error closing transport for session ${sessionId}:`, error); - } - } - console.log('Server shutdown complete'); - process.exit(0); -}); -//# sourceMappingURL=elicitationUrlExample.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/elicitationUrlExample.js.map b/dist/cjs/examples/server/elicitationUrlExample.js.map deleted file mode 100644 index 462c721e93..0000000000 --- a/dist/cjs/examples/server/elicitationUrlExample.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"elicitationUrlExample.js","sourceRoot":"","sources":["../../../../src/examples/server/elicitationUrlExample.ts"],"names":[],"mappings":";AAAA,iEAAiE;AACjE,EAAE;AACF,2EAA2E;AAC3E,oDAAoD;AACpD,uFAAuF;AACvF,oCAAoC;AACpC,8FAA8F;AAC9F,kEAAkE;;;;;AAElE,sDAAqD;AACrD,6CAAyC;AACzC,6BAAwB;AACxB,gDAAgD;AAChD,sEAA+E;AAC/E,2DAA0G;AAC1G,8EAA+E;AAC/E,6CAAwI;AACxI,2EAAqE;AACrE,iFAAiE;AAEjE,8DAAkE;AAElE,gDAAwB;AAExB,mDAAmD;AACnD,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,SAAS,GAAG,IAAI,kBAAS,CAC3B;QACI,IAAI,EAAE,6BAA6B;QACnC,OAAO,EAAE,OAAO;KACnB,EACD;QACI,YAAY,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE;KAChC,CACJ,CAAC;IAEF,SAAS,CAAC,YAAY,CAClB,iBAAiB,EACjB;QACI,WAAW,EAAE,qD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A2C;AAC3C,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,EAAE,gBAAgB,CAAC,CAAC;AAErD,GAAG,CAAC,MAAM,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE;IACzB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,gDAAgD,QAAQ,EAAE,CAAC,CAAC;AAC5E,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAEvC,6DAA6D;IAC7D,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACjC,IAAI,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,iCAAiC,SAAS,EAAE,CAAC,CAAC;YAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;YAC7B,OAAO,0BAA0B,CAAC,SAAS,CAAC,CAAC;QACjD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts b/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts deleted file mode 100644 index 477fa6bae7..0000000000 --- a/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=jsonResponseStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts.map b/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts.map deleted file mode 100644 index ee8117ee2e..0000000000 --- a/dist/cjs/examples/server/jsonResponseStreamableHttp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"jsonResponseStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/jsonResponseStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/jsonResponseStreamableHttp.js b/dist/cjs/examples/server/jsonResponseStreamableHttp.js deleted file mode 100644 index fa4802f15e..0000000000 --- a/dist/cjs/examples/server/jsonResponseStreamableHttp.js +++ /dev/null @@ -1,175 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const express_1 = __importDefault(require("express")); -const node_crypto_1 = require("node:crypto"); -const mcp_js_1 = require("../../server/mcp.js"); -const streamableHttp_js_1 = require("../../server/streamableHttp.js"); -const z = __importStar(require("zod/v4")); -const types_js_1 = require("../../types.js"); -const cors_1 = __importDefault(require("cors")); -// Create an MCP server with implementation details -const getServer = () => { - const server = new mcp_js_1.McpServer({ - name: 'json-response-streamable-http-server', - version: '1.0.0' - }, { - capabilities: { - logging: {} - } - }); - // Register a simple tool that returns a greeting - server.tool('greet', 'A simple greeting tool', { - name: z.string().describe('Name to greet') - }, async ({ name }) => { - return { - content: [ - { - type: 'text', - text: `Hello, ${name}!` - } - ] - }; - }); - // Register a tool that sends multiple greetings with notifications - server.tool('multi-greet', 'A tool that sends different greetings with delays between them', { - name: z.string().describe('Name to greet') - }, async ({ name }, extra) => { - const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); - await server.sendLoggingMessage({ - level: 'debug', - data: `Starting multi-greet for ${name}` - }, extra.sessionId); - await sleep(1000); // Wait 1 second before first greeting - await server.sendLoggingMessage({ - level: 'info', - data: `Sending first greeting to ${name}` - }, extra.sessionId); - await sleep(1000); // Wait another second before second greeting - await server.sendLoggingMessage({ - level: 'info', - data: `Sending second greeting to ${name}` - }, extra.sessionId); - return { - content: [ - { - type: 'text', - text: `Good morning, ${name}!` - } - ] - }; - }); - return server; -}; -const app = (0, express_1.default)(); -app.use(express_1.default.json()); -// Configure CORS to expose Mcp-Session-Id header for browser-based clients -app.use((0, cors_1.default)({ - origin: '*', // Allow all origins - adjust as needed for production - exposedHeaders: ['Mcp-Session-Id'] -})); -// Map to store transports by session ID -const transports = {}; -app.post('/mcp', async (req, res) => { - console.log('Received MCP request:', req.body); - try { - // Check for existing session ID - const sessionId = req.headers['mcp-session-id']; - let transport; - if (sessionId && transports[sessionId]) { - // Reuse existing transport - transport = transports[sessionId]; - } - else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) { - // New initialization request - use JSON response mode - transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ - sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), - enableJsonResponse: true, // Enable JSON response mode - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - // This avoids race conditions where requests might come in before the session is stored - console.log(`Session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - } - }); - // Connect the transport to the MCP server BEFORE handling the request - const server = getServer(); - await server.connect(transport); - await transport.handleRequest(req, res, req.body); - return; // Already handled - } - else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - // Handle the request with existing transport - no need to reconnect - await transport.handleRequest(req, res, req.body); - } - catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}); -// Handle GET requests for SSE streams according to spec -app.get('/mcp', async (req, res) => { - // Since this is a very simple example, we don't support GET requests for this server - // The spec requires returning 405 Method Not Allowed in this case - res.status(405).set('Allow', 'POST').send('Method Not Allowed'); -}); -// Start the server -const PORT = 3000; -app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`MCP Streamable HTTP Server listening on port ${PORT}`); -}); -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - process.exit(0); -}); -//# sourceMappingURL=jsonResponseStreamableHttp.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/jsonResponseStreamableHttp.js.map b/dist/cjs/examples/server/jsonResponseStreamableHttp.js.map deleted file mode 100644 index cfe7bc4a31..0000000000 --- a/dist/cjs/examples/server/jsonResponseStreamableHttp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"jsonResponseStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/jsonResponseStreamableHttp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sDAAqD;AACrD,6CAAyC;AACzC,gDAAgD;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AAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBACjB,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE;oBACH,IAAI,EAAE,CAAC,KAAK;oBACZ,OAAO,EAAE,uBAAuB;iBACnC;gBACD,EAAE,EAAE,IAAI;aACX,CAAC,CAAC;QACP,CAAC;IACL,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,wDAAwD;AACxD,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,EAAE;IAClD,qFAAqF;IACrF,kEAAkE;IAClE,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;AACpE,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,gDAAgD,IAAI,EAAE,CAAC,CAAC;AACxE,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/mcpServerOutputSchema.d.ts b/dist/cjs/examples/server/mcpServerOutputSchema.d.ts deleted file mode 100644 index a6cb497473..0000000000 --- a/dist/cjs/examples/server/mcpServerOutputSchema.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env node -/** - * Example MCP server using the high-level McpServer API with outputSchema - * This demonstrates how to easily create tools with structured output - */ -export {}; -//# sourceMappingURL=mcpServerOutputSchema.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/mcpServerOutputSchema.d.ts.map b/dist/cjs/examples/server/mcpServerOutputSchema.d.ts.map deleted file mode 100644 index bd3abdcc26..0000000000 --- a/dist/cjs/examples/server/mcpServerOutputSchema.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"mcpServerOutputSchema.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/mcpServerOutputSchema.ts"],"names":[],"mappings":";AACA;;;GAGG"} \ No newline at end of file diff --git a/dist/cjs/examples/server/mcpServerOutputSchema.js b/dist/cjs/examples/server/mcpServerOutputSchema.js deleted file mode 100644 index 4ac7e5cdae..0000000000 --- a/dist/cjs/examples/server/mcpServerOutputSchema.js +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/env node -"use strict"; -/** - * Example MCP server using the high-level McpServer API with outputSchema - * This demonstrates how to easily create tools with structured output - */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const mcp_js_1 = require("../../server/mcp.js"); -const stdio_js_1 = require("../../server/stdio.js"); -const z = __importStar(require("zod/v4")); -const server = new mcp_js_1.McpServer({ - name: 'mcp-output-schema-high-level-example', - version: '1.0.0' -}); -// Define a tool with structured output - Weather data -server.registerTool('get_weather', { - description: 'Get weather information for a city', - inputSchema: { - city: z.string().describe('City name'), - country: z.string().describe('Country code (e.g., US, UK)') - }, - outputSchema: { - temperature: z.object({ - celsius: z.number(), - fahrenheit: z.number() - }), - conditions: z.enum(['sunny', 'cloudy', 'rainy', 'stormy', 'snowy']), - humidity: z.number().min(0).max(100), - wind: z.object({ - speed_kmh: z.number(), - direction: z.string() - }) - } -}, async ({ city, country }) => { - // Parameters are available but not used in this example - void city; - void country; - // Simulate weather API call - const temp_c = Math.round((Math.random() * 35 - 5) * 10) / 10; - const conditions = ['sunny', 'cloudy', 'rainy', 'stormy', 'snowy'][Math.floor(Math.random() * 5)]; - const structuredContent = { - temperature: { - celsius: temp_c, - fahrenheit: Math.round(((temp_c * 9) / 5 + 32) * 10) / 10 - }, - conditions, - humidity: Math.round(Math.random() * 100), - wind: { - speed_kmh: Math.round(Math.random() * 50), - direction: ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'][Math.floor(Math.random() * 8)] - } - }; - return { - content: [ - { - type: 'text', - text: JSON.stringify(structuredContent, null, 2) - } - ], - structuredContent - }; -}); -async function main() { - const transport = new stdio_js_1.StdioServerTransport(); - await server.connect(transport); - console.error('High-level Output Schema Example Server running on stdio'); -} -main().catch(error => { - console.error('Server error:', error); - process.exit(1); -}); -//# sourceMappingURL=mcpServerOutputSchema.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/mcpServerOutputSchema.js.map b/dist/cjs/examples/server/mcpServerOutputSchema.js.map deleted file mode 100644 index ba0f8b24c4..0000000000 --- a/dist/cjs/examples/server/mcpServerOutputSchema.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"mcpServerOutputSchema.js","source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AK,CAAC,0DAA0D,CAAC,CAAC;AAC9E,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleSseServer.d.ts b/dist/cjs/examples/server/simpleSseServer.d.ts deleted file mode 100644 index 4269b7814f..0000000000 --- a/dist/cjs/examples/server/simpleSseServer.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=simpleSseServer.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleSseServer.d.ts.map b/dist/cjs/examples/server/simpleSseServer.d.ts.map deleted file mode 100644 index 08a1b45021..0000000000 --- a/dist/cjs/examples/server/simpleSseServer.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleSseServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleSseServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleSseServer.js b/dist/cjs/examples/server/simpleSseServer.js deleted file mode 100644 index 8b1afd86b2..0000000000 --- a/dist/cjs/examples/server/simpleSseServer.js +++ /dev/null @@ -1,169 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const express_1 = __importDefault(require("express")); -const mcp_js_1 = require("../../server/mcp.js"); -const sse_js_1 = require("../../server/sse.js"); -const z = __importStar(require("zod/v4")); -/** - * This example server demonstrates the deprecated HTTP+SSE transport - * (protocol version 2024-11-05). It mainly used for testing backward compatible clients. - * - * The server exposes two endpoints: - * - /mcp: For establishing the SSE stream (GET) - * - /messages: For receiving client messages (POST) - * - */ -// Create an MCP server instance -const getServer = () => { - const server = new mcp_js_1.McpServer({ - name: 'simple-sse-server', - version: '1.0.0' - }, { capabilities: { logging: {} } }); - server.tool('start-notification-stream', 'Starts sending periodic notifications', { - interval: z.number().describe('Interval in milliseconds between notifications').default(1000), - count: z.number().describe('Number of notifications to send').default(10) - }, async ({ interval, count }, extra) => { - const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); - let counter = 0; - // Send the initial notification - await server.sendLoggingMessage({ - level: 'info', - data: `Starting notification stream with ${count} messages every ${interval}ms` - }, extra.sessionId); - // Send periodic notifications - while (counter < count) { - counter++; - await sleep(interval); - try { - await server.sendLoggingMessage({ - level: 'info', - data: `Notification #${counter} at ${new Date().toISOString()}` - }, extra.sessionId); - } - catch (error) { - console.error('Error sending notification:', error); - } - } - return { - content: [ - { - type: 'text', - text: `Completed sending ${count} notifications every ${interval}ms` - } - ] - }; - }); - return server; -}; -const app = (0, express_1.default)(); -app.use(express_1.default.json()); -// Store transports by session ID -const transports = {}; -// SSE endpoint for establishing the stream -app.get('/mcp', async (req, res) => { - console.log('Received GET request to /sse (establishing SSE stream)'); - try { - // Create a new SSE transport for the client - // The endpoint for POST messages is '/messages' - const transport = new sse_js_1.SSEServerTransport('/messages', res); - // Store the transport by session ID - const sessionId = transport.sessionId; - transports[sessionId] = transport; - // Set up onclose handler to clean up transport when closed - transport.onclose = () => { - console.log(`SSE transport closed for session ${sessionId}`); - delete transports[sessionId]; - }; - // Connect the transport to the MCP server - const server = getServer(); - await server.connect(transport); - console.log(`Established SSE stream with session ID: ${sessionId}`); - } - catch (error) { - console.error('Error establishing SSE stream:', error); - if (!res.headersSent) { - res.status(500).send('Error establishing SSE stream'); - } - } -}); -// Messages endpoint for receiving client JSON-RPC requests -app.post('/messages', async (req, res) => { - console.log('Received POST request to /messages'); - // Extract session ID from URL query parameter - // In the SSE protocol, this is added by the client based on the endpoint event - const sessionId = req.query.sessionId; - if (!sessionId) { - console.error('No session ID provided in request URL'); - res.status(400).send('Missing sessionId parameter'); - return; - } - const transport = transports[sessionId]; - if (!transport) { - console.error(`No active transport found for session ID: ${sessionId}`); - res.status(404).send('Session not found'); - return; - } - try { - // Handle the POST message with the transport - await transport.handlePostMessage(req, res, req.body); - } - catch (error) { - console.error('Error handling request:', error); - if (!res.headersSent) { - res.status(500).send('Error handling request'); - } - } -}); -// Start the server -const PORT = 3000; -app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`Simple SSE Server (deprecated protocol version 2024-11-05) listening on port ${PORT}`); -}); -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - // Close all active transports to properly clean up resources - for (const sessionId in transports) { - try { - console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId].close(); - delete transports[sessionId]; - } - catch (error) { - console.error(`Error closing transport for session ${sessionId}:`, error); - } - } - console.log('Server shutdown complete'); - process.exit(0); -}); -//# sourceMappingURL=simpleSseServer.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleSseServer.js.map b/dist/cjs/examples/server/simpleSseServer.js.map deleted file mode 100644 index 6bb0444a2f..0000000000 --- a/dist/cjs/examples/server/simpleSseServer.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleSseServer.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleSseServer.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sDAAqD;AACrD,gDAAgD;AAChD,gDAAyD;AACzD,0CAA4B;AAG5B;;;;;;;;GAQG;AAEH,gCAAgC;AAChC,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,GAAG,IAAI,kBAAS,CACxB;QACI,IAAI,EAAE,mBAAmB;QACzB,OAAO,EAAE,OAAO;KACnB,EACD,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,CACpC,CAAC;IAEF,MAAM,CAAC,IAAI,CACP,2BAA2B,EAC3B,uCAAuC,EACvC;QACI,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,gDAAgD,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC;QAC7F,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,iCAAiC,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC;KAC5E,EACD,KAAK,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,EAAE,KAAK,EAA2B,EAAE;QAC1D,MAAM,KAAK,GAAG,CAAC,EAAU,EAAE,EAAE,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;QAC9E,IAAI,OAAO,GAAG,CAAC,CAAC;QAEhB,gCAAgC;QAChC,MAAM,MAAM,CAAC,kBAAkB,CAC3B;YACI,KAAK,EAAE,MAAM;YACb,IAAI,EAAE,qCAAqC,KAAK,mBAAmB,QAAQ,IAAI;SAClF,EACD,KAAK,CAAC,SAAS,CAClB,CAAC;QAEF,8BAA8B;QAC9B,OAAO,OAAO,GAAG,KAAK,EAAE,CAAC;YACrB,OAAO,EAAE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AC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts b/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts deleted file mode 100644 index 0aa4ad2439..0000000000 --- a/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=simpleStatelessStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts.map b/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts.map deleted file mode 100644 index 92deb06ecb..0000000000 --- a/dist/cjs/examples/server/simpleStatelessStreamableHttp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleStatelessStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleStatelessStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStatelessStreamableHttp.js b/dist/cjs/examples/server/simpleStatelessStreamableHttp.js deleted file mode 100644 index b82ab00f81..0000000000 --- a/dist/cjs/examples/server/simpleStatelessStreamableHttp.js +++ /dev/null @@ -1,170 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const express_1 = __importDefault(require("express")); -const mcp_js_1 = require("../../server/mcp.js"); -const streamableHttp_js_1 = require("../../server/streamableHttp.js"); -const z = __importStar(require("zod/v4")); -const cors_1 = __importDefault(require("cors")); -const getServer = () => { - // Create an MCP server with implementation details - const server = new mcp_js_1.McpServer({ - name: 'stateless-streamable-http-server', - version: '1.0.0' - }, { capabilities: { logging: {} } }); - // Register a simple prompt - server.prompt('greeting-template', 'A simple greeting prompt template', { - name: z.string().describe('Name to include in greeting') - }, async ({ name }) => { - return { - messages: [ - { - role: 'user', - content: { - type: 'text', - text: `Please greet ${name} in a friendly manner.` - } - } - ] - }; - }); - // Register a tool specifically for testing resumability - server.tool('start-notification-stream', 'Starts sending periodic notifications for testing resumability', { - interval: z.number().describe('Interval in milliseconds between notifications').default(100), - count: z.number().describe('Number of notifications to send (0 for 100)').default(10) - }, async ({ interval, count }, extra) => { - const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); - let counter = 0; - while (count === 0 || counter < count) { - counter++; - try { - await server.sendLoggingMessage({ - level: 'info', - data: `Periodic notification #${counter} at ${new Date().toISOString()}` - }, extra.sessionId); - } - catch (error) { - console.error('Error sending notification:', error); - } - // Wait for the specified interval - await sleep(interval); - } - return { - content: [ - { - type: 'text', - text: `Started sending periodic notifications every ${interval}ms` - } - ] - }; - }); - // Create a simple resource at a fixed URI - server.resource('greeting-resource', 'https://example.com/greetings/default', { mimeType: 'text/plain' }, async () => { - return { - contents: [ - { - uri: 'https://example.com/greetings/default', - text: 'Hello, world!' - } - ] - }; - }); - return server; -}; -const app = (0, express_1.default)(); -app.use(express_1.default.json()); -// Configure CORS to expose Mcp-Session-Id header for browser-based clients -app.use((0, cors_1.default)({ - origin: '*', // Allow all origins - adjust as needed for production - exposedHeaders: ['Mcp-Session-Id'] -})); -app.post('/mcp', async (req, res) => { - const server = getServer(); - try { - const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ - sessionIdGenerator: undefined - }); - await server.connect(transport); - await transport.handleRequest(req, res, req.body); - res.on('close', () => { - console.log('Request closed'); - transport.close(); - server.close(); - }); - } - catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}); -app.get('/mcp', async (req, res) => { - console.log('Received GET MCP request'); - res.writeHead(405).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Method not allowed.' - }, - id: null - })); -}); -app.delete('/mcp', async (req, res) => { - console.log('Received DELETE MCP request'); - res.writeHead(405).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Method not allowed.' - }, - id: null - })); -}); -// Start the server -const PORT = 3000; -app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`MCP Stateless Streamable HTTP Server listening on port ${PORT}`); -}); -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - process.exit(0); -}); -//# sourceMappingURL=simpleStatelessStreamableHttp.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStatelessStreamableHttp.js.map b/dist/cjs/examples/server/simpleStatelessStreamableHttp.js.map deleted file mode 100644 index abc90f024e..0000000000 --- a/dist/cjs/examples/server/simpleStatelessStreamableHttp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleStatelessStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleStatelessStreamableHttp.ts"],"names":[],"mappings":";;;;;;;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X,OAAO,EAAE,KAAK;QACd,KAAK,EAAE;YACH,IAAI,EAAE,CAAC,KAAK;YACZ,OAAO,EAAE,qBAAqB;SACjC;QACD,EAAE,EAAE,IAAI;KACX,CAAC,CACL,CAAC;AACN,CAAC,CAAC,CAAC;AAEH,GAAG,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,EAAE;IACrD,OAAO,CAAC,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAC3C,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,CAClB,IAAI,CAAC,SAAS,CAAC;QACX,OAAO,EAAE,KAAK;QACd,KAAK,EAAE;YACH,IAAI,EAAE,CAAC,KAAK;YACZ,OAAO,EAAE,qBAAqB;SACjC;QACD,EAAE,EAAE,IAAI;KACX,CAAC,CACL,CAAC;AACN,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0DAA0D,IAAI,EAAE,CAAC,CAAC;AAClF,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStreamableHttp.d.ts b/dist/cjs/examples/server/simpleStreamableHttp.d.ts deleted file mode 100644 index a20be42ca4..0000000000 --- a/dist/cjs/examples/server/simpleStreamableHttp.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=simpleStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStreamableHttp.d.ts.map b/dist/cjs/examples/server/simpleStreamableHttp.d.ts.map deleted file mode 100644 index e3cf042241..0000000000 --- a/dist/cjs/examples/server/simpleStreamableHttp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStreamableHttp.js b/dist/cjs/examples/server/simpleStreamableHttp.js deleted file mode 100644 index 86d46ea456..0000000000 --- a/dist/cjs/examples/server/simpleStreamableHttp.js +++ /dev/null @@ -1,611 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const express_1 = __importDefault(require("express")); -const node_crypto_1 = require("node:crypto"); -const z = __importStar(require("zod/v4")); -const mcp_js_1 = require("../../server/mcp.js"); -const streamableHttp_js_1 = require("../../server/streamableHttp.js"); -const router_js_1 = require("../../server/auth/router.js"); -const bearerAuth_js_1 = require("../../server/auth/middleware/bearerAuth.js"); -const types_js_1 = require("../../types.js"); -const inMemoryEventStore_js_1 = require("../shared/inMemoryEventStore.js"); -const demoInMemoryOAuthProvider_js_1 = require("./demoInMemoryOAuthProvider.js"); -const auth_utils_js_1 = require("../../shared/auth-utils.js"); -const cors_1 = __importDefault(require("cors")); -// Check for OAuth flag -const useOAuth = process.argv.includes('--oauth'); -const strictOAuth = process.argv.includes('--oauth-strict'); -// Create an MCP server with implementation details -const getServer = () => { - const server = new mcp_js_1.McpServer({ - name: 'simple-streamable-http-server', - version: '1.0.0', - icons: [{ src: './mcp.svg', sizes: ['512x512'], mimeType: 'image/svg+xml' }], - websiteUrl: 'https://github.com/modelcontextprotocol/typescript-sdk' - }, { capabilities: { logging: {} } }); - // Register a simple tool that returns a greeting - server.registerTool('greet', { - title: 'Greeting Tool', // Display name for UI - description: 'A simple greeting tool', - inputSchema: { - name: z.string().describe('Name to greet') - } - }, async ({ name }) => { - return { - content: [ - { - type: 'text', - text: `Hello, ${name}!` - } - ] - }; - }); - // Register a tool that sends multiple greetings with notifications (with annotations) - server.tool('multi-greet', 'A tool that sends different greetings with delays between them', { - name: z.string().describe('Name to greet') - }, { - title: 'Multiple Greeting Tool', - readOnlyHint: true, - openWorldHint: false - }, async ({ name }, extra) => { - const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); - await server.sendLoggingMessage({ - level: 'debug', - data: `Starting multi-greet for ${name}` - }, extra.sessionId); - await sleep(1000); // Wait 1 second before first greeting - await server.sendLoggingMessage({ - level: 'info', - data: `Sending first greeting to ${name}` - }, extra.sessionId); - await sleep(1000); // Wait another second before second greeting - await server.sendLoggingMessage({ - level: 'info', - data: `Sending second greeting to ${name}` - }, extra.sessionId); - return { - content: [ - { - type: 'text', - text: `Good morning, ${name}!` - } - ] - }; - }); - // Register a tool that demonstrates form elicitation (user input collection with a schema) - // This creates a closure that captures the server instance - server.tool('collect-user-info', 'A tool that collects user information through form elicitation', { - infoType: z.enum(['contact', 'preferences', 'feedback']).describe('Type of information to collect') - }, async ({ infoType }) => { - let message; - let requestedSchema; - switch (infoType) { - case 'contact': - message = 'Please provide your contact information'; - requestedSchema = { - type: 'object', - properties: { - name: { - type: 'string', - title: 'Full Name', - description: 'Your full name' - }, - email: { - type: 'string', - title: 'Email Address', - description: 'Your email address', - format: 'email' - }, - phone: { - type: 'string', - title: 'Phone Number', - description: 'Your phone number (optional)' - } - }, - required: ['name', 'email'] - }; - break; - case 'preferences': - message = 'Please set your preferences'; - requestedSchema = { - type: 'object', - properties: { - theme: { - type: 'string', - title: 'Theme', - description: 'Choose your preferred theme', - enum: ['light', 'dark', 'auto'], - enumNames: ['Light', 'Dark', 'Auto'] - }, - notifications: { - type: 'boolean', - title: 'Enable Notifications', - description: 'Would you like to receive notifications?', - default: true - }, - frequency: { - type: 'string', - title: 'Notification Frequency', - description: 'How often would you like notifications?', - enum: ['daily', 'weekly', 'monthly'], - enumNames: ['Daily', 'Weekly', 'Monthly'] - } - }, - required: ['theme'] - }; - break; - case 'feedback': - message = 'Please provide your feedback'; - requestedSchema = { - type: 'object', - properties: { - rating: { - type: 'integer', - title: 'Rating', - description: 'Rate your experience (1-5)', - minimum: 1, - maximum: 5 - }, - comments: { - type: 'string', - title: 'Comments', - description: 'Additional comments (optional)', - maxLength: 500 - }, - recommend: { - type: 'boolean', - title: 'Would you recommend this?', - description: 'Would you recommend this to others?' - } - }, - required: ['rating', 'recommend'] - }; - break; - default: - throw new Error(`Unknown info type: ${infoType}`); - } - try { - // Use the underlying server instance to elicit input from the client - const result = await server.server.elicitInput({ - mode: 'form', - message, - requestedSchema - }); - if (result.action === 'accept') { - return { - content: [ - { - type: 'text', - text: `Thank you! Collected ${infoType} information: ${JSON.stringify(result.content, null, 2)}` - } - ] - }; - } - else if (result.action === 'decline') { - return { - content: [ - { - type: 'text', - text: `No information was collected. User declined ${infoType} information request.` - } - ] - }; - } - else { - return { - content: [ - { - type: 'text', - text: `Information collection was cancelled by the user.` - } - ] - }; - } - } - catch (error) { - return { - content: [ - { - type: 'text', - text: `Error collecting ${infoType} information: ${error}` - } - ] - }; - } - }); - // Register a simple prompt with title - server.registerPrompt('greeting-template', { - title: 'Greeting Template', // Display name for UI - description: 'A simple greeting prompt template', - argsSchema: { - name: z.string().describe('Name to include in greeting') - } - }, async ({ name }) => { - return { - messages: [ - { - role: 'user', - content: { - type: 'text', - text: `Please greet ${name} in a friendly manner.` - } - } - ] - }; - }); - // Register a tool specifically for testing resumability - server.tool('start-notification-stream', 'Starts sending periodic notifications for testing resumability', { - interval: z.number().describe('Interval in milliseconds between notifications').default(100), - count: z.number().describe('Number of notifications to send (0 for 100)').default(50) - }, async ({ interval, count }, extra) => { - const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); - let counter = 0; - while (count === 0 || counter < count) { - counter++; - try { - await server.sendLoggingMessage({ - level: 'info', - data: `Periodic notification #${counter} at ${new Date().toISOString()}` - }, extra.sessionId); - } - catch (error) { - console.error('Error sending notification:', error); - } - // Wait for the specified interval - await sleep(interval); - } - return { - content: [ - { - type: 'text', - text: `Started sending periodic notifications every ${interval}ms` - } - ] - }; - }); - // Create a simple resource at a fixed URI - server.registerResource('greeting-resource', 'https://example.com/greetings/default', { - title: 'Default Greeting', // Display name for UI - description: 'A simple greeting resource', - mimeType: 'text/plain' - }, async () => { - return { - contents: [ - { - uri: 'https://example.com/greetings/default', - text: 'Hello, world!' - } - ] - }; - }); - // Create additional resources for ResourceLink demonstration - server.registerResource('example-file-1', 'file:///example/file1.txt', { - title: 'Example File 1', - description: 'First example file for ResourceLink demonstration', - mimeType: 'text/plain' - }, async () => { - return { - contents: [ - { - uri: 'file:///example/file1.txt', - text: 'This is the content of file 1' - } - ] - }; - }); - server.registerResource('example-file-2', 'file:///example/file2.txt', { - title: 'Example File 2', - description: 'Second example file for ResourceLink demonstration', - mimeType: 'text/plain' - }, async () => { - return { - contents: [ - { - uri: 'file:///example/file2.txt', - text: 'This is the content of file 2' - } - ] - }; - }); - // Register a tool that returns ResourceLinks - server.registerTool('list-files', { - title: 'List Files with ResourceLinks', - description: 'Returns a list of files as ResourceLinks without embedding their content', - inputSchema: { - includeDescriptions: z.boolean().optional().describe('Whether to include descriptions in the resource links') - } - }, async ({ includeDescriptions = true }) => { - const resourceLinks = [ - { - type: 'resource_link', - uri: 'https://example.com/greetings/default', - name: 'Default Greeting', - mimeType: 'text/plain', - ...(includeDescriptions && { description: 'A simple greeting resource' }) - }, - { - type: 'resource_link', - uri: 'file:///example/file1.txt', - name: 'Example File 1', - mimeType: 'text/plain', - ...(includeDescriptions && { description: 'First example file for ResourceLink demonstration' }) - }, - { - type: 'resource_link', - uri: 'file:///example/file2.txt', - name: 'Example File 2', - mimeType: 'text/plain', - ...(includeDescriptions && { description: 'Second example file for ResourceLink demonstration' }) - } - ]; - return { - content: [ - { - type: 'text', - text: 'Here are the available files as resource links:' - }, - ...resourceLinks, - { - type: 'text', - text: '\nYou can read any of these resources using their URI.' - } - ] - }; - }); - return server; -}; -const MCP_PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; -const AUTH_PORT = process.env.MCP_AUTH_PORT ? parseInt(process.env.MCP_AUTH_PORT, 10) : 3001; -const app = (0, express_1.default)(); -app.use(express_1.default.json()); -// Allow CORS all domains, expose the Mcp-Session-Id header -app.use((0, cors_1.default)({ - origin: '*', // Allow all origins - exposedHeaders: ['Mcp-Session-Id'] -})); -// Set up OAuth if enabled -let authMiddleware = null; -if (useOAuth) { - // Create auth middleware for MCP endpoints - const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`); - const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); - const oauthMetadata = (0, demoInMemoryOAuthProvider_js_1.setupAuthServer)({ authServerUrl, mcpServerUrl, strictResource: strictOAuth }); - const tokenVerifier = { - verifyAccessToken: async (token) => { - const endpoint = oauthMetadata.introspection_endpoint; - if (!endpoint) { - throw new Error('No token verification endpoint available in metadata'); - } - const response = await fetch(endpoint, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: new URLSearchParams({ - token: token - }).toString() - }); - if (!response.ok) { - throw new Error(`Invalid or expired token: ${await response.text()}`); - } - const data = await response.json(); - if (strictOAuth) { - if (!data.aud) { - throw new Error(`Resource Indicator (RFC8707) missing`); - } - if (!(0, auth_utils_js_1.checkResourceAllowed)({ requestedResource: data.aud, configuredResource: mcpServerUrl })) { - throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); - } - } - // Convert the response to AuthInfo format - return { - token, - clientId: data.client_id, - scopes: data.scope ? data.scope.split(' ') : [], - expiresAt: data.exp - }; - } - }; - // Add metadata routes to the main MCP server - app.use((0, router_js_1.mcpAuthMetadataRouter)({ - oauthMetadata, - resourceServerUrl: mcpServerUrl, - scopesSupported: ['mcp:tools'], - resourceName: 'MCP Demo Server' - })); - authMiddleware = (0, bearerAuth_js_1.requireBearerAuth)({ - verifier: tokenVerifier, - requiredScopes: [], - resourceMetadataUrl: (0, router_js_1.getOAuthProtectedResourceMetadataUrl)(mcpServerUrl) - }); -} -// Map to store transports by session ID -const transports = {}; -// MCP POST endpoint with optional auth -const mcpPostHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (sessionId) { - console.log(`Received MCP request for session: ${sessionId}`); - } - else { - console.log('Request body:', req.body); - } - if (useOAuth && req.auth) { - console.log('Authenticated user:', req.auth); - } - try { - let transport; - if (sessionId && transports[sessionId]) { - // Reuse existing transport - transport = transports[sessionId]; - } - else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) { - // New initialization request - const eventStore = new inMemoryEventStore_js_1.InMemoryEventStore(); - transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ - sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), - eventStore, // Enable resumability - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - // This avoids race conditions where requests might come in before the session is stored - console.log(`Session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - } - }); - // Set up onclose handler to clean up transport when closed - transport.onclose = () => { - const sid = transport.sessionId; - if (sid && transports[sid]) { - console.log(`Transport closed for session ${sid}, removing from transports map`); - delete transports[sid]; - } - }; - // Connect the transport to the MCP server BEFORE handling the request - // so responses can flow back through the same transport - const server = getServer(); - await server.connect(transport); - await transport.handleRequest(req, res, req.body); - return; // Already handled - } - else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - // Handle the request with existing transport - no need to reconnect - // The existing transport is already connected to the server - await transport.handleRequest(req, res, req.body); - } - catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}; -// Set up routes with conditional auth middleware -if (useOAuth && authMiddleware) { - app.post('/mcp', authMiddleware, mcpPostHandler); -} -else { - app.post('/mcp', mcpPostHandler); -} -// Handle GET requests for SSE streams (using built-in support from StreamableHTTP) -const mcpGetHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - if (useOAuth && req.auth) { - console.log('Authenticated SSE connection from user:', req.auth); - } - // Check for Last-Event-ID header for resumability - const lastEventId = req.headers['last-event-id']; - if (lastEventId) { - console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`); - } - else { - console.log(`Establishing new SSE stream for session ${sessionId}`); - } - const transport = transports[sessionId]; - await transport.handleRequest(req, res); -}; -// Set up GET route with conditional auth middleware -if (useOAuth && authMiddleware) { - app.get('/mcp', authMiddleware, mcpGetHandler); -} -else { - app.get('/mcp', mcpGetHandler); -} -// Handle DELETE requests for session termination (according to MCP spec) -const mcpDeleteHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - console.log(`Received session termination request for session ${sessionId}`); - try { - const transport = transports[sessionId]; - await transport.handleRequest(req, res); - } - catch (error) { - console.error('Error handling session termination:', error); - if (!res.headersSent) { - res.status(500).send('Error processing session termination'); - } - } -}; -// Set up DELETE route with conditional auth middleware -if (useOAuth && authMiddleware) { - app.delete('/mcp', authMiddleware, mcpDeleteHandler); -} -else { - app.delete('/mcp', mcpDeleteHandler); -} -app.listen(MCP_PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`MCP Streamable HTTP Server listening on port ${MCP_PORT}`); -}); -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - // Close all active transports to properly clean up resources - for (const sessionId in transports) { - try { - console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId].close(); - delete transports[sessionId]; - } - catch (error) { - console.error(`Error closing transport for session ${sessionId}:`, error); - } - } - console.log('Server shutdown complete'); - process.exit(0); -}); -//# sourceMappingURL=simpleStreamableHttp.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/simpleStreamableHttp.js.map b/dist/cjs/examples/server/simpleStreamableHttp.js.map deleted file mode 100644 index c39bde1267..0000000000 --- a/dist/cjs/examples/server/simpleStreamableHttp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleStreamableHttp.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sDAAqD;AACrD,6CAAyC;AACzC,0CAA4B;AAC5B,gDAAgD;AAChD,sEAA+E;AAC/E,2DAA0G;AAC1G,8EAA+E;AAC/E,6CAOwB;AACxB,2EAAqE;AACrE,iFAAiE;AAEjE,8DAAkE;AAElE,gDAAwB;AAExB,uBAAuB;AACvB,MAAM,QAAQ,GAA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,CAAC;QACjC,IAAI,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,iCAAiC,SAAS,EAAE,CAAC,CAAC;YAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts b/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts deleted file mode 100644 index c536d0c80e..0000000000 --- a/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=sseAndStreamableHttpCompatibleServer.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map b/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map deleted file mode 100644 index fb982c84a6..0000000000 --- a/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"sseAndStreamableHttpCompatibleServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/sseAndStreamableHttpCompatibleServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js b/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js deleted file mode 100644 index def1932ede..0000000000 --- a/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js +++ /dev/null @@ -1,263 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const express_1 = __importDefault(require("express")); -const node_crypto_1 = require("node:crypto"); -const mcp_js_1 = require("../../server/mcp.js"); -const streamableHttp_js_1 = require("../../server/streamableHttp.js"); -const sse_js_1 = require("../../server/sse.js"); -const z = __importStar(require("zod/v4")); -const types_js_1 = require("../../types.js"); -const inMemoryEventStore_js_1 = require("../shared/inMemoryEventStore.js"); -const cors_1 = __importDefault(require("cors")); -/** - * This example server demonstrates backwards compatibility with both: - * 1. The deprecated HTTP+SSE transport (protocol version 2024-11-05) - * 2. The Streamable HTTP transport (protocol version 2025-03-26) - * - * It maintains a single MCP server instance but exposes two transport options: - * - /mcp: The new Streamable HTTP endpoint (supports GET/POST/DELETE) - * - /sse: The deprecated SSE endpoint for older clients (GET to establish stream) - * - /messages: The deprecated POST endpoint for older clients (POST to send messages) - */ -const getServer = () => { - const server = new mcp_js_1.McpServer({ - name: 'backwards-compatible-server', - version: '1.0.0' - }, { capabilities: { logging: {} } }); - // Register a simple tool that sends notifications over time - server.tool('start-notification-stream', 'Starts sending periodic notifications for testing resumability', { - interval: z.number().describe('Interval in milliseconds between notifications').default(100), - count: z.number().describe('Number of notifications to send (0 for 100)').default(50) - }, async ({ interval, count }, extra) => { - const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); - let counter = 0; - while (count === 0 || counter < count) { - counter++; - try { - await server.sendLoggingMessage({ - level: 'info', - data: `Periodic notification #${counter} at ${new Date().toISOString()}` - }, extra.sessionId); - } - catch (error) { - console.error('Error sending notification:', error); - } - // Wait for the specified interval - await sleep(interval); - } - return { - content: [ - { - type: 'text', - text: `Started sending periodic notifications every ${interval}ms` - } - ] - }; - }); - return server; -}; -// Create Express application -const app = (0, express_1.default)(); -app.use(express_1.default.json()); -// Configure CORS to expose Mcp-Session-Id header for browser-based clients -app.use((0, cors_1.default)({ - origin: '*', // Allow all origins - adjust as needed for production - exposedHeaders: ['Mcp-Session-Id'] -})); -// Store transports by session ID -const transports = {}; -//============================================================================= -// STREAMABLE HTTP TRANSPORT (PROTOCOL VERSION 2025-03-26) -//============================================================================= -// Handle all MCP Streamable HTTP requests (GET, POST, DELETE) on a single endpoint -app.all('/mcp', async (req, res) => { - console.log(`Received ${req.method} request to /mcp`); - try { - // Check for existing session ID - const sessionId = req.headers['mcp-session-id']; - let transport; - if (sessionId && transports[sessionId]) { - // Check if the transport is of the correct type - const existingTransport = transports[sessionId]; - if (existingTransport instanceof streamableHttp_js_1.StreamableHTTPServerTransport) { - // Reuse existing transport - transport = existingTransport; - } - else { - // Transport exists but is not a StreamableHTTPServerTransport (could be SSEServerTransport) - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: Session exists but uses a different transport protocol' - }, - id: null - }); - return; - } - } - else if (!sessionId && req.method === 'POST' && (0, types_js_1.isInitializeRequest)(req.body)) { - const eventStore = new inMemoryEventStore_js_1.InMemoryEventStore(); - transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ - sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), - eventStore, // Enable resumability - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - console.log(`StreamableHTTP session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - } - }); - // Set up onclose handler to clean up transport when closed - transport.onclose = () => { - const sid = transport.sessionId; - if (sid && transports[sid]) { - console.log(`Transport closed for session ${sid}, removing from transports map`); - delete transports[sid]; - } - }; - // Connect the transport to the MCP server - const server = getServer(); - await server.connect(transport); - } - else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - // Handle the request with the transport - await transport.handleRequest(req, res, req.body); - } - catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}); -//============================================================================= -// DEPRECATED HTTP+SSE TRANSPORT (PROTOCOL VERSION 2024-11-05) -//============================================================================= -app.get('/sse', async (req, res) => { - console.log('Received GET request to /sse (deprecated SSE transport)'); - const transport = new sse_js_1.SSEServerTransport('/messages', res); - transports[transport.sessionId] = transport; - res.on('close', () => { - delete transports[transport.sessionId]; - }); - const server = getServer(); - await server.connect(transport); -}); -app.post('/messages', async (req, res) => { - const sessionId = req.query.sessionId; - let transport; - const existingTransport = transports[sessionId]; - if (existingTransport instanceof sse_js_1.SSEServerTransport) { - // Reuse existing transport - transport = existingTransport; - } - else { - // Transport exists but is not a SSEServerTransport (could be StreamableHTTPServerTransport) - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: Session exists but uses a different transport protocol' - }, - id: null - }); - return; - } - if (transport) { - await transport.handlePostMessage(req, res, req.body); - } - else { - res.status(400).send('No transport found for sessionId'); - } -}); -// Start the server -const PORT = 3000; -app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`Backwards compatible MCP server listening on port ${PORT}`); - console.log(` -============================================== -SUPPORTED TRANSPORT OPTIONS: - -1. Streamable Http(Protocol version: 2025-03-26) - Endpoint: /mcp - Methods: GET, POST, DELETE - Usage: - - Initialize with POST to /mcp - - Establish SSE stream with GET to /mcp - - Send requests with POST to /mcp - - Terminate session with DELETE to /mcp - -2. Http + SSE (Protocol version: 2024-11-05) - Endpoints: /sse (GET) and /messages (POST) - Usage: - - Establish SSE stream with GET to /sse - - Send requests with POST to /messages?sessionId= -============================================== -`); -}); -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - // Close all active transports to properly clean up resources - for (const sessionId in transports) { - try { - console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId].close(); - delete transports[sessionId]; - } - catch (error) { - console.error(`Error closing transport for session ${sessionId}:`, error); - } - } - console.log('Server shutdown complete'); - process.exit(0); -}); -//# sourceMappingURL=sseAndStreamableHttpCompatibleServer.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js.map b/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js.map deleted file mode 100644 index 148cf28b1c..0000000000 --- a/dist/cjs/examples/server/sseAndStreamableHttpCompatibleServer.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"sseAndStreamableHttpCompatibleServer.js","sourceRoot":"","sources":["../../../../src/examples/server/sseAndStreamableHttpCompatibleServer.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,sDAAqD;AACrD,6CAAyC;AACzC,gDAAgD;AAChD,sEAA+E;AAC/E,gDAAyD;AACzD,0CAA4B;AAC5B,6CAAqE;AACrE,2EAAqE;AACrE,gDAAwB;AAExB;;;;;;;;;GASG;AAEH,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,GAAG,IAAI,kBAAS,CACxB;QACI,IAAI,EAAE,6BAA6B;QACnC,OAAO,EAAE,OAAO;KACnB,EACD,EAAE,YAAY,EAAE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,6DAA6D;IAC7D,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACjC,IAAI,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,iCAAiC,SAAS,EAAE,CAAC,CAAC;YAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts b/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts deleted file mode 100644 index 4df17831b7..0000000000 --- a/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=standaloneSseWithGetStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map b/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map deleted file mode 100644 index df60dc51b0..0000000000 --- a/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"standaloneSseWithGetStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/standaloneSseWithGetStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js b/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js deleted file mode 100644 index ae1193d31c..0000000000 --- a/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js +++ /dev/null @@ -1,116 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const express_1 = __importDefault(require("express")); -const node_crypto_1 = require("node:crypto"); -const mcp_js_1 = require("../../server/mcp.js"); -const streamableHttp_js_1 = require("../../server/streamableHttp.js"); -const types_js_1 = require("../../types.js"); -// Create an MCP server with implementation details -const server = new mcp_js_1.McpServer({ - name: 'resource-list-changed-notification-server', - version: '1.0.0' -}); -// Store transports by session ID to send notifications -const transports = {}; -const addResource = (name, content) => { - const uri = `https://mcp-example.com/dynamic/${encodeURIComponent(name)}`; - server.resource(name, uri, { mimeType: 'text/plain', description: `Dynamic resource: ${name}` }, async () => { - return { - contents: [{ uri, text: content }] - }; - }); -}; -addResource('example-resource', 'Initial content for example-resource'); -const resourceChangeInterval = setInterval(() => { - const name = (0, node_crypto_1.randomUUID)(); - addResource(name, `Content for ${name}`); -}, 5000); // Change resources every 5 seconds for testing -const app = (0, express_1.default)(); -app.use(express_1.default.json()); -app.post('/mcp', async (req, res) => { - console.log('Received MCP request:', req.body); - try { - // Check for existing session ID - const sessionId = req.headers['mcp-session-id']; - let transport; - if (sessionId && transports[sessionId]) { - // Reuse existing transport - transport = transports[sessionId]; - } - else if (!sessionId && (0, types_js_1.isInitializeRequest)(req.body)) { - // New initialization request - transport = new streamableHttp_js_1.StreamableHTTPServerTransport({ - sessionIdGenerator: () => (0, node_crypto_1.randomUUID)(), - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - // This avoids race conditions where requests might come in before the session is stored - console.log(`Session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - } - }); - // Connect the transport to the MCP server - await server.connect(transport); - // Handle the request - the onsessioninitialized callback will store the transport - await transport.handleRequest(req, res, req.body); - return; // Already handled - } - else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - // Handle the request with existing transport - await transport.handleRequest(req, res, req.body); - } - catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}); -// Handle GET requests for SSE streams (now using built-in support from StreamableHTTP) -app.get('/mcp', async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - console.log(`Establishing SSE stream for session ${sessionId}`); - const transport = transports[sessionId]; - await transport.handleRequest(req, res); -}); -// Start the server -const PORT = 3000; -app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`Server listening on port ${PORT}`); -}); -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - clearInterval(resourceChangeInterval); - await server.close(); - process.exit(0); -}); -//# sourceMappingURL=standaloneSseWithGetStreamableHttp.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js.map b/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js.map deleted file mode 100644 index c48532b79e..0000000000 --- a/dist/cjs/examples/server/standaloneSseWithGetStreamableHttp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"standaloneSseWithGetStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/standaloneSseWithGetStreamableHttp.ts"],"names":[],"mappings":";;;;;AAAA,sDAAqD;AACrD,6CAAyC;AACzC,gDAAgD;AAChD,sEAA+E;AAC/E,6CAAyE;AAEzE,mDAAmD;AACnD,MAAM,MAAM,GAAG,IAAI,kBAAS,CAAC;IACzB,IAAI,EAAE,2CAA2C;IACjD,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,uDAAuD;AACvD,MAAM,UAAU,GAA2D,EAAE,CAAC;AAE9E,MAAM,WAAW,GAAG,C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AAE,CAAC;IACrB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/server/toolWithSampleServer.d.ts b/dist/cjs/examples/server/toolWithSampleServer.d.ts deleted file mode 100644 index acc24b6a53..0000000000 --- a/dist/cjs/examples/server/toolWithSampleServer.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=toolWithSampleServer.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/server/toolWithSampleServer.d.ts.map b/dist/cjs/examples/server/toolWithSampleServer.d.ts.map deleted file mode 100644 index bd0cebcf19..0000000000 --- a/dist/cjs/examples/server/toolWithSampleServer.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"toolWithSampleServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/toolWithSampleServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/examples/server/toolWithSampleServer.js b/dist/cjs/examples/server/toolWithSampleServer.js deleted file mode 100644 index 4a35eb7987..0000000000 --- a/dist/cjs/examples/server/toolWithSampleServer.js +++ /dev/null @@ -1,71 +0,0 @@ -"use strict"; -// Run with: npx tsx src/examples/server/toolWithSampleServer.ts -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -const mcp_js_1 = require("../../server/mcp.js"); -const stdio_js_1 = require("../../server/stdio.js"); -const z = __importStar(require("zod/v4")); -const mcpServer = new mcp_js_1.McpServer({ - name: 'tools-with-sample-server', - version: '1.0.0' -}); -// Tool that uses LLM sampling to summarize any text -mcpServer.registerTool('summarize', { - description: 'Summarize any text using an LLM', - inputSchema: { - text: z.string().describe('Text to summarize') - } -}, async ({ text }) => { - // Call the LLM through MCP sampling - const response = await mcpServer.server.createMessage({ - messages: [ - { - role: 'user', - content: { - type: 'text', - text: `Please summarize the following text concisely:\n\n${text}` - } - } - ], - maxTokens: 500 - }); - const contents = Array.isArray(response.content) ? response.content : [response.content]; - return { - content: contents.map(content => ({ - type: 'text', - text: content.type === 'text' ? content.text : 'Unable to generate summary' - })) - }; -}); -async function main() { - const transport = new stdio_js_1.StdioServerTransport(); - await mcpServer.connect(transport); - console.log('MCP server is running...'); -} -main().catch(error => { - console.error('Server error:', error); - process.exit(1); -}); -//# sourceMappingURL=toolWithSampleServer.js.map \ No newline at end of file diff --git a/dist/cjs/examples/server/toolWithSampleServer.js.map b/dist/cjs/examples/server/toolWithSampleServer.js.map deleted file mode 100644 index 5f9d219921..0000000000 --- a/dist/cjs/examples/server/toolWithSampleServer.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"toolWithSampleServer.js","sourceRoot":"","sources":["../../../../src/examples/server/toolWithSampleServer.ts"],"names":[],"mappings":";AAAA,gEAAgE;;;;;;;;;;;;;;;;;;;;;;;;;AAEhE,gDAAgD;AAChD,oDAA6D;AAC7D,0CAA4B;AAE5B,MAAM,SAAS,GAAG,IAAI,kBAAS,CAAC;IAC5B,IAAI,EAAE,0BAA0B;IAChC,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,oDAAoD;AACpD,SAAS,CAA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,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/examples/shared/inMemoryEventStore.d.ts b/dist/cjs/examples/shared/inMemoryEventStore.d.ts deleted file mode 100644 index 26ff38cf93..0000000000 --- a/dist/cjs/examples/shared/inMemoryEventStore.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { JSONRPCMessage } from '../../types.js'; -import { EventStore } from '../../server/streamableHttp.js'; -/** - * Simple in-memory implementation of the EventStore interface for resumability - * This is primarily intended for examples and testing, not for production use - * where a persistent storage solution would be more appropriate. - */ -export declare class InMemoryEventStore implements EventStore { - private events; - /** - * Generates a unique event ID for a given stream ID - */ - private generateEventId; - /** - * Extracts the stream ID from an event ID - */ - private getStreamIdFromEventId; - /** - * Stores an event with a generated event ID - * Implements EventStore.storeEvent - */ - storeEvent(streamId: string, message: JSONRPCMessage): Promise; - /** - * Replays events that occurred after a specific event ID - * Implements EventStore.replayEventsAfter - */ - replayEventsAfter(lastEventId: string, { send }: { - send: (eventId: string, message: JSONRPCMessage) => Promise; - }): Promise; -} -//# sourceMappingURL=inMemoryEventStore.d.ts.map \ No newline at end of file diff --git a/dist/cjs/examples/shared/inMemoryEventStore.d.ts.map b/dist/cjs/examples/shared/inMemoryEventStore.d.ts.map deleted file mode 100644 index a67ee6cd17..0000000000 --- a/dist/cjs/examples/shared/inMemoryEventStore.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inMemoryEventStore.d.ts","sourceRoot":"","sources":["../../../../src/examples/shared/inMemoryEventStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAE5D;;;;GAIG;AACH,qBAAa,kBAAmB,YAAW,UAAU;IACjD,OAAO,CAAC,MAAM,CAAyE;IAEvF;;OAEG;IACH,OAAO,CAAC,eAAe;IAIvB;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAK9B;;;OAGG;IACG,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;IAM5E;;;OAGG;IACG,iBAAiB,CACnB,WAAW,EAAE,MAAM,EACnB,EAAE,IAAI,EAAE,EAAE;QAAE,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;KAAE,GAChF,OAAO,CAAC,MAAM,CAAC;CAkCrB"} \ No newline at end of file diff --git a/dist/cjs/examples/shared/inMemoryEventStore.js b/dist/cjs/examples/shared/inMemoryEventStore.js deleted file mode 100644 index d33ffdb5c1..0000000000 --- a/dist/cjs/examples/shared/inMemoryEventStore.js +++ /dev/null @@ -1,69 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InMemoryEventStore = void 0; -/** - * Simple in-memory implementation of the EventStore interface for resumability - * This is primarily intended for examples and testing, not for production use - * where a persistent storage solution would be more appropriate. - */ -class InMemoryEventStore { - constructor() { - this.events = new Map(); - } - /** - * Generates a unique event ID for a given stream ID - */ - generateEventId(streamId) { - return `${streamId}_${Date.now()}_${Math.random().toString(36).substring(2, 10)}`; - } - /** - * Extracts the stream ID from an event ID - */ - getStreamIdFromEventId(eventId) { - const parts = eventId.split('_'); - return parts.length > 0 ? parts[0] : ''; - } - /** - * Stores an event with a generated event ID - * Implements EventStore.storeEvent - */ - async storeEvent(streamId, message) { - const eventId = this.generateEventId(streamId); - this.events.set(eventId, { streamId, message }); - return eventId; - } - /** - * Replays events that occurred after a specific event ID - * Implements EventStore.replayEventsAfter - */ - async replayEventsAfter(lastEventId, { send }) { - if (!lastEventId || !this.events.has(lastEventId)) { - return ''; - } - // Extract the stream ID from the event ID - const streamId = this.getStreamIdFromEventId(lastEventId); - if (!streamId) { - return ''; - } - let foundLastEvent = false; - // Sort events by eventId for chronological ordering - const sortedEvents = [...this.events.entries()].sort((a, b) => a[0].localeCompare(b[0])); - for (const [eventId, { streamId: eventStreamId, message }] of sortedEvents) { - // Only include events from the same stream - if (eventStreamId !== streamId) { - continue; - } - // Start sending events after we find the lastEventId - if (eventId === lastEventId) { - foundLastEvent = true; - continue; - } - if (foundLastEvent) { - await send(eventId, message); - } - } - return streamId; - } -} -exports.InMemoryEventStore = InMemoryEventStore; -//# sourceMappingURL=inMemoryEventStore.js.map \ No newline at end of file diff --git a/dist/cjs/examples/shared/inMemoryEventStore.js.map b/dist/cjs/examples/shared/inMemoryEventStore.js.map deleted file mode 100644 index d696450639..0000000000 --- a/dist/cjs/examples/shared/inMemoryEventStore.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inMemoryEventStore.js","sourceRoot":"","sources":["../../../../src/examples/shared/inMemoryEventStore.ts"],"names":[],"mappings":";;;AAGA;;;;GAIG;AACH,MAAa,kBAAkB;IAA/B;QACY,WAAM,GAA+D,IAAI,GAAG,EAAE,CAAC;IAoE3F,CAAC;IAlEG;;OAEG;IACK,eAAe,CAAC,QAAgB;QACpC,OAAO,GAAG,QAAQ,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC;IACtF,CAAC;IAED;;OAEG;IACK,sBAAsB,CAAC,OAAe;QAC1C,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACjC,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;IAC5C,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,UAAU,CAAC,QAAgB,EAAE,OAAuB;QACtD,MAAM,OAAO,GAAG,IAAI,CAAC,eAAe,CAAC,QAAQ,CAAC,CA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;AArED,gDAqEC"} \ No newline at end of file diff --git a/dist/cjs/inMemory.d.ts b/dist/cjs/inMemory.d.ts deleted file mode 100644 index 32a931a863..0000000000 --- a/dist/cjs/inMemory.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { Transport } from './shared/transport.js'; -import { JSONRPCMessage, RequestId } from './types.js'; -import { AuthInfo } from './server/auth/types.js'; -/** - * In-memory transport for creating clients and servers that talk to each other within the same process. - */ -export declare class InMemoryTransport implements Transport { - private _otherTransport?; - private _messageQueue; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage, extra?: { - authInfo?: AuthInfo; - }) => void; - sessionId?: string; - /** - * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a Client and one to a Server. - */ - static createLinkedPair(): [InMemoryTransport, InMemoryTransport]; - start(): Promise; - close(): Promise; - /** - * Sends a message with optional auth info. - * This is useful for testing authentication scenarios. - */ - send(message: JSONRPCMessage, options?: { - relatedRequestId?: RequestId; - authInfo?: AuthInfo; - }): Promise; -} -//# sourceMappingURL=inMemory.d.ts.map \ No newline at end of file diff --git a/dist/cjs/inMemory.d.ts.map b/dist/cjs/inMemory.d.ts.map deleted file mode 100644 index 46bc74be17..0000000000 --- a/dist/cjs/inMemory.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inMemory.d.ts","sourceRoot":"","sources":["../../src/inMemory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAOlD;;GAEG;AACH,qBAAa,iBAAkB,YAAW,SAAS;IAC/C,OAAO,CAAC,eAAe,CAAC,CAAoB;IAC5C,OAAO,CAAC,aAAa,CAAuB;IAE5C,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,KAAK,IAAI,CAAC;IAC/E,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,MAAM,CAAC,gBAAgB,IAAI,CAAC,iBAAiB,EAAE,iBAAiB,CAAC;IAQ3D,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAQtB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAO5B;;;OAGG;IACG,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,SAAS,CAAC;QAAC,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAWtH"} \ No newline at end of file diff --git a/dist/cjs/inMemory.js b/dist/cjs/inMemory.js deleted file mode 100644 index 3070d83910..0000000000 --- a/dist/cjs/inMemory.js +++ /dev/null @@ -1,53 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InMemoryTransport = void 0; -/** - * In-memory transport for creating clients and servers that talk to each other within the same process. - */ -class InMemoryTransport { - constructor() { - this._messageQueue = []; - } - /** - * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a Client and one to a Server. - */ - static createLinkedPair() { - const clientTransport = new InMemoryTransport(); - const serverTransport = new InMemoryTransport(); - clientTransport._otherTransport = serverTransport; - serverTransport._otherTransport = clientTransport; - return [clientTransport, serverTransport]; - } - async start() { - var _a; - // Process any messages that were queued before start was called - while (this._messageQueue.length > 0) { - const queuedMessage = this._messageQueue.shift(); - (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, queuedMessage.message, queuedMessage.extra); - } - } - async close() { - var _a; - const other = this._otherTransport; - this._otherTransport = undefined; - await (other === null || other === void 0 ? void 0 : other.close()); - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - } - /** - * Sends a message with optional auth info. - * This is useful for testing authentication scenarios. - */ - async send(message, options) { - if (!this._otherTransport) { - throw new Error('Not connected'); - } - if (this._otherTransport.onmessage) { - this._otherTransport.onmessage(message, { authInfo: options === null || options === void 0 ? void 0 : options.authInfo }); - } - else { - this._otherTransport._messageQueue.push({ message, extra: { authInfo: options === null || options === void 0 ? void 0 : options.authInfo } }); - } - } -} -exports.InMemoryTransport = InMemoryTransport; -//# sourceMappingURL=inMemory.js.map \ No newline at end of file diff --git a/dist/cjs/inMemory.js.map b/dist/cjs/inMemory.js.map deleted file mode 100644 index 869a51f615..0000000000 --- a/dist/cjs/inMemory.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inMemory.js","sourceRoot":"","sources":["../../src/inMemory.ts"],"names":[],"mappings":";;;AASA;;GAEG;AACH,MAAa,iBAAiB;IAA9B;QAEY,kBAAa,GAAoB,EAAE,CAAC;IAgDhD,CAAC;IAzCG;;OAEG;IACH,MAAM,CAAC,gBAAgB;QACnB,MAAM,eAAe,GAAG,IAAI,iBAAiB,EAAE,CAAC;QAChD,MAAM,eAAe,GAAG,IAAI,iBAAiB,EAAE,CAAC;QAChD,eAAe,CAAC,eAAe,GAAG,eAAe,CAAC;QAClD,eAAe,CAAC,eAAe,GAAG,eAAe,CAAC;QAClD,OAAO,CAAC,eAAe,EAAE,eAAe,CAAC,CAAC;IAC9C,CAAC;IAED,KAAK,CAAC,KAAK;;QACP,gEAAgE;QAChE,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACnC,MAAM,aAAa,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,EAAG,CAAC;YAClD,MAAA,IAAI,CAAC,SAAS,qDAAG,aAAa,CAAC,OAAO,EAAE,aAAa,CAAC,KAAK,CAAC,CAAC;QACjE,CAAC;IACL,CAAC;IAED,KAAK,CAAC,KAAK;;QACP,MAAM,KAAK,GAAG,IAAI,CAAC,eAAe,CAAC;QACnC,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACjC,MAAM,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,KAAK,EAAE,CAAA,CAAC;QACrB,MAAA,IAAI,CAAC,OAAO,oDAAI,CAAC;IACrB,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,IAAI,CAAC,OAAuB,EAAE,OAA+D;QAC/F,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC;YACxB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;QACrC,CAAC;QAED,IAAI,IAAI,CAAC,eAAe,CAAC,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,EAAE,CAAC,CAAC;QAC7E,CAAC;aAAM,CAAC;YACJ,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;QACjG,CAAC;IACL,CAAC;CACJ;AAlDD,8CAkDC"} \ No newline at end of file diff --git a/dist/cjs/package.json b/dist/cjs/package.json deleted file mode 100644 index b731bd61b9..0000000000 --- a/dist/cjs/package.json +++ /dev/null @@ -1 +0,0 @@ -{"type": "commonjs"} diff --git a/dist/cjs/server/auth/clients.d.ts b/dist/cjs/server/auth/clients.d.ts deleted file mode 100644 index be6899a198..0000000000 --- a/dist/cjs/server/auth/clients.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { OAuthClientInformationFull } from '../../shared/auth.js'; -/** - * Stores information about registered OAuth clients for this server. - */ -export interface OAuthRegisteredClientsStore { - /** - * Returns information about a registered client, based on its ID. - */ - getClient(clientId: string): OAuthClientInformationFull | undefined | Promise; - /** - * Registers a new client with the server. The client ID and secret will be automatically generated by the library. A modified version of the client information can be returned to reflect specific values enforced by the server. - * - * NOTE: Implementations should NOT delete expired client secrets in-place. Auth middleware provided by this library will automatically check the `client_secret_expires_at` field and reject requests with expired secrets. Any custom logic for authenticating clients should check the `client_secret_expires_at` field as well. - * - * If unimplemented, dynamic client registration is unsupported. - */ - registerClient?(client: Omit): OAuthClientInformationFull | Promise; -} -//# sourceMappingURL=clients.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/clients.d.ts.map b/dist/cjs/server/auth/clients.d.ts.map deleted file mode 100644 index ab3851db35..0000000000 --- a/dist/cjs/server/auth/clients.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"clients.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/clients.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAElE;;GAEG;AACH,MAAM,WAAW,2BAA2B;IACxC;;OAEG;IACH,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,0BAA0B,GAAG,SAAS,GAAG,OAAO,CAAC,0BAA0B,GAAG,SAAS,CAAC,CAAC;IAEtH;;;;;;OAMG;IACH,cAAc,CAAC,CACX,MAAM,EAAE,IAAI,CAAC,0BAA0B,EAAE,WAAW,GAAG,qBAAqB,CAAC,GAC9E,0BAA0B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAAC;CACvE"} \ No newline at end of file diff --git a/dist/cjs/server/auth/clients.js b/dist/cjs/server/auth/clients.js deleted file mode 100644 index 866b88b74b..0000000000 --- a/dist/cjs/server/auth/clients.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -//# sourceMappingURL=clients.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/clients.js.map b/dist/cjs/server/auth/clients.js.map deleted file mode 100644 index 0210104422..0000000000 --- a/dist/cjs/server/auth/clients.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"clients.js","sourceRoot":"","sources":["../../../../src/server/auth/clients.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/server/auth/errors.d.ts b/dist/cjs/server/auth/errors.d.ts deleted file mode 100644 index b487760fc2..0000000000 --- a/dist/cjs/server/auth/errors.d.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { OAuthErrorResponse } from '../../shared/auth.js'; -/** - * Base class for all OAuth errors - */ -export declare class OAuthError extends Error { - readonly errorUri?: string | undefined; - static errorCode: string; - constructor(message: string, errorUri?: string | undefined); - /** - * Converts the error to a standard OAuth error response object - */ - toResponseObject(): OAuthErrorResponse; - get errorCode(): string; -} -/** - * Invalid request error - The request is missing a required parameter, - * includes an invalid parameter value, includes a parameter more than once, - * or is otherwise malformed. - */ -export declare class InvalidRequestError extends OAuthError { - static errorCode: string; -} -/** - * Invalid client error - Client authentication failed (e.g., unknown client, no client - * authentication included, or unsupported authentication method). - */ -export declare class InvalidClientError extends OAuthError { - static errorCode: string; -} -/** - * Invalid grant error - The provided authorization grant or refresh token is - * invalid, expired, revoked, does not match the redirection URI used in the - * authorization request, or was issued to another client. - */ -export declare class InvalidGrantError extends OAuthError { - static errorCode: string; -} -/** - * Unauthorized client error - The authenticated client is not authorized to use - * this authorization grant type. - */ -export declare class UnauthorizedClientError extends OAuthError { - static errorCode: string; -} -/** - * Unsupported grant type error - The authorization grant type is not supported - * by the authorization server. - */ -export declare class UnsupportedGrantTypeError extends OAuthError { - static errorCode: string; -} -/** - * Invalid scope error - The requested scope is invalid, unknown, malformed, or - * exceeds the scope granted by the resource owner. - */ -export declare class InvalidScopeError extends OAuthError { - static errorCode: string; -} -/** - * Access denied error - The resource owner or authorization server denied the request. - */ -export declare class AccessDeniedError extends OAuthError { - static errorCode: string; -} -/** - * Server error - The authorization server encountered an unexpected condition - * that prevented it from fulfilling the request. - */ -export declare class ServerError extends OAuthError { - static errorCode: string; -} -/** - * Temporarily unavailable error - The authorization server is currently unable to - * handle the request due to a temporary overloading or maintenance of the server. - */ -export declare class TemporarilyUnavailableError extends OAuthError { - static errorCode: string; -} -/** - * Unsupported response type error - The authorization server does not support - * obtaining an authorization code using this method. - */ -export declare class UnsupportedResponseTypeError extends OAuthError { - static errorCode: string; -} -/** - * Unsupported token type error - The authorization server does not support - * the requested token type. - */ -export declare class UnsupportedTokenTypeError extends OAuthError { - static errorCode: string; -} -/** - * Invalid token error - The access token provided is expired, revoked, malformed, - * or invalid for other reasons. - */ -export declare class InvalidTokenError extends OAuthError { - static errorCode: string; -} -/** - * Method not allowed error - The HTTP method used is not allowed for this endpoint. - * (Custom, non-standard error) - */ -export declare class MethodNotAllowedError extends OAuthError { - static errorCode: string; -} -/** - * Too many requests error - Rate limit exceeded. - * (Custom, non-standard error based on RFC 6585) - */ -export declare class TooManyRequestsError extends OAuthError { - static errorCode: string; -} -/** - * Invalid client metadata error - The client metadata is invalid. - * (Custom error for dynamic client registration - RFC 7591) - */ -export declare class InvalidClientMetadataError extends OAuthError { - static errorCode: string; -} -/** - * Insufficient scope error - The request requires higher privileges than provided by the access token. - */ -export declare class InsufficientScopeError extends OAuthError { - static errorCode: string; -} -/** - * A utility class for defining one-off error codes - */ -export declare class CustomOAuthError extends OAuthError { - private readonly customErrorCode; - constructor(customErrorCode: string, message: string, errorUri?: string); - get errorCode(): string; -} -/** - * A full list of all OAuthErrors, enabling parsing from error responses - */ -export declare const OAUTH_ERRORS: { - readonly [x: string]: typeof InvalidRequestError; -}; -//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/errors.d.ts.map b/dist/cjs/server/auth/errors.d.ts.map deleted file mode 100644 index 5141085c26..0000000000 --- a/dist/cjs/server/auth/errors.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EA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;;GAGG;AACH,qBAAa,iBAAkB,SAAQ,UAAU;IAC7C,MAAM,CAAC,SAAS,SAAmB;CACtC;AAED;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,UAAU;IACjD,MAAM,CAAC,SAAS,SAAwB;CAC3C;AAED;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,UAAU;IAChD,MAAM,CAAC,SAAS,SAAuB;CAC1C;AAED;;;GAGG;AACH,qBAAa,0BAA2B,SAAQ,UAAU;IACtD,MAAM,CAAC,SAAS,SAA6B;CAChD;AAED;;GAEG;AACH,qBAAa,sBAAuB,SAAQ,UAAU;IAClD,MAAM,CAAC,SAAS,SAAwB;CAC3C;AAED;;GAEG;AACH,qBAAa,gBAAiB,SAAQ,UAAU;IAExC,OAAO,CAAC,QAAQ,CAAC,eAAe;gBAAf,eAAe,EAAE,MAAM,EACxC,OAAO,EAAE,MAAM,EACf,QAAQ,CAAC,EAAE,MAAM;IAKrB,IAAI,SAAS,IAAI,MAAM,CAEtB;CACJ;AAED;;GAEG;AACH,eAAO,MAAM,YAAY;;CAiBf,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/errors.js b/dist/cjs/server/auth/errors.js deleted file mode 100644 index 6b97cce5d3..0000000000 --- a/dist/cjs/server/auth/errors.js +++ /dev/null @@ -1,193 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OAUTH_ERRORS = exports.CustomOAuthError = exports.InsufficientScopeError = exports.InvalidClientMetadataError = exports.TooManyRequestsError = exports.MethodNotAllowedError = exports.InvalidTokenError = exports.UnsupportedTokenTypeError = exports.UnsupportedResponseTypeError = exports.TemporarilyUnavailableError = exports.ServerError = exports.AccessDeniedError = exports.InvalidScopeError = exports.UnsupportedGrantTypeError = exports.UnauthorizedClientError = exports.InvalidGrantError = exports.InvalidClientError = exports.InvalidRequestError = exports.OAuthError = void 0; -/** - * Base class for all OAuth errors - */ -class OAuthError extends Error { - constructor(message, errorUri) { - super(message); - this.errorUri = errorUri; - this.name = this.constructor.name; - } - /** - * Converts the error to a standard OAuth error response object - */ - toResponseObject() { - const response = { - error: this.errorCode, - error_description: this.message - }; - if (this.errorUri) { - response.error_uri = this.errorUri; - } - return response; - } - get errorCode() { - return this.constructor.errorCode; - } -} -exports.OAuthError = OAuthError; -/** - * Invalid request error - The request is missing a required parameter, - * includes an invalid parameter value, includes a parameter more than once, - * or is otherwise malformed. - */ -class InvalidRequestError extends OAuthError { -} -exports.InvalidRequestError = InvalidRequestError; -InvalidRequestError.errorCode = 'invalid_request'; -/** - * Invalid client error - Client authentication failed (e.g., unknown client, no client - * authentication included, or unsupported authentication method). - */ -class InvalidClientError extends OAuthError { -} -exports.InvalidClientError = InvalidClientError; -InvalidClientError.errorCode = 'invalid_client'; -/** - * Invalid grant error - The provided authorization grant or refresh token is - * invalid, expired, revoked, does not match the redirection URI used in the - * authorization request, or was issued to another client. - */ -class InvalidGrantError extends OAuthError { -} -exports.InvalidGrantError = InvalidGrantError; -InvalidGrantError.errorCode = 'invalid_grant'; -/** - * Unauthorized client error - The authenticated client is not authorized to use - * this authorization grant type. - */ -class UnauthorizedClientError extends OAuthError { -} -exports.UnauthorizedClientError = UnauthorizedClientError; -UnauthorizedClientError.errorCode = 'unauthorized_client'; -/** - * Unsupported grant type error - The authorization grant type is not supported - * by the authorization server. - */ -class UnsupportedGrantTypeError extends OAuthError { -} -exports.UnsupportedGrantTypeError = UnsupportedGrantTypeError; -UnsupportedGrantTypeError.errorCode = 'unsupported_grant_type'; -/** - * Invalid scope error - The requested scope is invalid, unknown, malformed, or - * exceeds the scope granted by the resource owner. - */ -class InvalidScopeError extends OAuthError { -} -exports.InvalidScopeError = InvalidScopeError; -InvalidScopeError.errorCode = 'invalid_scope'; -/** - * Access denied error - The resource owner or authorization server denied the request. - */ -class AccessDeniedError extends OAuthError { -} -exports.AccessDeniedError = AccessDeniedError; -AccessDeniedError.errorCode = 'access_denied'; -/** - * Server error - The authorization server encountered an unexpected condition - * that prevented it from fulfilling the request. - */ -class ServerError extends OAuthError { -} -exports.ServerError = ServerError; -ServerError.errorCode = 'server_error'; -/** - * Temporarily unavailable error - The authorization server is currently unable to - * handle the request due to a temporary overloading or maintenance of the server. - */ -class TemporarilyUnavailableError extends OAuthError { -} -exports.TemporarilyUnavailableError = TemporarilyUnavailableError; -TemporarilyUnavailableError.errorCode = 'temporarily_unavailable'; -/** - * Unsupported response type error - The authorization server does not support - * obtaining an authorization code using this method. - */ -class UnsupportedResponseTypeError extends OAuthError { -} -exports.UnsupportedResponseTypeError = UnsupportedResponseTypeError; -UnsupportedResponseTypeError.errorCode = 'unsupported_response_type'; -/** - * Unsupported token type error - The authorization server does not support - * the requested token type. - */ -class UnsupportedTokenTypeError extends OAuthError { -} -exports.UnsupportedTokenTypeError = UnsupportedTokenTypeError; -UnsupportedTokenTypeError.errorCode = 'unsupported_token_type'; -/** - * Invalid token error - The access token provided is expired, revoked, malformed, - * or invalid for other reasons. - */ -class InvalidTokenError extends OAuthError { -} -exports.InvalidTokenError = InvalidTokenError; -InvalidTokenError.errorCode = 'invalid_token'; -/** - * Method not allowed error - The HTTP method used is not allowed for this endpoint. - * (Custom, non-standard error) - */ -class MethodNotAllowedError extends OAuthError { -} -exports.MethodNotAllowedError = MethodNotAllowedError; -MethodNotAllowedError.errorCode = 'method_not_allowed'; -/** - * Too many requests error - Rate limit exceeded. - * (Custom, non-standard error based on RFC 6585) - */ -class TooManyRequestsError extends OAuthError { -} -exports.TooManyRequestsError = TooManyRequestsError; -TooManyRequestsError.errorCode = 'too_many_requests'; -/** - * Invalid client metadata error - The client metadata is invalid. - * (Custom error for dynamic client registration - RFC 7591) - */ -class InvalidClientMetadataError extends OAuthError { -} -exports.InvalidClientMetadataError = InvalidClientMetadataError; -InvalidClientMetadataError.errorCode = 'invalid_client_metadata'; -/** - * Insufficient scope error - The request requires higher privileges than provided by the access token. - */ -class InsufficientScopeError extends OAuthError { -} -exports.InsufficientScopeError = InsufficientScopeError; -InsufficientScopeError.errorCode = 'insufficient_scope'; -/** - * A utility class for defining one-off error codes - */ -class CustomOAuthError extends OAuthError { - constructor(customErrorCode, message, errorUri) { - super(message, errorUri); - this.customErrorCode = customErrorCode; - } - get errorCode() { - return this.customErrorCode; - } -} -exports.CustomOAuthError = CustomOAuthError; -/** - * A full list of all OAuthErrors, enabling parsing from error responses - */ -exports.OAUTH_ERRORS = { - [InvalidRequestError.errorCode]: InvalidRequestError, - [InvalidClientError.errorCode]: InvalidClientError, - [InvalidGrantError.errorCode]: InvalidGrantError, - [UnauthorizedClientError.errorCode]: UnauthorizedClientError, - [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError, - [InvalidScopeError.errorCode]: InvalidScopeError, - [AccessDeniedError.errorCode]: AccessDeniedError, - [ServerError.errorCode]: ServerError, - [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError, - [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError, - [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError, - [InvalidTokenError.errorCode]: InvalidTokenError, - [MethodNotAllowedError.errorCode]: MethodNotAllowedError, - [TooManyRequestsError.errorCode]: TooManyRequestsError, - [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError, - [InsufficientScopeError.errorCode]: InsufficientScopeError -}; -//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/errors.js.map b/dist/cjs/server/auth/errors.js.map deleted file mode 100644 index 974f6ccfd7..0000000000 --- a/dist/cjs/server/auth/errors.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../src/server/auth/errors.ts"],"names":[],"mappings":";;;AAEA;;GAEG;AACH,MAAa,UAAW,SAAQ,KAAK;IAGjC,YACI,OAAe,EACC,QAAiB;QAEjC,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,aAAQ,GAAR,QAAQ,CAAS;QAGjC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CA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C,yBAAyB,CAAC,SAAS,CAAC,EAAE,yBAAyB;IAChE,CAAC,iBAAiB,CAAC,SAAS,CAAC,EAAE,iBAAiB;IAChD,CAAC,iBAAiB,CAAC,SAAS,CAAC,EAAE,iBAAiB;IAChD,CAAC,WAAW,CAAC,SAAS,CAAC,EAAE,WAAW;IACpC,CAAC,2BAA2B,CAAC,SAAS,CAAC,EAAE,2BAA2B;IACpE,CAAC,4BAA4B,CAAC,SAAS,CAAC,EAAE,4BAA4B;IACtE,CAAC,yBAAyB,CAAC,SAAS,CAAC,EAAE,yBAAyB;IAChE,CAAC,iBAAiB,CAAC,SAAS,CAAC,EAAE,iBAAiB;IAChD,CAAC,qBAAqB,CAAC,SAAS,CAAC,EAAE,qBAAqB;IACxD,CAAC,oBAAoB,CAAC,SAAS,CAAC,EAAE,oBAAoB;IACtD,CAAC,0BAA0B,CAAC,SAAS,CAAC,EAAE,0BAA0B;IAClE,CAAC,sBAAsB,CAAC,SAAS,CAAC,EAAE,sBAAsB;CACpD,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/authorize.d.ts b/dist/cjs/server/auth/handlers/authorize.d.ts deleted file mode 100644 index 38e9829bd2..0000000000 --- a/dist/cjs/server/auth/handlers/authorize.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { RequestHandler } from 'express'; -import { OAuthServerProvider } from '../provider.js'; -import { Options as RateLimitOptions } from 'express-rate-limit'; -export type AuthorizationHandlerOptions = { - provider: OAuthServerProvider; - /** - * Rate limiting configuration for the authorization endpoint. - * Set to false to disable rate limiting for this endpoint. - */ - rateLimit?: Partial | false; -}; -export declare function authorizationHandler({ provider, rateLimit: rateLimitConfig }: AuthorizationHandlerOptions): RequestHandler; -//# sourceMappingURL=authorize.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/authorize.d.ts.map b/dist/cjs/server/auth/handlers/authorize.d.ts.map deleted file mode 100644 index b067988349..0000000000 --- a/dist/cjs/server/auth/handlers/authorize.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"authorize.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/authorize.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAGzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,2BAA2B,GAAG;IACtC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAqBF,wBAAgB,oBAAoB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,2BAA2B,GAAG,cAAc,CAgH1H"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/authorize.js b/dist/cjs/server/auth/handlers/authorize.js deleted file mode 100644 index 9022082196..0000000000 --- a/dist/cjs/server/auth/handlers/authorize.js +++ /dev/null @@ -1,167 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.authorizationHandler = authorizationHandler; -const z = __importStar(require("zod/v4")); -const express_1 = __importDefault(require("express")); -const express_rate_limit_1 = require("express-rate-limit"); -const allowedMethods_js_1 = require("../middleware/allowedMethods.js"); -const errors_js_1 = require("../errors.js"); -// Parameters that must be validated in order to issue redirects. -const ClientAuthorizationParamsSchema = z.object({ - client_id: z.string(), - redirect_uri: z - .string() - .optional() - .refine(value => value === undefined || URL.canParse(value), { message: 'redirect_uri must be a valid URL' }) -}); -// Parameters that must be validated for a successful authorization request. Failure can be reported to the redirect URI. -const RequestAuthorizationParamsSchema = z.object({ - response_type: z.literal('code'), - code_challenge: z.string(), - code_challenge_method: z.literal('S256'), - scope: z.string().optional(), - state: z.string().optional(), - resource: z.string().url().optional() -}); -function authorizationHandler({ provider, rateLimit: rateLimitConfig }) { - // Create a router to apply middleware - const router = express_1.default.Router(); - router.use((0, allowedMethods_js_1.allowedMethods)(['GET', 'POST'])); - router.use(express_1.default.urlencoded({ extended: false })); - // Apply rate limiting unless explicitly disabled - if (rateLimitConfig !== false) { - router.use((0, express_rate_limit_1.rateLimit)({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 100, // 100 requests per windowMs - standardHeaders: true, - legacyHeaders: false, - message: new errors_js_1.TooManyRequestsError('You have exceeded the rate limit for authorization requests').toResponseObject(), - ...rateLimitConfig - })); - } - router.all('/', async (req, res) => { - res.setHeader('Cache-Control', 'no-store'); - // In the authorization flow, errors are split into two categories: - // 1. Pre-redirect errors (direct response with 400) - // 2. Post-redirect errors (redirect with error parameters) - // Phase 1: Validate client_id and redirect_uri. Any errors here must be direct responses. - let client_id, redirect_uri, client; - try { - const result = ClientAuthorizationParamsSchema.safeParse(req.method === 'POST' ? req.body : req.query); - if (!result.success) { - throw new errors_js_1.InvalidRequestError(result.error.message); - } - client_id = result.data.client_id; - redirect_uri = result.data.redirect_uri; - client = await provider.clientsStore.getClient(client_id); - if (!client) { - throw new errors_js_1.InvalidClientError('Invalid client_id'); - } - if (redirect_uri !== undefined) { - if (!client.redirect_uris.includes(redirect_uri)) { - throw new errors_js_1.InvalidRequestError('Unregistered redirect_uri'); - } - } - else if (client.redirect_uris.length === 1) { - redirect_uri = client.redirect_uris[0]; - } - else { - throw new errors_js_1.InvalidRequestError('redirect_uri must be specified when client has multiple registered URIs'); - } - } - catch (error) { - // Pre-redirect errors - return direct response - // - // These don't need to be JSON encoded, as they'll be displayed in a user - // agent, but OTOH they all represent exceptional situations (arguably, - // "programmer error"), so presenting a nice HTML page doesn't help the - // user anyway. - if (error instanceof errors_js_1.OAuthError) { - const status = error instanceof errors_js_1.ServerError ? 500 : 400; - res.status(status).json(error.toResponseObject()); - } - else { - const serverError = new errors_js_1.ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - return; - } - // Phase 2: Validate other parameters. Any errors here should go into redirect responses. - let state; - try { - // Parse and validate authorization parameters - const parseResult = RequestAuthorizationParamsSchema.safeParse(req.method === 'POST' ? req.body : req.query); - if (!parseResult.success) { - throw new errors_js_1.InvalidRequestError(parseResult.error.message); - } - const { scope, code_challenge, resource } = parseResult.data; - state = parseResult.data.state; - // Validate scopes - let requestedScopes = []; - if (scope !== undefined) { - requestedScopes = scope.split(' '); - } - // All validation passed, proceed with authorization - await provider.authorize(client, { - state, - scopes: requestedScopes, - redirectUri: redirect_uri, - codeChallenge: code_challenge, - resource: resource ? new URL(resource) : undefined - }, res); - } - catch (error) { - // Post-redirect errors - redirect with error parameters - if (error instanceof errors_js_1.OAuthError) { - res.redirect(302, createErrorRedirect(redirect_uri, error, state)); - } - else { - const serverError = new errors_js_1.ServerError('Internal Server Error'); - res.redirect(302, createErrorRedirect(redirect_uri, serverError, state)); - } - } - }); - return router; -} -/** - * Helper function to create redirect URL with error parameters - */ -function createErrorRedirect(redirectUri, error, state) { - const errorUrl = new URL(redirectUri); - errorUrl.searchParams.set('error', error.errorCode); - errorUrl.searchParams.set('error_description', error.message); - if (error.errorUri) { - errorUrl.searchParams.set('error_uri', error.errorUri); - } - if (state) { - errorUrl.searchParams.set('state', state); - } - return errorUrl.href; -} -//# sourceMappingURL=authorize.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/authorize.js.map b/dist/cjs/server/auth/handlers/authorize.js.map deleted file mode 100644 index 28e876271b..0000000000 --- a/dist/cjs/server/auth/handlers/authorize.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"authorize.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/authorize.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,oDAgHC;AAnJD,0CAA4B;AAC5B,sDAA8B;AAE9B,2DAA4E;AAC5E,uEAAiE;AACjE,4CAAsH;AAWtH,iEAAiE;AACjE,MAAM,+BAA+B,GAAG,CAAC,CAAC,MAAM,CAAC;IAC7C,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,YAAY,EAAE,CAAC;SACV,MAAM,EAAE;SACR,QAAQ,EAAE;SACV,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,KAAK,SAAS,IAAI,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,EAAE,OAAO,EAAE,kCAAkC,EAAE,CAAC;CACpH,CAAC,CAAC;AAEH,yHAAyH;AACzH,MAAM,gCAAgC,GAAG,CAAC,CAAC,MAAM,CAAC;IAC9C,aAAa,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC;IAChC,cAAc,EAAE,CAAC,CAAC,MAAM,EAAE;IAC1B,qBAAqB,EAAE,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC;IACxC,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC5B,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;IAC5B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wDAAwD;YACxD,IAAI,KAAK,YAAY,sBAAU,EAAE,CAAC;gBAC9B,GAAG,CAAC,QAAQ,CAAC,GAAG,EAAE,mBAAmB,CAAC,YAAY,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC;YACvE,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,uBAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,QAAQ,CAAC,GAAG,EAAE,mBAAmB,CAAC,YAAY,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC,CAAC;YAC7E,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;GAEG;AACH,SAAS,mBAAmB,CAAC,WAAmB,EAAE,KAAiB,EAAE,KAAc;IAC/E,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,WAAW,CAAC,CAAC;IACtC,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IACpD,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,mBAAmB,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;IAC9D,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;QACjB,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,WAAW,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC3D,CAAC;IACD,IAAI,KAAK,EAAE,CAAC;QACR,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC9C,CAAC;IACD,OAAO,QAAQ,CAAC,IAAI,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/metadata.d.ts b/dist/cjs/server/auth/handlers/metadata.d.ts deleted file mode 100644 index 4d03286170..0000000000 --- a/dist/cjs/server/auth/handlers/metadata.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { RequestHandler } from 'express'; -import { OAuthMetadata, OAuthProtectedResourceMetadata } from '../../../shared/auth.js'; -export declare function metadataHandler(metadata: OAuthMetadata | OAuthProtectedResourceMetadata): RequestHandler; -//# sourceMappingURL=metadata.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/metadata.d.ts.map b/dist/cjs/server/auth/handlers/metadata.d.ts.map deleted file mode 100644 index 55e3a50dc1..0000000000 --- a/dist/cjs/server/auth/handlers/metadata.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"metadata.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/metadata.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,8BAA8B,EAAE,MAAM,yBAAyB,CAAC;AAIxF,wBAAgB,eAAe,CAAC,QAAQ,EAAE,aAAa,GAAG,8BAA8B,GAAG,cAAc,CAaxG"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/metadata.js b/dist/cjs/server/auth/handlers/metadata.js deleted file mode 100644 index 4e00bc588e..0000000000 --- a/dist/cjs/server/auth/handlers/metadata.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.metadataHandler = metadataHandler; -const express_1 = __importDefault(require("express")); -const cors_1 = __importDefault(require("cors")); -const allowedMethods_js_1 = require("../middleware/allowedMethods.js"); -function metadataHandler(metadata) { - // Nested router so we can configure middleware and restrict HTTP method - const router = express_1.default.Router(); - // Configure CORS to allow any origin, to make accessible to web-based MCP clients - router.use((0, cors_1.default)()); - router.use((0, allowedMethods_js_1.allowedMethods)(['GET', 'OPTIONS'])); - router.get('/', (req, res) => { - res.status(200).json(metadata); - }); - return router; -} -//# sourceMappingURL=metadata.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/metadata.js.map b/dist/cjs/server/auth/handlers/metadata.js.map deleted file mode 100644 index 9679c9fa50..0000000000 --- a/dist/cjs/server/auth/handlers/metadata.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/metadata.ts"],"names":[],"mappings":";;;;;AAKA,0CAaC;AAlBD,sDAAkD;AAElD,gDAAwB;AACxB,uEAAiE;AAEjE,SAAgB,eAAe,CAAC,QAAwD;IACpF,wEAAwE;IACxE,MAAM,MAAM,GAAG,iBAAO,CAAC,MAAM,EAAE,CAAC;IAEhC,kFAAkF;IAClF,MAAM,CAAC,GAAG,CAAC,IAAA,cAAI,GAAE,CAAC,CAAC;IAEnB,MAAM,CAAC,GAAG,CAAC,IAAA,kCAAc,EAAC,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;IAC/C,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;QACzB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACnC,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/register.d.ts b/dist/cjs/server/auth/handlers/register.d.ts deleted file mode 100644 index e9add28458..0000000000 --- a/dist/cjs/server/auth/handlers/register.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { RequestHandler } from 'express'; -import { OAuthRegisteredClientsStore } from '../clients.js'; -import { Options as RateLimitOptions } from 'express-rate-limit'; -export type ClientRegistrationHandlerOptions = { - /** - * A store used to save information about dynamically registered OAuth clients. - */ - clientsStore: OAuthRegisteredClientsStore; - /** - * The number of seconds after which to expire issued client secrets, or 0 to prevent expiration of client secrets (not recommended). - * - * If not set, defaults to 30 days. - */ - clientSecretExpirySeconds?: number; - /** - * Rate limiting configuration for the client registration endpoint. - * Set to false to disable rate limiting for this endpoint. - * Registration endpoints are particularly sensitive to abuse and should be rate limited. - */ - rateLimit?: Partial | false; - /** - * Whether to generate a client ID before calling the client registration endpoint. - * - * If not set, defaults to true. - */ - clientIdGeneration?: boolean; -}; -export declare function clientRegistrationHandler({ clientsStore, clientSecretExpirySeconds, rateLimit: rateLimitConfig, clientIdGeneration }: ClientRegistrationHandlerOptions): RequestHandler; -//# sourceMappingURL=register.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/register.d.ts.map b/dist/cjs/server/auth/handlers/register.d.ts.map deleted file mode 100644 index a38ebdb89e..0000000000 --- a/dist/cjs/server/auth/handlers/register.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"register.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/register.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAIlD,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,gCAAgC,GAAG;IAC3C;;OAEG;IACH,YAAY,EAAE,2BAA2B,CAAC;IAE1C;;;;OAIG;IACH,yBAAyB,CAAC,EAAE,MAAM,CAAC;IAEnC;;;;OAIG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;IAE9C;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAChC,CAAC;AAIF,wBAAgB,yBAAyB,CAAC,EACtC,YAAY,EACZ,yBAAgE,EAChE,SAAS,EAAE,eAAe,EAC1B,kBAAyB,EAC5B,EAAE,gCAAgC,GAAG,cAAc,CA0EnD"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/register.js b/dist/cjs/server/auth/handlers/register.js deleted file mode 100644 index e40c5c904e..0000000000 --- a/dist/cjs/server/auth/handlers/register.js +++ /dev/null @@ -1,77 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.clientRegistrationHandler = clientRegistrationHandler; -const express_1 = __importDefault(require("express")); -const auth_js_1 = require("../../../shared/auth.js"); -const node_crypto_1 = __importDefault(require("node:crypto")); -const cors_1 = __importDefault(require("cors")); -const express_rate_limit_1 = require("express-rate-limit"); -const allowedMethods_js_1 = require("../middleware/allowedMethods.js"); -const errors_js_1 = require("../errors.js"); -const DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS = 30 * 24 * 60 * 60; // 30 days -function clientRegistrationHandler({ clientsStore, clientSecretExpirySeconds = DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS, rateLimit: rateLimitConfig, clientIdGeneration = true }) { - if (!clientsStore.registerClient) { - throw new Error('Client registration store does not support registering clients'); - } - // Nested router so we can configure middleware and restrict HTTP method - const router = express_1.default.Router(); - // Configure CORS to allow any origin, to make accessible to web-based MCP clients - router.use((0, cors_1.default)()); - router.use((0, allowedMethods_js_1.allowedMethods)(['POST'])); - router.use(express_1.default.json()); - // Apply rate limiting unless explicitly disabled - stricter limits for registration - if (rateLimitConfig !== false) { - router.use((0, express_rate_limit_1.rateLimit)({ - windowMs: 60 * 60 * 1000, // 1 hour - max: 20, // 20 requests per hour - stricter as registration is sensitive - standardHeaders: true, - legacyHeaders: false, - message: new errors_js_1.TooManyRequestsError('You have exceeded the rate limit for client registration requests').toResponseObject(), - ...rateLimitConfig - })); - } - router.post('/', async (req, res) => { - res.setHeader('Cache-Control', 'no-store'); - try { - const parseResult = auth_js_1.OAuthClientMetadataSchema.safeParse(req.body); - if (!parseResult.success) { - throw new errors_js_1.InvalidClientMetadataError(parseResult.error.message); - } - const clientMetadata = parseResult.data; - const isPublicClient = clientMetadata.token_endpoint_auth_method === 'none'; - // Generate client credentials - const clientSecret = isPublicClient ? undefined : node_crypto_1.default.randomBytes(32).toString('hex'); - const clientIdIssuedAt = Math.floor(Date.now() / 1000); - // Calculate client secret expiry time - const clientsDoExpire = clientSecretExpirySeconds > 0; - const secretExpiryTime = clientsDoExpire ? clientIdIssuedAt + clientSecretExpirySeconds : 0; - const clientSecretExpiresAt = isPublicClient ? undefined : secretExpiryTime; - let clientInfo = { - ...clientMetadata, - client_secret: clientSecret, - client_secret_expires_at: clientSecretExpiresAt - }; - if (clientIdGeneration) { - clientInfo.client_id = node_crypto_1.default.randomUUID(); - clientInfo.client_id_issued_at = clientIdIssuedAt; - } - clientInfo = await clientsStore.registerClient(clientInfo); - res.status(201).json(clientInfo); - } - catch (error) { - if (error instanceof errors_js_1.OAuthError) { - const status = error instanceof errors_js_1.ServerError ? 500 : 400; - res.status(status).json(error.toResponseObject()); - } - else { - const serverError = new errors_js_1.ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - } - }); - return router; -} -//# sourceMappingURL=register.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/register.js.map b/dist/cjs/server/auth/handlers/register.js.map deleted file mode 100644 index e116a474fd..0000000000 --- a/dist/cjs/server/auth/handlers/register.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"register.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/register.ts"],"names":[],"mappings":";;;;;AAuCA,8DA+EC;AAtHD,sDAAkD;AAClD,qDAAgG;AAChG,8DAAiC;AACjC,gDAAwB;AAExB,2DAA4E;AAC5E,uEAAiE;AACjE,4CAAyG;AA8BzG,MAAM,oCAAoC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,UAAU;AAE1E,SAAgB,yBAAyB,CAAC,EACtC,YAAY,EACZ,yBAAyB,GAAG,oCAAoC,EAChE,SAAS,EAAE,eAAe,EAC1B,kBAAkB,GAAG,IAAI,EACM;IAC/B,IAAI,CAAC,YAAY,CAAC,cAAc,EAAE,CAAC;QAC/B,MAA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gBACJ,MAAM,WAAW,GAAG,IAAI,uBAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/revoke.d.ts b/dist/cjs/server/auth/handlers/revoke.d.ts deleted file mode 100644 index 2be32bb3ca..0000000000 --- a/dist/cjs/server/auth/handlers/revoke.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { OAuthServerProvider } from '../provider.js'; -import { RequestHandler } from 'express'; -import { Options as RateLimitOptions } from 'express-rate-limit'; -export type RevocationHandlerOptions = { - provider: OAuthServerProvider; - /** - * Rate limiting configuration for the token revocation endpoint. - * Set to false to disable rate limiting for this endpoint. - */ - rateLimit?: Partial | false; -}; -export declare function revocationHandler({ provider, rateLimit: rateLimitConfig }: RevocationHandlerOptions): RequestHandler; -//# sourceMappingURL=revoke.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/revoke.d.ts.map b/dist/cjs/server/auth/handlers/revoke.d.ts.map deleted file mode 100644 index fb13cf19fe..0000000000 --- a/dist/cjs/server/auth/handlers/revoke.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"revoke.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/revoke.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAIlD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,wBAAwB,GAAG;IACnC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAEF,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,wBAAwB,GAAG,cAAc,CA4DpH"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/revoke.js b/dist/cjs/server/auth/handlers/revoke.js deleted file mode 100644 index 4fb1da738a..0000000000 --- a/dist/cjs/server/auth/handlers/revoke.js +++ /dev/null @@ -1,65 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.revocationHandler = revocationHandler; -const express_1 = __importDefault(require("express")); -const cors_1 = __importDefault(require("cors")); -const clientAuth_js_1 = require("../middleware/clientAuth.js"); -const auth_js_1 = require("../../../shared/auth.js"); -const express_rate_limit_1 = require("express-rate-limit"); -const allowedMethods_js_1 = require("../middleware/allowedMethods.js"); -const errors_js_1 = require("../errors.js"); -function revocationHandler({ provider, rateLimit: rateLimitConfig }) { - if (!provider.revokeToken) { - throw new Error('Auth provider does not support revoking tokens'); - } - // Nested router so we can configure middleware and restrict HTTP method - const router = express_1.default.Router(); - // Configure CORS to allow any origin, to make accessible to web-based MCP clients - router.use((0, cors_1.default)()); - router.use((0, allowedMethods_js_1.allowedMethods)(['POST'])); - router.use(express_1.default.urlencoded({ extended: false })); - // Apply rate limiting unless explicitly disabled - if (rateLimitConfig !== false) { - router.use((0, express_rate_limit_1.rateLimit)({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 50, // 50 requests per windowMs - standardHeaders: true, - legacyHeaders: false, - message: new errors_js_1.TooManyRequestsError('You have exceeded the rate limit for token revocation requests').toResponseObject(), - ...rateLimitConfig - })); - } - // Authenticate and extract client details - router.use((0, clientAuth_js_1.authenticateClient)({ clientsStore: provider.clientsStore })); - router.post('/', async (req, res) => { - res.setHeader('Cache-Control', 'no-store'); - try { - const parseResult = auth_js_1.OAuthTokenRevocationRequestSchema.safeParse(req.body); - if (!parseResult.success) { - throw new errors_js_1.InvalidRequestError(parseResult.error.message); - } - const client = req.client; - if (!client) { - // This should never happen - throw new errors_js_1.ServerError('Internal Server Error'); - } - await provider.revokeToken(client, parseResult.data); - res.status(200).json({}); - } - catch (error) { - if (error instanceof errors_js_1.OAuthError) { - const status = error instanceof errors_js_1.ServerError ? 500 : 400; - res.status(status).json(error.toResponseObject()); - } - else { - const serverError = new errors_js_1.ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - } - }); - return router; -} -//# sourceMappingURL=revoke.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/revoke.js.map b/dist/cjs/server/auth/handlers/revoke.js.map deleted file mode 100644 index ca01fee7f5..0000000000 --- a/dist/cjs/server/auth/handlers/revoke.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"revoke.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/revoke.ts"],"names":[],"mappings":";;;;;AAkBA,8CA4DC;AA7ED,sDAAkD;AAClD,gDAAwB;AACxB,+DAAiE;AACjE,qDAA4E;AAC5E,2DAA4E;AAC5E,uEAAiE;AACjE,4CAAkG;AAWlG,SAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAA4B;IAChG,IAAI,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC;QACxB,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;IACtE,CAAC;IAED,wEAAwE;IACxE,MAAM,MAAM,GAAG,iBAAO,CAAC,MAAM,EAAE,CAAC;IAEhC,kFAAkF;IAClF,MAAM,CAAC,GAAG,CAAC,IAAA,cAAI,GAAE,CAAC,CAAC;IAEnB,MAAM,CAAC,GAAG,CAAC,IAAA,kCAAc,EAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACrC,MAAM,CAAC,GAAG,CAAC,iBAAO,CAAC,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,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC7B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,KAAK,YAAY,sBAAU,EAAE,CAAC;gBAC9B,MAAM,MAAM,GAAG,KAAK,YAAY,uBAAW,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;gBACxD,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,uBAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/token.d.ts b/dist/cjs/server/auth/handlers/token.d.ts deleted file mode 100644 index 24d1c8783b..0000000000 --- a/dist/cjs/server/auth/handlers/token.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { RequestHandler } from 'express'; -import { OAuthServerProvider } from '../provider.js'; -import { Options as RateLimitOptions } from 'express-rate-limit'; -export type TokenHandlerOptions = { - provider: OAuthServerProvider; - /** - * Rate limiting configuration for the token endpoint. - * Set to false to disable rate limiting for this endpoint. - */ - rateLimit?: Partial | false; -}; -export declare function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHandlerOptions): RequestHandler; -//# sourceMappingURL=token.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/token.d.ts.map b/dist/cjs/server/auth/handlers/token.d.ts.map deleted file mode 100644 index 3d539f3451..0000000000 --- a/dist/cjs/server/auth/handlers/token.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/token.ts"],"names":[],"mappings":"AACA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAIrD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAW5E,MAAM,MAAM,mBAAmB,GAAG;IAC9B,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAmBF,wBAAgB,YAAY,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,mBAAmB,GAAG,cAAc,CAiH1G"} \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/token.js b/dist/cjs/server/auth/handlers/token.js deleted file mode 100644 index c88bb294f8..0000000000 --- a/dist/cjs/server/auth/handlers/token.js +++ /dev/null @@ -1,136 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.tokenHandler = tokenHandler; -const z = __importStar(require("zod/v4")); -const express_1 = __importDefault(require("express")); -const cors_1 = __importDefault(require("cors")); -const pkce_challenge_1 = require("pkce-challenge"); -const clientAuth_js_1 = require("../middleware/clientAuth.js"); -const express_rate_limit_1 = require("express-rate-limit"); -const allowedMethods_js_1 = require("../middleware/allowedMethods.js"); -const errors_js_1 = require("../errors.js"); -const TokenRequestSchema = z.object({ - grant_type: z.string() -}); -const AuthorizationCodeGrantSchema = z.object({ - code: z.string(), - code_verifier: z.string(), - redirect_uri: z.string().optional(), - resource: z.string().url().optional() -}); -const RefreshTokenGrantSchema = z.object({ - refresh_token: z.string(), - scope: z.string().optional(), - resource: z.string().url().optional() -}); -function tokenHandler({ provider, rateLimit: rateLimitConfig }) { - // Nested router so we can configure middleware and restrict HTTP method - const router = express_1.default.Router(); - // Configure CORS to allow any origin, to make accessible to web-based MCP clients - router.use((0, cors_1.default)()); - router.use((0, allowedMethods_js_1.allowedMethods)(['POST'])); - router.use(express_1.default.urlencoded({ extended: false })); - // Apply rate limiting unless explicitly disabled - if (rateLimitConfig !== false) { - router.use((0, express_rate_limit_1.rateLimit)({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 50, // 50 requests per windowMs - standardHeaders: true, - legacyHeaders: false, - message: new errors_js_1.TooManyRequestsError('You have exceeded the rate limit for token requests').toResponseObject(), - ...rateLimitConfig - })); - } - // Authenticate and extract client details - router.use((0, clientAuth_js_1.authenticateClient)({ clientsStore: provider.clientsStore })); - router.post('/', async (req, res) => { - res.setHeader('Cache-Control', 'no-store'); - try { - const parseResult = TokenRequestSchema.safeParse(req.body); - if (!parseResult.success) { - throw new errors_js_1.InvalidRequestError(parseResult.error.message); - } - const { grant_type } = parseResult.data; - const client = req.client; - if (!client) { - // This should never happen - throw new errors_js_1.ServerError('Internal Server Error'); - } - switch (grant_type) { - case 'authorization_code': { - const parseResult = AuthorizationCodeGrantSchema.safeParse(req.body); - if (!parseResult.success) { - throw new errors_js_1.InvalidRequestError(parseResult.error.message); - } - const { code, code_verifier, redirect_uri, resource } = parseResult.data; - const skipLocalPkceValidation = provider.skipLocalPkceValidation; - // Perform local PKCE validation unless explicitly skipped - // (e.g. to validate code_verifier in upstream server) - if (!skipLocalPkceValidation) { - const codeChallenge = await provider.challengeForAuthorizationCode(client, code); - if (!(await (0, pkce_challenge_1.verifyChallenge)(code_verifier, codeChallenge))) { - throw new errors_js_1.InvalidGrantError('code_verifier does not match the challenge'); - } - } - // Passes the code_verifier to the provider if PKCE validation didn't occur locally - const tokens = await provider.exchangeAuthorizationCode(client, code, skipLocalPkceValidation ? code_verifier : undefined, redirect_uri, resource ? new URL(resource) : undefined); - res.status(200).json(tokens); - break; - } - case 'refresh_token': { - const parseResult = RefreshTokenGrantSchema.safeParse(req.body); - if (!parseResult.success) { - throw new errors_js_1.InvalidRequestError(parseResult.error.message); - } - const { refresh_token, scope, resource } = parseResult.data; - const scopes = scope === null || scope === void 0 ? void 0 : scope.split(' '); - const tokens = await provider.exchangeRefreshToken(client, refresh_token, scopes, resource ? new URL(resource) : undefined); - res.status(200).json(tokens); - break; - } - // Not supported right now - //case "client_credentials": - default: - throw new errors_js_1.UnsupportedGrantTypeError('The grant type is not supported by this authorization server.'); - } - } - catch (error) { - if (error instanceof errors_js_1.OAuthError) { - const status = error instanceof errors_js_1.ServerError ? 500 : 400; - res.status(status).json(error.toResponseObject()); - } - else { - const serverError = new errors_js_1.ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - } - }); - return router; -} -//# sourceMappingURL=token.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/handlers/token.js.map b/dist/cjs/server/auth/handlers/token.js.map deleted file mode 100644 index 4ca53c5bc4..0000000000 --- a/dist/cjs/server/auth/handlers/token.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"token.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/token.ts"],"names":[],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th/middleware/allowedMethods.d.ts b/dist/cjs/server/auth/middleware/allowedMethods.d.ts deleted file mode 100644 index ee6037e0de..0000000000 --- a/dist/cjs/server/auth/middleware/allowedMethods.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { RequestHandler } from 'express'; -/** - * Middleware to handle unsupported HTTP methods with a 405 Method Not Allowed response. - * - * @param allowedMethods Array of allowed HTTP methods for this endpoint (e.g., ['GET', 'POST']) - * @returns Express middleware that returns a 405 error if method not in allowed list - */ -export declare function allowedMethods(allowedMethods: string[]): RequestHandler; -//# sourceMappingURL=allowedMethods.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/allowedMethods.d.ts.map b/dist/cjs/server/auth/middleware/allowedMethods.d.ts.map deleted file mode 100644 index d3de93e242..0000000000 --- a/dist/cjs/server/auth/middleware/allowedMethods.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"allowedMethods.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/allowedMethods.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAGzC;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,cAAc,EAAE,MAAM,EAAE,GAAG,cAAc,CAUvE"} \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/allowedMethods.js b/dist/cjs/server/auth/middleware/allowedMethods.js deleted file mode 100644 index f445537458..0000000000 --- a/dist/cjs/server/auth/middleware/allowedMethods.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.allowedMethods = allowedMethods; -const errors_js_1 = require("../errors.js"); -/** - * Middleware to handle unsupported HTTP methods with a 405 Method Not Allowed response. - * - * @param allowedMethods Array of allowed HTTP methods for this endpoint (e.g., ['GET', 'POST']) - * @returns Express middleware that returns a 405 error if method not in allowed list - */ -function allowedMethods(allowedMethods) { - return (req, res, next) => { - if (allowedMethods.includes(req.method)) { - next(); - return; - } - const error = new errors_js_1.MethodNotAllowedError(`The method ${req.method} is not allowed for this endpoint`); - res.status(405).set('Allow', allowedMethods.join(', ')).json(error.toResponseObject()); - }; -} -//# sourceMappingURL=allowedMethods.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/allowedMethods.js.map b/dist/cjs/server/auth/middleware/allowedMethods.js.map deleted file mode 100644 index be69f33771..0000000000 --- a/dist/cjs/server/auth/middleware/allowedMethods.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"allowedMethods.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/allowedMethods.ts"],"names":[],"mappings":";;AASA,wCAUC;AAlBD,4CAAqD;AAErD;;;;;GAKG;AACH,SAAgB,cAAc,CAAC,cAAwB;IACnD,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACtB,IAAI,cAAc,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;YACtC,IAAI,EAAE,CAAC;YACP,OAAO;QACX,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,iCAAqB,CAAC,cAAc,GAAG,CAAC,MAAM,mCAAmC,CAAC,CAAC;QACrG,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;IAC3F,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/bearerAuth.d.ts b/dist/cjs/server/auth/middleware/bearerAuth.d.ts deleted file mode 100644 index 10730758bc..0000000000 --- a/dist/cjs/server/auth/middleware/bearerAuth.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { RequestHandler } from 'express'; -import { OAuthTokenVerifier } from '../provider.js'; -import { AuthInfo } from '../types.js'; -export type BearerAuthMiddlewareOptions = { - /** - * A provider used to verify tokens. - */ - verifier: OAuthTokenVerifier; - /** - * Optional scopes that the token must have. - */ - requiredScopes?: string[]; - /** - * Optional resource metadata URL to include in WWW-Authenticate header. - */ - resourceMetadataUrl?: string; -}; -declare module 'express-serve-static-core' { - interface Request { - /** - * Information about the validated access token, if the `requireBearerAuth` middleware was used. - */ - auth?: AuthInfo; - } -} -/** - * Middleware that requires a valid Bearer token in the Authorization header. - * - * This will validate the token with the auth provider and add the resulting auth info to the request object. - * - * If resourceMetadataUrl is provided, it will be included in the WWW-Authenticate header - * for 401 responses as per the OAuth 2.0 Protected Resource Metadata spec. - */ -export declare function requireBearerAuth({ verifier, requiredScopes, resourceMetadataUrl }: BearerAuthMiddlewareOptions): RequestHandler; -//# sourceMappingURL=bearerAuth.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/bearerAuth.d.ts.map b/dist/cjs/server/auth/middleware/bearerAuth.d.ts.map deleted file mode 100644 index c9d939f3b7..0000000000 --- a/dist/cjs/server/auth/middleware/bearerAuth.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bearerAuth.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/bearerAuth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,MAAM,MAAM,2BAA2B,GAAG;IACtC;;OAEG;IACH,QAAQ,EAAE,kBAAkB,CAAC;IAE7B;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAE1B;;OAEG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAChC,CAAC;AAEF,OAAO,QAAQ,2BAA2B,CAAC;IACvC,UAAU,OAAO;QACb;;WAEG;QACH,IAAI,CAAC,EAAE,QAAQ,CAAC;KACnB;CACJ;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,cAAmB,EAAE,mBAAmB,EAAE,EAAE,2BAA2B,GAAG,cAAc,CA8DrI"} \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/bearerAuth.js b/dist/cjs/server/auth/middleware/bearerAuth.js deleted file mode 100644 index dcfc509356..0000000000 --- a/dist/cjs/server/auth/middleware/bearerAuth.js +++ /dev/null @@ -1,75 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.requireBearerAuth = requireBearerAuth; -const errors_js_1 = require("../errors.js"); -/** - * Middleware that requires a valid Bearer token in the Authorization header. - * - * This will validate the token with the auth provider and add the resulting auth info to the request object. - * - * If resourceMetadataUrl is provided, it will be included in the WWW-Authenticate header - * for 401 responses as per the OAuth 2.0 Protected Resource Metadata spec. - */ -function requireBearerAuth({ verifier, requiredScopes = [], resourceMetadataUrl }) { - return async (req, res, next) => { - try { - const authHeader = req.headers.authorization; - if (!authHeader) { - throw new errors_js_1.InvalidTokenError('Missing Authorization header'); - } - const [type, token] = authHeader.split(' '); - if (type.toLowerCase() !== 'bearer' || !token) { - throw new errors_js_1.InvalidTokenError("Invalid Authorization header format, expected 'Bearer TOKEN'"); - } - const authInfo = await verifier.verifyAccessToken(token); - // Check if token has the required scopes (if any) - if (requiredScopes.length > 0) { - const hasAllScopes = requiredScopes.every(scope => authInfo.scopes.includes(scope)); - if (!hasAllScopes) { - throw new errors_js_1.InsufficientScopeError('Insufficient scope'); - } - } - // Check if the token is set to expire or if it is expired - if (typeof authInfo.expiresAt !== 'number' || isNaN(authInfo.expiresAt)) { - throw new errors_js_1.InvalidTokenError('Token has no expiration time'); - } - else if (authInfo.expiresAt < Date.now() / 1000) { - throw new errors_js_1.InvalidTokenError('Token has expired'); - } - req.auth = authInfo; - next(); - } - catch (error) { - // Build WWW-Authenticate header parts - const buildWwwAuthHeader = (errorCode, message) => { - let header = `Bearer error="${errorCode}", error_description="${message}"`; - if (requiredScopes.length > 0) { - header += `, scope="${requiredScopes.join(' ')}"`; - } - if (resourceMetadataUrl) { - header += `, resource_metadata="${resourceMetadataUrl}"`; - } - return header; - }; - if (error instanceof errors_js_1.InvalidTokenError) { - res.set('WWW-Authenticate', buildWwwAuthHeader(error.errorCode, error.message)); - res.status(401).json(error.toResponseObject()); - } - else if (error instanceof errors_js_1.InsufficientScopeError) { - res.set('WWW-Authenticate', buildWwwAuthHeader(error.errorCode, error.message)); - res.status(403).json(error.toResponseObject()); - } - else if (error instanceof errors_js_1.ServerError) { - res.status(500).json(error.toResponseObject()); - } - else if (error instanceof errors_js_1.OAuthError) { - res.status(400).json(error.toResponseObject()); - } - else { - const serverError = new errors_js_1.ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - } - }; -} -//# sourceMappingURL=bearerAuth.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/bearerAuth.js.map b/dist/cjs/server/auth/middleware/bearerAuth.js.map deleted file mode 100644 index d111d36bf8..0000000000 --- a/dist/cjs/server/auth/middleware/bearerAuth.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bearerAuth.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/bearerAuth.ts"],"names":[],"mappings":";;AAuCA,8CA8DC;AApGD,4CAAkG;AA8BlG;;;;;;;GAOG;AACH,SAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,cAAc,GAAG,EAAE,EAAE,mBAAmB,EAA+B;IACjH,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC5B,IAAI,CAAC;YACD,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,aAAa,CAAC;YAC7C,IAAI,CAAC,UAAU,EAAE,CAAC;gBACd,MAAM,IAAI,6BAAiB,CAAC,8BAA8B,CAAC,CAAC;YAChE,CAAC;YAED,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,C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,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/clientAuth.d.ts b/dist/cjs/server/auth/middleware/clientAuth.d.ts deleted file mode 100644 index 837f95fd29..0000000000 --- a/dist/cjs/server/auth/middleware/clientAuth.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { RequestHandler } from 'express'; -import { OAuthRegisteredClientsStore } from '../clients.js'; -import { OAuthClientInformationFull } from '../../../shared/auth.js'; -export type ClientAuthenticationMiddlewareOptions = { - /** - * A store used to read information about registered OAuth clients. - */ - clientsStore: OAuthRegisteredClientsStore; -}; -declare module 'express-serve-static-core' { - interface Request { - /** - * The authenticated client for this request, if the `authenticateClient` middleware was used. - */ - client?: OAuthClientInformationFull; - } -} -export declare function authenticateClient({ clientsStore }: ClientAuthenticationMiddlewareOptions): RequestHandler; -//# sourceMappingURL=clientAuth.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/clientAuth.d.ts.map b/dist/cjs/server/auth/middleware/clientAuth.d.ts.map deleted file mode 100644 index 5dfa3924f2..0000000000 --- a/dist/cjs/server/auth/middleware/clientAuth.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"clientAuth.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/clientAuth.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AAGrE,MAAM,MAAM,qCAAqC,GAAG;IAChD;;OAEG;IACH,YAAY,EAAE,2BAA2B,CAAC;CAC7C,CAAC;AAOF,OAAO,QAAQ,2BAA2B,CAAC;IACvC,UAAU,OAAO;QACb;;WAEG;QACH,MAAM,CAAC,EAAE,0BAA0B,CAAC;KACvC;CACJ;AAED,wBAAgB,kBAAkB,CAAC,EAAE,YAAY,EAAE,EAAE,qCAAqC,GAAG,cAAc,CA4C1G"} \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/clientAuth.js b/dist/cjs/server/auth/middleware/clientAuth.js deleted file mode 100644 index 2c3732ff8f..0000000000 --- a/dist/cjs/server/auth/middleware/clientAuth.js +++ /dev/null @@ -1,75 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.authenticateClient = authenticateClient; -const z = __importStar(require("zod/v4")); -const errors_js_1 = require("../errors.js"); -const ClientAuthenticatedRequestSchema = z.object({ - client_id: z.string(), - client_secret: z.string().optional() -}); -function authenticateClient({ clientsStore }) { - return async (req, res, next) => { - try { - const result = ClientAuthenticatedRequestSchema.safeParse(req.body); - if (!result.success) { - throw new errors_js_1.InvalidRequestError(String(result.error)); - } - const { client_id, client_secret } = result.data; - const client = await clientsStore.getClient(client_id); - if (!client) { - throw new errors_js_1.InvalidClientError('Invalid client_id'); - } - // If client has a secret, validate it - if (client.client_secret) { - // Check if client_secret is required but not provided - if (!client_secret) { - throw new errors_js_1.InvalidClientError('Client secret is required'); - } - // Check if client_secret matches - if (client.client_secret !== client_secret) { - throw new errors_js_1.InvalidClientError('Invalid client_secret'); - } - // Check if client_secret has expired - if (client.client_secret_expires_at && client.client_secret_expires_at < Math.floor(Date.now() / 1000)) { - throw new errors_js_1.InvalidClientError('Client secret has expired'); - } - } - req.client = client; - next(); - } - catch (error) { - if (error instanceof errors_js_1.OAuthError) { - const status = error instanceof errors_js_1.ServerError ? 500 : 400; - res.status(status).json(error.toResponseObject()); - } - else { - const serverError = new errors_js_1.ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - } - }; -} -//# sourceMappingURL=clientAuth.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/middleware/clientAuth.js.map b/dist/cjs/server/auth/middleware/clientAuth.js.map deleted file mode 100644 index 862ba692e8..0000000000 --- a/dist/cjs/server/auth/middleware/clientAuth.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"clientAuth.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/clientAuth.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,gDA4CC;AAvED,0CAA4B;AAI5B,4CAAgG;AAShG,MAAM,gCAAgC,GAAG,CAAC,CAAC,MAAM,CAAC;IAC9C,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE;IACrB,aAAa,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACvC,CAAC,CAAC;AAWH,SAAgB,kBAAkB,CAAC,EAAE,YAAY,EAAyC;IACtF,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC5B,IAAI,CAAC;YACD,MAAM,MAAM,GAAG,gCAAgC,CAAC,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YACpE,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;gBAClB,MAAM,IAAI,+BAAmB,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;YACxD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AAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/provider.d.ts b/dist/cjs/server/auth/provider.d.ts deleted file mode 100644 index 3e4eca392c..0000000000 --- a/dist/cjs/server/auth/provider.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { Response } from 'express'; -import { OAuthRegisteredClientsStore } from './clients.js'; -import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../shared/auth.js'; -import { AuthInfo } from './types.js'; -export type AuthorizationParams = { - state?: string; - scopes?: string[]; - codeChallenge: string; - redirectUri: string; - resource?: URL; -}; -/** - * Implements an end-to-end OAuth server. - */ -export interface OAuthServerProvider { - /** - * A store used to read information about registered OAuth clients. - */ - get clientsStore(): OAuthRegisteredClientsStore; - /** - * Begins the authorization flow, which can either be implemented by this server itself or via redirection to a separate authorization server. - * - * This server must eventually issue a redirect with an authorization response or an error response to the given redirect URI. Per OAuth 2.1: - * - In the successful case, the redirect MUST include the `code` and `state` (if present) query parameters. - * - In the error case, the redirect MUST include the `error` query parameter, and MAY include an optional `error_description` query parameter. - */ - authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; - /** - * Returns the `codeChallenge` that was used when the indicated authorization began. - */ - challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise; - /** - * Exchanges an authorization code for an access token. - */ - exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, redirectUri?: string, resource?: URL): Promise; - /** - * Exchanges a refresh token for an access token. - */ - exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; - /** - * Verifies an access token and returns information about it. - */ - verifyAccessToken(token: string): Promise; - /** - * Revokes an access or refresh token. If unimplemented, token revocation is not supported (not recommended). - * - * If the given token is invalid or already revoked, this method should do nothing. - */ - revokeToken?(client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest): Promise; - /** - * Whether to skip local PKCE validation. - * - * If true, the server will not perform PKCE validation locally and will pass the code_verifier to the upstream server. - * - * NOTE: This should only be true if the upstream server is performing the actual PKCE validation. - */ - skipLocalPkceValidation?: boolean; -} -/** - * Slim implementation useful for token verification - */ -export interface OAuthTokenVerifier { - /** - * Verifies an access token and returns information about it. - */ - verifyAccessToken(token: string): Promise; -} -//# sourceMappingURL=provider.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/provider.d.ts.map b/dist/cjs/server/auth/provider.d.ts.map deleted file mode 100644 index d1a4bfff0b..0000000000 --- a/dist/cjs/server/auth/provider.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,2BAA2B,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC5G,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAEtC,MAAM,MAAM,mBAAmB,GAAG;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,GAAG,CAAC;CAClB,CAAC;AAEF;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAChC;;OAEG;IACH,IAAI,YAAY,IAAI,2BAA2B,CAAC;IAEhD;;;;;;OAMG;IACH,SAAS,CAAC,MAAM,EAAE,0BAA0B,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEzG;;OAEG;IACH,6BAA6B,CAAC,MAAM,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAE9G;;OAEG;IACH,yBAAyB,CACrB,MAAM,EAAE,0BAA0B,EAClC,iBAAiB,EAAE,MAAM,EACzB,YAAY,CAAC,EAAE,MAAM,EACrB,WAAW,CAAC,EAAE,MAAM,EACpB,QAAQ,CAAC,EAAE,GAAG,GACf,OAAO,CAAC,WAAW,CAAC,CAAC;IAExB;;OAEG;IACH,oBAAoB,CAAC,MAAM,EAAE,0BAA0B,EAAE,YAAY,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,EAAE,EAAE,QAAQ,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IAExI;;OAEG;IACH,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;IAEpD;;;;OAIG;IACH,WAAW,CAAC,CAAC,MAAM,EAAE,0BAA0B,EAAE,OAAO,EAAE,2BAA2B,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEtG;;;;;;OAMG;IACH,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACrC;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IAC/B;;OAEG;IACH,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CACvD"} \ No newline at end of file diff --git a/dist/cjs/server/auth/provider.js b/dist/cjs/server/auth/provider.js deleted file mode 100644 index 0903bb2eff..0000000000 --- a/dist/cjs/server/auth/provider.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -//# sourceMappingURL=provider.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/provider.js.map b/dist/cjs/server/auth/provider.js.map deleted file mode 100644 index b968414aa9..0000000000 --- a/dist/cjs/server/auth/provider.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../../src/server/auth/provider.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/server/auth/providers/proxyProvider.d.ts b/dist/cjs/server/auth/providers/proxyProvider.d.ts deleted file mode 100644 index ee6f350817..0000000000 --- a/dist/cjs/server/auth/providers/proxyProvider.d.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Response } from 'express'; -import { OAuthRegisteredClientsStore } from '../clients.js'; -import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../../shared/auth.js'; -import { AuthInfo } from '../types.js'; -import { AuthorizationParams, OAuthServerProvider } from '../provider.js'; -import { FetchLike } from '../../../shared/transport.js'; -export type ProxyEndpoints = { - authorizationUrl: string; - tokenUrl: string; - revocationUrl?: string; - registrationUrl?: string; -}; -export type ProxyOptions = { - /** - * Individual endpoint URLs for proxying specific OAuth operations - */ - endpoints: ProxyEndpoints; - /** - * Function to verify access tokens and return auth info - */ - verifyAccessToken: (token: string) => Promise; - /** - * Function to fetch client information from the upstream server - */ - getClient: (clientId: string) => Promise; - /** - * Custom fetch implementation used for all network requests. - */ - fetch?: FetchLike; -}; -/** - * Implements an OAuth server that proxies requests to another OAuth server. - */ -export declare class ProxyOAuthServerProvider implements OAuthServerProvider { - protected readonly _endpoints: ProxyEndpoints; - protected readonly _verifyAccessToken: (token: string) => Promise; - protected readonly _getClient: (clientId: string) => Promise; - protected readonly _fetch?: FetchLike; - skipLocalPkceValidation: boolean; - revokeToken?: (client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest) => Promise; - constructor(options: ProxyOptions); - get clientsStore(): OAuthRegisteredClientsStore; - authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; - challengeForAuthorizationCode(_client: OAuthClientInformationFull, _authorizationCode: string): Promise; - exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, redirectUri?: string, resource?: URL): Promise; - exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; - verifyAccessToken(token: string): Promise; -} -//# sourceMappingURL=proxyProvider.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/providers/proxyProvider.d.ts.map b/dist/cjs/server/auth/providers/proxyProvider.d.ts.map deleted file mode 100644 index ba2efd1aab..0000000000 --- a/dist/cjs/server/auth/providers/proxyProvider.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"proxyProvider.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/providers/proxyProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EACH,0BAA0B,EAE1B,2BAA2B,EAC3B,WAAW,EAEd,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE1E,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAEzD,MAAM,MAAM,cAAc,GAAG;IACzB,gBAAgB,EAAE,MAAM,CAAC;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,eAAe,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACvB;;OAEG;IACH,SAAS,EAAE,cAAc,CAAC;IAE1B;;OAEG;IACH,iBAAiB,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;IAExD;;OAEG;IACH,SAAS,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,0BAA0B,GAAG,SAAS,CAAC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AAW,CAAC;IAmCjB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;CAG5D"} \ No newline at end of file diff --git a/dist/cjs/server/auth/providers/proxyProvider.js b/dist/cjs/server/auth/providers/proxyProvider.js deleted file mode 100644 index 51bd2a9c21..0000000000 --- a/dist/cjs/server/auth/providers/proxyProvider.js +++ /dev/null @@ -1,161 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ProxyOAuthServerProvider = void 0; -const auth_js_1 = require("../../../shared/auth.js"); -const errors_js_1 = require("../errors.js"); -/** - * Implements an OAuth server that proxies requests to another OAuth server. - */ -class ProxyOAuthServerProvider { - constructor(options) { - var _a; - this.skipLocalPkceValidation = true; - this._endpoints = options.endpoints; - this._verifyAccessToken = options.verifyAccessToken; - this._getClient = options.getClient; - this._fetch = options.fetch; - if ((_a = options.endpoints) === null || _a === void 0 ? void 0 : _a.revocationUrl) { - this.revokeToken = async (client, request) => { - var _a; - const revocationUrl = this._endpoints.revocationUrl; - if (!revocationUrl) { - throw new Error('No revocation endpoint configured'); - } - const params = new URLSearchParams(); - params.set('token', request.token); - params.set('client_id', client.client_id); - if (client.client_secret) { - params.set('client_secret', client.client_secret); - } - if (request.token_type_hint) { - params.set('token_type_hint', request.token_type_hint); - } - const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(revocationUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: params.toString() - }); - if (!response.ok) { - throw new errors_js_1.ServerError(`Token revocation failed: ${response.status}`); - } - }; - } - } - get clientsStore() { - const registrationUrl = this._endpoints.registrationUrl; - return { - getClient: this._getClient, - ...(registrationUrl && { - registerClient: async (client) => { - var _a; - const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(registrationUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(client) - }); - if (!response.ok) { - throw new errors_js_1.ServerError(`Client registration failed: ${response.status}`); - } - const data = await response.json(); - return auth_js_1.OAuthClientInformationFullSchema.parse(data); - } - }) - }; - } - async authorize(client, params, res) { - var _a; - // Start with required OAuth parameters - const targetUrl = new URL(this._endpoints.authorizationUrl); - const searchParams = new URLSearchParams({ - client_id: client.client_id, - response_type: 'code', - redirect_uri: params.redirectUri, - code_challenge: params.codeChallenge, - code_challenge_method: 'S256' - }); - // Add optional standard OAuth parameters - if (params.state) - searchParams.set('state', params.state); - if ((_a = params.scopes) === null || _a === void 0 ? void 0 : _a.length) - searchParams.set('scope', params.scopes.join(' ')); - if (params.resource) - searchParams.set('resource', params.resource.href); - targetUrl.search = searchParams.toString(); - res.redirect(targetUrl.toString()); - } - async challengeForAuthorizationCode(_client, _authorizationCode) { - // In a proxy setup, we don't store the code challenge ourselves - // Instead, we proxy the token request and let the upstream server validate it - return ''; - } - async exchangeAuthorizationCode(client, authorizationCode, codeVerifier, redirectUri, resource) { - var _a; - const params = new URLSearchParams({ - grant_type: 'authorization_code', - client_id: client.client_id, - code: authorizationCode - }); - if (client.client_secret) { - params.append('client_secret', client.client_secret); - } - if (codeVerifier) { - params.append('code_verifier', codeVerifier); - } - if (redirectUri) { - params.append('redirect_uri', redirectUri); - } - if (resource) { - params.append('resource', resource.href); - } - const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(this._endpoints.tokenUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: params.toString() - }); - if (!response.ok) { - throw new errors_js_1.ServerError(`Token exchange failed: ${response.status}`); - } - const data = await response.json(); - return auth_js_1.OAuthTokensSchema.parse(data); - } - async exchangeRefreshToken(client, refreshToken, scopes, resource) { - var _a; - const params = new URLSearchParams({ - grant_type: 'refresh_token', - client_id: client.client_id, - refresh_token: refreshToken - }); - if (client.client_secret) { - params.set('client_secret', client.client_secret); - } - if (scopes === null || scopes === void 0 ? void 0 : scopes.length) { - params.set('scope', scopes.join(' ')); - } - if (resource) { - params.set('resource', resource.href); - } - const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(this._endpoints.tokenUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: params.toString() - }); - if (!response.ok) { - throw new errors_js_1.ServerError(`Token refresh failed: ${response.status}`); - } - const data = await response.json(); - return auth_js_1.OAuthTokensSchema.parse(data); - } - async verifyAccessToken(token) { - return this._verifyAccessToken(token); - } -} -exports.ProxyOAuthServerProvider = ProxyOAuthServerProvider; -//# sourceMappingURL=proxyProvider.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/providers/proxyProvider.js.map b/dist/cjs/server/auth/providers/proxyProvider.js.map deleted file mode 100644 index dd33760a83..0000000000 --- a/dist/cjs/server/auth/providers/proxyProvider.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"proxyProvider.js","sourceRoot":"","sources":["../../../../../src/server/auth/providers/proxyProvider.ts"],"names":[],"mappings":";;;AAEA,qDAMiC;AAGjC,4CAA2C;AAgC3C;;GAEG;AACH,MAAa,wBAAwB;IAUjC,YAAY,OAAqB;;QAJjC,4BAAuB,GAAG,IAAI,CAAC;QAK3B,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC;QACpC,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,iBAAiB,CAAC;QACpD,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC;QACpC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC;QAC5B,IAAI,MAAA,OAAO,CAAC,SAAS,0CAAE,aAAa,EAAE,CAAC;YACnC,IAAI,CAAC,WAAW,GAAG,KAAK,EAAE,MAAkC,EAAE,OAAoC,EAAE,EAAE;;gBAClG,MAAM,aAAa,GAAG,IAAI,CAAC,UAAU,CAAC,aAAa,CAAC;gBAEpD,IAAI,CAAC,aAAa,EAAE,CAAC;oBACjB,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC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C;QACtE,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,OAAO,2BAAiB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACzC,CAAC;IAED,KAAK,CAAC,iBAAiB,CAAC,KAAa;QACjC,OAAO,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;CACJ;AA3LD,4DA2LC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/router.d.ts b/dist/cjs/server/auth/router.d.ts deleted file mode 100644 index 43dabde7d2..0000000000 --- a/dist/cjs/server/auth/router.d.ts +++ /dev/null @@ -1,101 +0,0 @@ -import express, { RequestHandler } from 'express'; -import { ClientRegistrationHandlerOptions } from './handlers/register.js'; -import { TokenHandlerOptions } from './handlers/token.js'; -import { AuthorizationHandlerOptions } from './handlers/authorize.js'; -import { RevocationHandlerOptions } from './handlers/revoke.js'; -import { OAuthServerProvider } from './provider.js'; -import { OAuthMetadata } from '../../shared/auth.js'; -export type AuthRouterOptions = { - /** - * A provider implementing the actual authorization logic for this router. - */ - provider: OAuthServerProvider; - /** - * The authorization server's issuer identifier, which is a URL that uses the "https" scheme and has no query or fragment components. - */ - issuerUrl: URL; - /** - * The base URL of the authorization server to use for the metadata endpoints. - * - * If not provided, the issuer URL will be used as the base URL. - */ - baseUrl?: URL; - /** - * An optional URL of a page containing human-readable information that developers might want or need to know when using the authorization server. - */ - serviceDocumentationUrl?: URL; - /** - * An optional list of scopes supported by this authorization server - */ - scopesSupported?: string[]; - /** - * The resource name to be displayed in protected resource metadata - */ - resourceName?: string; - /** - * The URL of the protected resource (RS) whose metadata we advertise. - * If not provided, falls back to `baseUrl` and then to `issuerUrl` (AS=RS). - */ - resourceServerUrl?: URL; - authorizationOptions?: Omit; - clientRegistrationOptions?: Omit; - revocationOptions?: Omit; - tokenOptions?: Omit; -}; -export declare const createOAuthMetadata: (options: { - provider: OAuthServerProvider; - issuerUrl: URL; - baseUrl?: URL; - serviceDocumentationUrl?: URL; - scopesSupported?: string[]; -}) => OAuthMetadata; -/** - * Installs standard MCP authorization server endpoints, including dynamic client registration and token revocation (if supported). - * Also advertises standard authorization server metadata, for easier discovery of supported configurations by clients. - * Note: if your MCP server is only a resource server and not an authorization server, use mcpAuthMetadataRouter instead. - * - * By default, rate limiting is applied to all endpoints to prevent abuse. - * - * This router MUST be installed at the application root, like so: - * - * const app = express(); - * app.use(mcpAuthRouter(...)); - */ -export declare function mcpAuthRouter(options: AuthRouterOptions): RequestHandler; -export type AuthMetadataOptions = { - /** - * OAuth Metadata as would be returned from the authorization server - * this MCP server relies on - */ - oauthMetadata: OAuthMetadata; - /** - * The url of the MCP server, for use in protected resource metadata - */ - resourceServerUrl: URL; - /** - * The url for documentation for the MCP server - */ - serviceDocumentationUrl?: URL; - /** - * An optional list of scopes supported by this MCP server - */ - scopesSupported?: string[]; - /** - * An optional resource name to display in resource metadata - */ - resourceName?: string; -}; -export declare function mcpAuthMetadataRouter(options: AuthMetadataOptions): express.Router; -/** - * Helper function to construct the OAuth 2.0 Protected Resource Metadata URL - * from a given server URL. This replaces the path with the standard metadata endpoint. - * - * @param serverUrl - The base URL of the protected resource server - * @returns The URL for the OAuth protected resource metadata endpoint - * - * @example - * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) - * // Returns: 'https://api.example.com/.well-known/oauth-protected-resource/mcp' - */ -export declare function getOAuthProtectedResourceMetadataUrl(serverUrl: URL): string; -//# sourceMappingURL=router.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/router.d.ts.map b/dist/cjs/server/auth/router.d.ts.map deleted file mode 100644 index 54e90be267..0000000000 --- a/dist/cjs/server/auth/router.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/router.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,EAAE,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAA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F;;;;;;;;;;;GAWG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,iBAAiB,GAAG,cAAc,CAyCxE;AAED,MAAM,MAAM,mBAAmB,GAAG;IAC9B;;;OAGG;IACH,aAAa,EAAE,aAAa,CAAC;IAE7B;;OAEG;IACH,iBAAiB,EAAE,GAAG,CAAC;IAEvB;;OAEG;IACH,uBAAuB,CAAC,EAAE,GAAG,CAAC;IAE9B;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAE3B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,MAAM,CAuBlF;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,oCAAoC,CAAC,SAAS,EAAE,GAAG,GAAG,MAAM,CAI3E"} \ No newline at end of file diff --git a/dist/cjs/server/auth/router.js b/dist/cjs/server/auth/router.js deleted file mode 100644 index 66b037f65d..0000000000 --- a/dist/cjs/server/auth/router.js +++ /dev/null @@ -1,125 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createOAuthMetadata = void 0; -exports.mcpAuthRouter = mcpAuthRouter; -exports.mcpAuthMetadataRouter = mcpAuthMetadataRouter; -exports.getOAuthProtectedResourceMetadataUrl = getOAuthProtectedResourceMetadataUrl; -const express_1 = __importDefault(require("express")); -const register_js_1 = require("./handlers/register.js"); -const token_js_1 = require("./handlers/token.js"); -const authorize_js_1 = require("./handlers/authorize.js"); -const revoke_js_1 = require("./handlers/revoke.js"); -const metadata_js_1 = require("./handlers/metadata.js"); -const checkIssuerUrl = (issuer) => { - // Technically RFC 8414 does not permit a localhost HTTPS exemption, but this will be necessary for ease of testing - if (issuer.protocol !== 'https:' && issuer.hostname !== 'localhost' && issuer.hostname !== '127.0.0.1') { - throw new Error('Issuer URL must be HTTPS'); - } - if (issuer.hash) { - throw new Error(`Issuer URL must not have a fragment: ${issuer}`); - } - if (issuer.search) { - throw new Error(`Issuer URL must not have a query string: ${issuer}`); - } -}; -const createOAuthMetadata = (options) => { - var _a; - const issuer = options.issuerUrl; - const baseUrl = options.baseUrl; - checkIssuerUrl(issuer); - const authorization_endpoint = '/authorize'; - const token_endpoint = '/token'; - const registration_endpoint = options.provider.clientsStore.registerClient ? '/register' : undefined; - const revocation_endpoint = options.provider.revokeToken ? '/revoke' : undefined; - const metadata = { - issuer: issuer.href, - service_documentation: (_a = options.serviceDocumentationUrl) === null || _a === void 0 ? void 0 : _a.href, - authorization_endpoint: new URL(authorization_endpoint, baseUrl || issuer).href, - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'], - token_endpoint: new URL(token_endpoint, baseUrl || issuer).href, - token_endpoint_auth_methods_supported: ['client_secret_post', 'none'], - grant_types_supported: ['authorization_code', 'refresh_token'], - scopes_supported: options.scopesSupported, - revocation_endpoint: revocation_endpoint ? new URL(revocation_endpoint, baseUrl || issuer).href : undefined, - revocation_endpoint_auth_methods_supported: revocation_endpoint ? ['client_secret_post'] : undefined, - registration_endpoint: registration_endpoint ? new URL(registration_endpoint, baseUrl || issuer).href : undefined - }; - return metadata; -}; -exports.createOAuthMetadata = createOAuthMetadata; -/** - * Installs standard MCP authorization server endpoints, including dynamic client registration and token revocation (if supported). - * Also advertises standard authorization server metadata, for easier discovery of supported configurations by clients. - * Note: if your MCP server is only a resource server and not an authorization server, use mcpAuthMetadataRouter instead. - * - * By default, rate limiting is applied to all endpoints to prevent abuse. - * - * This router MUST be installed at the application root, like so: - * - * const app = express(); - * app.use(mcpAuthRouter(...)); - */ -function mcpAuthRouter(options) { - var _a, _b; - const oauthMetadata = (0, exports.createOAuthMetadata)(options); - const router = express_1.default.Router(); - router.use(new URL(oauthMetadata.authorization_endpoint).pathname, (0, authorize_js_1.authorizationHandler)({ provider: options.provider, ...options.authorizationOptions })); - router.use(new URL(oauthMetadata.token_endpoint).pathname, (0, token_js_1.tokenHandler)({ provider: options.provider, ...options.tokenOptions })); - router.use(mcpAuthMetadataRouter({ - oauthMetadata, - // Prefer explicit RS; otherwise fall back to AS baseUrl, then to issuer (back-compat) - resourceServerUrl: (_b = (_a = options.resourceServerUrl) !== null && _a !== void 0 ? _a : options.baseUrl) !== null && _b !== void 0 ? _b : new URL(oauthMetadata.issuer), - serviceDocumentationUrl: options.serviceDocumentationUrl, - scopesSupported: options.scopesSupported, - resourceName: options.resourceName - })); - if (oauthMetadata.registration_endpoint) { - router.use(new URL(oauthMetadata.registration_endpoint).pathname, (0, register_js_1.clientRegistrationHandler)({ - clientsStore: options.provider.clientsStore, - ...options.clientRegistrationOptions - })); - } - if (oauthMetadata.revocation_endpoint) { - router.use(new URL(oauthMetadata.revocation_endpoint).pathname, (0, revoke_js_1.revocationHandler)({ provider: options.provider, ...options.revocationOptions })); - } - return router; -} -function mcpAuthMetadataRouter(options) { - var _a; - checkIssuerUrl(new URL(options.oauthMetadata.issuer)); - const router = express_1.default.Router(); - const protectedResourceMetadata = { - resource: options.resourceServerUrl.href, - authorization_servers: [options.oauthMetadata.issuer], - scopes_supported: options.scopesSupported, - resource_name: options.resourceName, - resource_documentation: (_a = options.serviceDocumentationUrl) === null || _a === void 0 ? void 0 : _a.href - }; - // Serve PRM at the path-specific URL per RFC 9728 - const rsPath = new URL(options.resourceServerUrl.href).pathname; - router.use(`/.well-known/oauth-protected-resource${rsPath === '/' ? '' : rsPath}`, (0, metadata_js_1.metadataHandler)(protectedResourceMetadata)); - // Always add this for OAuth Authorization Server metadata per RFC 8414 - router.use('/.well-known/oauth-authorization-server', (0, metadata_js_1.metadataHandler)(options.oauthMetadata)); - return router; -} -/** - * Helper function to construct the OAuth 2.0 Protected Resource Metadata URL - * from a given server URL. This replaces the path with the standard metadata endpoint. - * - * @param serverUrl - The base URL of the protected resource server - * @returns The URL for the OAuth protected resource metadata endpoint - * - * @example - * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) - * // Returns: 'https://api.example.com/.well-known/oauth-protected-resource/mcp' - */ -function getOAuthProtectedResourceMetadataUrl(serverUrl) { - const u = new URL(serverUrl.href); - const rsPath = u.pathname && u.pathname !== '/' ? u.pathname : ''; - return new URL(`/.well-known/oauth-protected-resource${rsPath}`, u).href; -} -//# sourceMappingURL=router.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/router.js.map b/dist/cjs/server/auth/router.js.map deleted file mode 100644 index 3c813c7ae5..0000000000 --- a/dist/cjs/server/auth/router.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"router.js","sourceRoot":"","sources":["../../../../src/server/auth/router.ts"],"names":[],"mappings":";;;;;;AAwHA,sCAyCC;AA8BD,sDAuBC;AAaD,oFAIC;AAvOD,sDAAkD;AAClD,wDAAqG;AACrG,kDAAwE;AACxE,0DAA4F;AAC5F,oDAAmF;AACnF,wDAAyD;AAkDzD,MAAM,cAAc,GAAG,CAAC,MAAW,EAAQ,EAAE;IACzC,mHAAmH;IACnH,IAAI,MAAM,CAAC,QAAQ,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,KAAK,WAAW,IAAI,MAAM,CAAC,QAAQ,KAAK,WAAW,EAAE,CAAC;QACrG,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;IAChD,CAAC;IACD,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;QACd,MAAM,IAAI,KAAK,CAAC,wCAAwC,MAAM,EAAE,CAAC,CAAC;IACtE,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,4CAA4C,MAAM,EAAE,CAAC,CAAC;IAC1E,CAAC;AACL,CAAC,CAAC;AAEK,MAAM,mBAAmB,GAAG,CAAC,OAMnC,EAAiB,EAAE;;IAChB,MAAM,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC;IACjC,MAAM,OAAO,GAAG,OAA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AAC,CAAC,CAAC;IAE9F,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;;;;;;;;;GAUG;AACH,SAAgB,oCAAoC,CAAC,SAAc;IAC/D,MAAM,CAAC,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IAClC,MAAM,MAAM,GAAG,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,QAAQ,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC;IAClE,OAAO,IAAI,GAAG,CAAC,wCAAwC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAC7E,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/types.d.ts b/dist/cjs/server/auth/types.d.ts deleted file mode 100644 index 05ec8485a5..0000000000 --- a/dist/cjs/server/auth/types.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Information about a validated access token, provided to request handlers. - */ -export interface AuthInfo { - /** - * The access token. - */ - token: string; - /** - * The client ID associated with this token. - */ - clientId: string; - /** - * Scopes associated with this token. - */ - scopes: string[]; - /** - * When the token expires (in seconds since epoch). - */ - expiresAt?: number; - /** - * The RFC 8707 resource server identifier for which this token is valid. - * If set, this MUST match the MCP server's resource identifier (minus hash fragment). - */ - resource?: URL; - /** - * Additional data associated with the token. - * This field should be used for any additional data that needs to be attached to the auth info. - */ - extra?: Record; -} -//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/auth/types.d.ts.map b/dist/cjs/server/auth/types.d.ts.map deleted file mode 100644 index 021e947401..0000000000 --- a/dist/cjs/server/auth/types.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,QAAQ;IACrB;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,MAAM,EAAE,MAAM,EAAE,CAAC;IAEjB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,QAAQ,CAAC,EAAE,GAAG,CAAC;IAEf;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC"} \ No newline at end of file diff --git a/dist/cjs/server/auth/types.js b/dist/cjs/server/auth/types.js deleted file mode 100644 index 11e638d1ee..0000000000 --- a/dist/cjs/server/auth/types.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/cjs/server/auth/types.js.map b/dist/cjs/server/auth/types.js.map deleted file mode 100644 index 0d8063dee4..0000000000 --- a/dist/cjs/server/auth/types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/server/auth/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/cjs/server/completable.d.ts b/dist/cjs/server/completable.d.ts deleted file mode 100644 index 1b3159ac8f..0000000000 --- a/dist/cjs/server/completable.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { AnySchema, SchemaInput } from './zod-compat.js'; -export declare const COMPLETABLE_SYMBOL: unique symbol; -export type CompleteCallback = (value: SchemaInput, context?: { - arguments?: Record; -}) => SchemaInput[] | Promise[]>; -export type CompletableMeta = { - complete: CompleteCallback; -}; -export type CompletableSchema = T & { - [COMPLETABLE_SYMBOL]: CompletableMeta; -}; -/** - * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. - * Works with both Zod v3 and v4 schemas. - */ -export declare function completable(schema: T, complete: CompleteCallback): CompletableSchema; -/** - * Checks if a schema is completable (has completion metadata). - */ -export declare function isCompletable(schema: unknown): schema is CompletableSchema; -/** - * Gets the completer callback from a completable schema, if it exists. - */ -export declare function getCompleter(schema: T): CompleteCallback | undefined; -/** - * Unwraps a completable schema to get the underlying schema. - * For backward compatibility with code that called `.unwrap()`. - */ -export declare function unwrapCompletable(schema: CompletableSchema): T; -export declare enum McpZodTypeKind { - Completable = "McpCompletable" -} -export interface CompletableDef { - type: T; - complete: CompleteCallback; - typeName: McpZodTypeKind.Completable; -} -//# sourceMappingURL=completable.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/completable.d.ts.map b/dist/cjs/server/completable.d.ts.map deleted file mode 100644 index 83ea2f1e27..0000000000 --- a/dist/cjs/server/completable.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"completable.d.ts","sourceRoot":"","sources":["../../../src/server/completable.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEzD,eAAO,MAAM,kBAAkB,EAAE,OAAO,MAAsC,CAAC;AAE/E,MAAM,MAAM,gBAAgB,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS,IAAI,CAC5D,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,EACrB,OAAO,CAAC,EAAE;IACN,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACtC,KACA,WAAW,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;AAElD,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS,IAAI;IAC3D,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC;CACjC,CAAC;AAEF,MAAM,MAAM,iBAAiB,CAAC,CAAC,SAAS,SAAS,IAAI,CAAC,GAAG;IACrD,CAAC,kBAAkB,CAAC,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC;CAC5C,CAAC;AAEF;;;GAGG;AACH,wBAAgB,WAAW,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,CAAC,EAAE,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAQ/G;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,IAAI,iBAAiB,CAAC,SAAS,CAAC,CAErF;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,CAAC,GAAG,gBAAgB,CAAC,CAAC,CAAC,GAAG,SAAS,CAG5F;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,CAAC,CAEtF;AAID,oBAAY,cAAc;IACtB,WAAW,mBAAmB;CACjC;AAED,MAAM,WAAW,cAAc,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS;IAC3D,IAAI,EAAE,CAAC,CAAC;IACR,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC;IAC9B,QAAQ,EAAE,cAAc,CAAC,WAAW,CAAC;CACxC"} \ No newline at end of file diff --git a/dist/cjs/server/completable.js b/dist/cjs/server/completable.js deleted file mode 100644 index cfddaeba48..0000000000 --- a/dist/cjs/server/completable.js +++ /dev/null @@ -1,48 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.McpZodTypeKind = exports.COMPLETABLE_SYMBOL = void 0; -exports.completable = completable; -exports.isCompletable = isCompletable; -exports.getCompleter = getCompleter; -exports.unwrapCompletable = unwrapCompletable; -exports.COMPLETABLE_SYMBOL = Symbol.for('mcp.completable'); -/** - * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. - * Works with both Zod v3 and v4 schemas. - */ -function completable(schema, complete) { - Object.defineProperty(schema, exports.COMPLETABLE_SYMBOL, { - value: { complete }, - enumerable: false, - writable: false, - configurable: false - }); - return schema; -} -/** - * Checks if a schema is completable (has completion metadata). - */ -function isCompletable(schema) { - return !!schema && typeof schema === 'object' && exports.COMPLETABLE_SYMBOL in schema; -} -/** - * Gets the completer callback from a completable schema, if it exists. - */ -function getCompleter(schema) { - const meta = schema[exports.COMPLETABLE_SYMBOL]; - return meta === null || meta === void 0 ? void 0 : meta.complete; -} -/** - * Unwraps a completable schema to get the underlying schema. - * For backward compatibility with code that called `.unwrap()`. - */ -function unwrapCompletable(schema) { - return schema; -} -// Legacy exports for backward compatibility -// These types are deprecated but kept for existing code -var McpZodTypeKind; -(function (McpZodTypeKind) { - McpZodTypeKind["Completable"] = "McpCompletable"; -})(McpZodTypeKind || (exports.McpZodTypeKind = McpZodTypeKind = {})); -//# sourceMappingURL=completable.js.map \ No newline at end of file diff --git a/dist/cjs/server/completable.js.map b/dist/cjs/server/completable.js.map deleted file mode 100644 index 728e58bdce..0000000000 --- a/dist/cjs/server/completable.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"completable.js","sourceRoot":"","sources":["../../../src/server/completable.ts"],"names":[],"mappings":";;;AAuBA,kCAQC;AAKD,sCAEC;AAKD,oCAGC;AAMD,8CAEC;AApDY,QAAA,kBAAkB,GAAkB,MAAM,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;AAiB/E;;;GAGG;AACH,SAAgB,WAAW,CAAsB,MAAS,EAAE,QAA6B;IACrF,MAAM,CAAC,cAAc,CAAC,MAAgB,EAAE,0BAAkB,EAAE;QACxD,KAAK,EAAE,EAAE,QAAQ,EAAwB;QACzC,UAAU,EAAE,KAAK;QACjB,QAAQ,EAAE,KAAK;QACf,YAAY,EAAE,KAAK;KACtB,CAAC,CAAC;IACH,OAAO,MAA8B,CAAC;AAC1C,CAAC;AAED;;GAEG;AACH,SAAgB,aAAa,CAAC,MAAe;IACzC,OAAO,CAAC,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,0BAAkB,IAAK,MAAiB,CAAC;AAC9F,CAAC;AAED;;GAEG;AACH,SAAgB,YAAY,CAAsB,MAAS;IACvD,MAAM,IAAI,GAAI,MAAmE,CAAC,0BAAkB,CAAC,CAAC;IACtG,OAAO,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,QAA2C,CAAC;AAC7D,CAAC;AAED;;;GAGG;AACH,SAAgB,iBAAiB,CAAsB,MAA4B;IAC/E,OAAO,MAAM,CAAC;AAClB,CAAC;AAED,4CAA4C;AAC5C,wDAAwD;AACxD,IAAY,cAEX;AAFD,WAAY,cAAc;IACtB,gDAA8B,CAAA;AAClC,CAAC,EAFW,cAAc,8BAAd,cAAc,QAEzB"} \ No newline at end of file diff --git a/dist/cjs/server/index.d.ts b/dist/cjs/server/index.d.ts deleted file mode 100644 index 8aabf3c536..0000000000 --- a/dist/cjs/server/index.d.ts +++ /dev/null @@ -1,333 +0,0 @@ -import { Protocol, type NotificationOptions, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; -import { type ClientCapabilities, type CreateMessageRequest, type ElicitRequestFormParams, type ElicitRequestURLParams, type ElicitResult, type Implementation, type ListRootsRequest, type LoggingMessageNotification, type Notification, type Request, type ResourceUpdatedNotification, type Result, type ServerCapabilities, type ServerNotification, type ServerRequest, type ServerResult } from '../types.js'; -import type { jsonSchemaValidator } from '../validation/types.js'; -type LegacyElicitRequestFormParams = Omit; -export type ServerOptions = ProtocolOptions & { - /** - * Capabilities to advertise as being supported by this server. - */ - capabilities?: ServerCapabilities; - /** - * Optional instructions describing how to use the server and its features. - */ - instructions?: string; - /** - * JSON Schema validator for elicitation response validation. - * - * The validator is used to validate user input returned from elicitation - * requests against the requested schema. - * - * @default AjvJsonSchemaValidator - * - * @example - * ```typescript - * // ajv (default) - * const server = new Server( - * { name: 'my-server', version: '1.0.0' }, - * { - * capabilities: {} - * jsonSchemaValidator: new AjvJsonSchemaValidator() - * } - * ); - * - * // @cfworker/json-schema - * const server = new Server( - * { name: 'my-server', version: '1.0.0' }, - * { - * capabilities: {}, - * jsonSchemaValidator: new CfWorkerJsonSchemaValidator() - * } - * ); - * ``` - */ - jsonSchemaValidator?: jsonSchemaValidator; -}; -/** - * An MCP server on top of a pluggable transport. - * - * This server will automatically respond to the initialization flow as initiated from the client. - * - * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: - * - * ```typescript - * // Custom schemas - * const CustomRequestSchema = RequestSchema.extend({...}) - * const CustomNotificationSchema = NotificationSchema.extend({...}) - * const CustomResultSchema = ResultSchema.extend({...}) - * - * // Type aliases - * type CustomRequest = z.infer - * type CustomNotification = z.infer - * type CustomResult = z.infer - * - * // Create typed server - * const server = new Server({ - * name: "CustomServer", - * version: "1.0.0" - * }) - * ``` - * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. - */ -export declare class Server extends Protocol { - private _serverInfo; - private _clientCapabilities?; - private _clientVersion?; - private _capabilities; - private _instructions?; - private _jsonSchemaValidator; - /** - * Callback for when initialization has fully completed (i.e., the client has sent an `initialized` notification). - */ - oninitialized?: () => void; - /** - * Initializes this server with the given name and version information. - */ - constructor(_serverInfo: Implementation, options?: ServerOptions); - private _loggingLevels; - private readonly LOG_LEVEL_SEVERITY; - private isMessageIgnored; - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - registerCapabilities(capabilities: ServerCapabilities): void; - protected assertCapabilityForMethod(method: RequestT['method']): void; - protected assertNotificationCapability(method: (ServerNotification | NotificationT)['method']): void; - protected assertRequestHandlerCapability(method: string): void; - private _oninitialize; - /** - * After initialization has completed, this will be populated with the client's reported capabilities. - */ - getClientCapabilities(): ClientCapabilities | undefined; - /** - * After initialization has completed, this will be populated with information about the client's name and version. - */ - getClientVersion(): Implementation | undefined; - private getCapabilities; - ping(): Promise<{ - _meta?: Record | undefined; - }>; - createMessage(params: CreateMessageRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - model: string; - role: "user" | "assistant"; - content: { - type: "text"; - text: string; - _meta?: Record | undefined; - } | { - type: "image"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "audio"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - [x: string]: unknown; - type: "tool_use"; - name: string; - id: string; - input: { - [x: string]: unknown; - }; - _meta?: { - [x: string]: unknown; - } | undefined; - } | { - [x: string]: unknown; - type: "tool_result"; - toolUseId: string; - content: ({ - type: "text"; - text: string; - _meta?: Record | undefined; - } | { - type: "image"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "audio"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "resource"; - resource: { - uri: string; - text: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - } | { - uri: string; - blob: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - }; - _meta?: Record | undefined; - } | { - uri: string; - name: string; - type: "resource_link"; - description?: string | undefined; - mimeType?: string | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - })[]; - structuredContent?: { - [x: string]: unknown; - } | undefined; - isError?: boolean | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - } | ({ - type: "text"; - text: string; - _meta?: Record | undefined; - } | { - type: "image"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "audio"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - [x: string]: unknown; - type: "tool_use"; - name: string; - id: string; - input: { - [x: string]: unknown; - }; - _meta?: { - [x: string]: unknown; - } | undefined; - } | { - [x: string]: unknown; - type: "tool_result"; - toolUseId: string; - content: ({ - type: "text"; - text: string; - _meta?: Record | undefined; - } | { - type: "image"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "audio"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "resource"; - resource: { - uri: string; - text: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - } | { - uri: string; - blob: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - }; - _meta?: Record | undefined; - } | { - uri: string; - name: string; - type: "resource_link"; - description?: string | undefined; - mimeType?: string | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - })[]; - structuredContent?: { - [x: string]: unknown; - } | undefined; - isError?: boolean | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - })[]; - _meta?: Record | undefined; - stopReason?: string | undefined; - }>; - /** - * Creates an elicitation request for the given parameters. - * @param params The parameters for the form elicitation request (explicit mode: 'form'). - * @param options Optional request options. - * @returns The result of the elicitation request. - */ - elicitInput(params: ElicitRequestFormParams, options?: RequestOptions): Promise; - /** - * Creates an elicitation request for the given parameters. - * @param params The parameters for the URL elicitation request (with url and elicitationId). - * @param options Optional request options. - * @returns The result of the elicitation request. - */ - elicitInput(params: ElicitRequestURLParams, options?: RequestOptions): Promise; - /** - * Creates an elicitation request for the given parameters. - * @deprecated Use the overloads with explicit `mode: 'form' | 'url'` instead. - * @param params The parameters for the form elicitation request (legacy signature without mode). - * @param options Optional request options. - * @returns The result of the elicitation request. - */ - elicitInput(params: LegacyElicitRequestFormParams, options?: RequestOptions): Promise; - /** - * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` - * notification for the specified elicitation ID. - * - * @param elicitationId The ID of the elicitation to mark as complete. - * @param options Optional notification options. Useful when the completion notification should be related to a prior request. - * @returns A function that emits the completion notification when awaited. - */ - createElicitationCompletionNotifier(elicitationId: string, options?: NotificationOptions): () => Promise; - listRoots(params?: ListRootsRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - roots: { - uri: string; - name?: string | undefined; - _meta?: Record | undefined; - }[]; - _meta?: Record | undefined; - }>; - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON RPC message - * @see LoggingMessageNotification - * @param params - * @param sessionId optional for stateless and backward compatibility - */ - sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string): Promise; - sendResourceUpdated(params: ResourceUpdatedNotification['params']): Promise; - sendResourceListChanged(): Promise; - sendToolListChanged(): Promise; - sendPromptListChanged(): Promise; -} -export {}; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/index.d.ts.map b/dist/cjs/server/index.d.ts.map deleted file mode 100644 index 4b8cc1c0a0..0000000000 --- a/dist/cjs/server/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAAE,KAAK,mBAAmB,EAAE,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACzI,OAAO,EACH,KAAK,kBAAkB,EACvB,KAAK,oBAAoB,EAEzB,KAAK,uBAAuB,EAC5B,KAAK,sBAAsB,EAC3B,KAAK,YAAY,EAIjB,KAAK,cAAc,EAMnB,KAAK,gBAAgB,EAIrB,KAAK,0BAA0B,EAE/B,KAAK,YAAY,EACjB,KAAK,OAAO,EACZ,KAAK,2BAA2B,EAChC,KAAK,MAAM,EACX,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,YAAY,EAGpB,MAAM,aAAa,CAAC;AAErB,OAAO,KAAK,EAAkB,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAElF,KAAK,6BAA6B,GAAG,IAAI,CAAC,uBAAuB,EAAE,MAAM,CAAC,CAAC;AAE3E,MAAM,MAAM,aAAa,GAAG,eAAe,GAAG;IAC1C;;OAEG;IACH,YAAY,CAAC,EAAE,kBAAkB,CAAC;IAElC;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACH,mBAAmB,CAAC,EAAE,mBAAmB,CAAC;CAC7C,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;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,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAIpF;;;;;OAKG;IACG,WAAW,CAAC,MAAM,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC;IACnG;;;;;OAKG;IACG,WAAW,CAAC,MAAM,EAAE,sBAAsB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC;IAClG;;;;;;OAMG;IACG,WAAW,CAAC,MAAM,EAAE,6BAA6B,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC;IAuDzG;;;;;;;OAOG;IACH,mCAAmC,CAAC,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC;IAiBxG,SAAS,CAAC,MAAM,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;IAI7E;;;;;;OAMG;IACG,kBAAkB,CAAC,MAAM,EAAE,0BAA0B,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC,EAAE,MAAM;IAQnF,mBAAmB,CAAC,MAAM,EAAE,2BAA2B,CAAC,QAAQ,CAAC;IAOjE,uBAAuB;IAMvB,mBAAmB;IAInB,qBAAqB;CAG9B"} \ No newline at end of file diff --git a/dist/cjs/server/index.js b/dist/cjs/server/index.js deleted file mode 100644 index 4658ed28e8..0000000000 --- a/dist/cjs/server/index.js +++ /dev/null @@ -1,304 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Server = void 0; -const protocol_js_1 = require("../shared/protocol.js"); -const types_js_1 = require("../types.js"); -const ajv_provider_js_1 = require("../validation/ajv-provider.js"); -/** - * An MCP server on top of a pluggable transport. - * - * This server will automatically respond to the initialization flow as initiated from the client. - * - * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: - * - * ```typescript - * // Custom schemas - * const CustomRequestSchema = RequestSchema.extend({...}) - * const CustomNotificationSchema = NotificationSchema.extend({...}) - * const CustomResultSchema = ResultSchema.extend({...}) - * - * // Type aliases - * type CustomRequest = z.infer - * type CustomNotification = z.infer - * type CustomResult = z.infer - * - * // Create typed server - * const server = new Server({ - * name: "CustomServer", - * version: "1.0.0" - * }) - * ``` - * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. - */ -class Server extends protocol_js_1.Protocol { - /** - * Initializes this server with the given name and version information. - */ - constructor(_serverInfo, options) { - var _a, _b; - super(options); - this._serverInfo = _serverInfo; - // Map log levels by session id - this._loggingLevels = new Map(); - // Map LogLevelSchema to severity index - this.LOG_LEVEL_SEVERITY = new Map(types_js_1.LoggingLevelSchema.options.map((level, index) => [level, index])); - // Is a message with the given level ignored in the log level set for the given session id? - this.isMessageIgnored = (level, sessionId) => { - const currentLevel = this._loggingLevels.get(sessionId); - return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; - }; - this._capabilities = (_a = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a !== void 0 ? _a : {}; - this._instructions = options === null || options === void 0 ? void 0 : options.instructions; - this._jsonSchemaValidator = (_b = options === null || options === void 0 ? void 0 : options.jsonSchemaValidator) !== null && _b !== void 0 ? _b : new ajv_provider_js_1.AjvJsonSchemaValidator(); - this.setRequestHandler(types_js_1.InitializeRequestSchema, request => this._oninitialize(request)); - this.setNotificationHandler(types_js_1.InitializedNotificationSchema, () => { var _a; return (_a = this.oninitialized) === null || _a === void 0 ? void 0 : _a.call(this); }); - if (this._capabilities.logging) { - this.setRequestHandler(types_js_1.SetLevelRequestSchema, async (request, extra) => { - var _a; - const transportSessionId = extra.sessionId || ((_a = extra.requestInfo) === null || _a === void 0 ? void 0 : _a.headers['mcp-session-id']) || undefined; - const { level } = request.params; - const parseResult = types_js_1.LoggingLevelSchema.safeParse(level); - if (parseResult.success) { - this._loggingLevels.set(transportSessionId, parseResult.data); - } - return {}; - }); - } - } - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - registerCapabilities(capabilities) { - if (this.transport) { - throw new Error('Cannot register capabilities after connecting to transport'); - } - this._capabilities = (0, protocol_js_1.mergeCapabilities)(this._capabilities, capabilities); - } - assertCapabilityForMethod(method) { - var _a, _b, _c; - switch (method) { - case 'sampling/createMessage': - if (!((_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.sampling)) { - throw new Error(`Client does not support sampling (required for ${method})`); - } - break; - case 'elicitation/create': - if (!((_b = this._clientCapabilities) === null || _b === void 0 ? void 0 : _b.elicitation)) { - throw new Error(`Client does not support elicitation (required for ${method})`); - } - break; - case 'roots/list': - if (!((_c = this._clientCapabilities) === null || _c === void 0 ? void 0 : _c.roots)) { - throw new Error(`Client does not support listing roots (required for ${method})`); - } - break; - case 'ping': - // No specific capability required for ping - break; - } - } - assertNotificationCapability(method) { - var _a, _b; - switch (method) { - case 'notifications/message': - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case 'notifications/resources/updated': - case 'notifications/resources/list_changed': - if (!this._capabilities.resources) { - throw new Error(`Server does not support notifying about resources (required for ${method})`); - } - break; - case 'notifications/tools/list_changed': - if (!this._capabilities.tools) { - throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); - } - break; - case 'notifications/prompts/list_changed': - if (!this._capabilities.prompts) { - throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); - } - break; - case 'notifications/elicitation/complete': - if (!((_b = (_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.elicitation) === null || _b === void 0 ? void 0 : _b.url)) { - throw new Error(`Client does not support URL elicitation (required for ${method})`); - } - break; - case 'notifications/cancelled': - // Cancellation notifications are always allowed - break; - case 'notifications/progress': - // Progress notifications are always allowed - break; - } - } - assertRequestHandlerCapability(method) { - switch (method) { - case 'completion/complete': - if (!this._capabilities.completions) { - throw new Error(`Server does not support completions (required for ${method})`); - } - break; - case 'logging/setLevel': - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case 'prompts/get': - case 'prompts/list': - if (!this._capabilities.prompts) { - throw new Error(`Server does not support prompts (required for ${method})`); - } - break; - case 'resources/list': - case 'resources/templates/list': - case 'resources/read': - if (!this._capabilities.resources) { - throw new Error(`Server does not support resources (required for ${method})`); - } - break; - case 'tools/call': - case 'tools/list': - if (!this._capabilities.tools) { - throw new Error(`Server does not support tools (required for ${method})`); - } - break; - case 'ping': - case 'initialize': - // No specific capability required for these methods - break; - } - } - async _oninitialize(request) { - const requestedVersion = request.params.protocolVersion; - this._clientCapabilities = request.params.capabilities; - this._clientVersion = request.params.clientInfo; - const protocolVersion = types_js_1.SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : types_js_1.LATEST_PROTOCOL_VERSION; - return { - protocolVersion, - capabilities: this.getCapabilities(), - serverInfo: this._serverInfo, - ...(this._instructions && { instructions: this._instructions }) - }; - } - /** - * After initialization has completed, this will be populated with the client's reported capabilities. - */ - getClientCapabilities() { - return this._clientCapabilities; - } - /** - * After initialization has completed, this will be populated with information about the client's name and version. - */ - getClientVersion() { - return this._clientVersion; - } - getCapabilities() { - return this._capabilities; - } - async ping() { - return this.request({ method: 'ping' }, types_js_1.EmptyResultSchema); - } - async createMessage(params, options) { - return this.request({ method: 'sampling/createMessage', params }, types_js_1.CreateMessageResultSchema, options); - } - // Implementation (not visible to callers) - async elicitInput(params, options) { - var _a, _b, _c, _d; - const mode = ('mode' in params ? params.mode : 'form'); - switch (mode) { - case 'url': { - if (!((_b = (_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.elicitation) === null || _b === void 0 ? void 0 : _b.url)) { - throw new Error('Client does not support url elicitation.'); - } - const urlParams = params; - return this.request({ method: 'elicitation/create', params: urlParams }, types_js_1.ElicitResultSchema, options); - } - case 'form': { - if (!((_d = (_c = this._clientCapabilities) === null || _c === void 0 ? void 0 : _c.elicitation) === null || _d === void 0 ? void 0 : _d.form)) { - throw new Error('Client does not support form elicitation.'); - } - const formParams = 'mode' in params - ? params - : { ...params, mode: 'form' }; - const result = await this.request({ method: 'elicitation/create', params: formParams }, types_js_1.ElicitResultSchema, options); - if (result.action === 'accept' && result.content && formParams.requestedSchema) { - try { - const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); - const validationResult = validator(result.content); - if (!validationResult.valid) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); - } - } - catch (error) { - if (error instanceof types_js_1.McpError) { - throw error; - } - throw new types_js_1.McpError(types_js_1.ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); - } - } - return result; - } - } - } - /** - * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` - * notification for the specified elicitation ID. - * - * @param elicitationId The ID of the elicitation to mark as complete. - * @param options Optional notification options. Useful when the completion notification should be related to a prior request. - * @returns A function that emits the completion notification when awaited. - */ - createElicitationCompletionNotifier(elicitationId, options) { - var _a, _b; - if (!((_b = (_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.elicitation) === null || _b === void 0 ? void 0 : _b.url)) { - throw new Error('Client does not support URL elicitation (required for notifications/elicitation/complete)'); - } - return () => this.notification({ - method: 'notifications/elicitation/complete', - params: { - elicitationId - } - }, options); - } - async listRoots(params, options) { - return this.request({ method: 'roots/list', params }, types_js_1.ListRootsResultSchema, options); - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON RPC message - * @see LoggingMessageNotification - * @param params - * @param sessionId optional for stateless and backward compatibility - */ - async sendLoggingMessage(params, sessionId) { - if (this._capabilities.logging) { - if (!this.isMessageIgnored(params.level, sessionId)) { - return this.notification({ method: 'notifications/message', params }); - } - } - } - async sendResourceUpdated(params) { - return this.notification({ - method: 'notifications/resources/updated', - params - }); - } - async sendResourceListChanged() { - return this.notification({ - method: 'notifications/resources/list_changed' - }); - } - async sendToolListChanged() { - return this.notification({ method: 'notifications/tools/list_changed' }); - } - async sendPromptListChanged() { - return this.notification({ method: 'notifications/prompts/list_changed' }); - } -} -exports.Server = Server; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/cjs/server/index.js.map b/dist/cjs/server/index.js.map deleted file mode 100644 index edfc221a28..0000000000 --- a/dist/cjs/server/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":";;;AAAA,uDAAyI;AACzI,0CAgCqB;AACrB,mEAAuE;AAgDvE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAa,MAIX,SAAQ,sBAA8F;IAYpG;;OAEG;IACH,YACY,WAA2B,EACnC,OAAuB;;QAEvB,KAAK,CAAC,OAAO,CAAC,CAAC;QAHP,gBAAW,GAAX,WAAW,CAAgB;QAyBvC,+BAA+B;QACvB,mBAAc,GAAG,IAAI,GAAG,EAAoC,CAAC;QAErE,uCAAuC;QACtB,uBAAkB,GAAG,IAAI,GAAG,CAAC,6BAAkB,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;QAEhH,2FAA2F;QACnF,qBAAgB,GAAG,CAAC,KAAmB,EAAE,SAAkB,EAAW,EAAE;YAC5E,MAAM,YAAY,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;YACxD,OAAO,YAAY,CAAC,C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B,OAAO,IAAI,CAAC,YAAY,CAAC;YACrB,MAAM,EAAE,sCAAsC;SACjD,CAAC,CAAC;IACP,CAAC;IAED,KAAK,CAAC,mBAAmB;QACrB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,kCAAkC,EAAE,CAAC,CAAC;IAC7E,CAAC;IAED,KAAK,CAAC,qBAAqB;QACvB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,oCAAoC,EAAE,CAAC,CAAC;IAC/E,CAAC;CACJ;AA3WD,wBA2WC"} \ No newline at end of file diff --git a/dist/cjs/server/mcp.d.ts b/dist/cjs/server/mcp.d.ts deleted file mode 100644 index c0294b5698..0000000000 --- a/dist/cjs/server/mcp.d.ts +++ /dev/null @@ -1,332 +0,0 @@ -import { Server, ServerOptions } from './index.js'; -import { AnySchema, AnyObjectSchema, ZodRawShapeCompat, SchemaOutput, ShapeOutput } from './zod-compat.js'; -import { Implementation, CallToolResult, Resource, ListResourcesResult, GetPromptResult, ReadResourceResult, ServerRequest, ServerNotification, ToolAnnotations, SecurityScheme, LoggingMessageNotification } from '../types.js'; -import { UriTemplate, Variables } from '../shared/uriTemplate.js'; -import { RequestHandlerExtra } from '../shared/protocol.js'; -import { Transport } from '../shared/transport.js'; -/** - * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. - * For advanced usage (like sending notifications or setting custom request handlers), use the underlying - * Server instance available via the `server` property. - */ -export declare class McpServer { - /** - * The underlying Server instance, useful for advanced operations like sending notifications. - */ - readonly server: Server; - private _registeredResources; - private _registeredResourceTemplates; - private _registeredTools; - private _registeredPrompts; - constructor(serverInfo: Implementation, options?: ServerOptions); - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. - */ - connect(transport: Transport): Promise; - /** - * Closes the connection. - */ - close(): Promise; - private _toolHandlersInitialized; - private setToolRequestHandlers; - /** - * Creates a tool error result. - * - * @param errorMessage - The error message. - * @returns The tool error result. - */ - private createToolError; - private _completionHandlerInitialized; - private setCompletionRequestHandler; - private handlePromptCompletion; - private handleResourceCompletion; - private _resourceHandlersInitialized; - private setResourceRequestHandlers; - private _promptHandlersInitialized; - private setPromptRequestHandlers; - /** - * Registers a resource `name` at a fixed URI, which will use the given callback to respond to read requests. - * @deprecated Use `registerResource` instead. - */ - resource(name: string, uri: string, readCallback: ReadResourceCallback): RegisteredResource; - /** - * Registers a resource `name` at a fixed URI with metadata, which will use the given callback to respond to read requests. - * @deprecated Use `registerResource` instead. - */ - resource(name: string, uri: string, metadata: ResourceMetadata, readCallback: ReadResourceCallback): RegisteredResource; - /** - * Registers a resource `name` with a template pattern, which will use the given callback to respond to read requests. - * @deprecated Use `registerResource` instead. - */ - resource(name: string, template: ResourceTemplate, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; - /** - * Registers a resource `name` with a template pattern and metadata, which will use the given callback to respond to read requests. - * @deprecated Use `registerResource` instead. - */ - resource(name: string, template: ResourceTemplate, metadata: ResourceMetadata, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; - /** - * Registers a resource with a config object and callback. - * For static resources, use a URI string. For dynamic resources, use a ResourceTemplate. - */ - registerResource(name: string, uriOrTemplate: string, config: ResourceMetadata, readCallback: ReadResourceCallback): RegisteredResource; - registerResource(name: string, uriOrTemplate: ResourceTemplate, config: ResourceMetadata, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; - private _createRegisteredResource; - private _createRegisteredResourceTemplate; - private _createRegisteredPrompt; - private _createRegisteredTool; - /** - * Registers a zero-argument tool `name`, which will run the given function when the client calls it. - * @deprecated Use `registerTool` instead. - */ - tool(name: string, cb: ToolCallback): RegisteredTool; - /** - * Registers a zero-argument tool `name` (with a description) which will run the given function when the client calls it. - * @deprecated Use `registerTool` instead. - */ - tool(name: string, description: string, cb: ToolCallback): RegisteredTool; - /** - * Registers a tool taking either a parameter schema for validation or annotations for additional metadata. - * This unified overload handles both `tool(name, paramsSchema, cb)` and `tool(name, annotations, cb)` cases. - * - * Note: We use a union type for the second parameter because TypeScript cannot reliably disambiguate - * between ToolAnnotations and ZodRawShape during overload resolution, as both are plain object types. - * @deprecated Use `registerTool` instead. - */ - tool(name: string, paramsSchemaOrAnnotations: Args | ToolAnnotations, cb: ToolCallback): RegisteredTool; - /** - * Registers a tool `name` (with a description) taking either parameter schema or annotations. - * This unified overload handles both `tool(name, description, paramsSchema, cb)` and - * `tool(name, description, annotations, cb)` cases. - * - * Note: We use a union type for the third parameter because TypeScript cannot reliably disambiguate - * between ToolAnnotations and ZodRawShape during overload resolution, as both are plain object types. - * @deprecated Use `registerTool` instead. - */ - tool(name: string, description: string, paramsSchemaOrAnnotations: Args | ToolAnnotations, cb: ToolCallback): RegisteredTool; - /** - * Registers a tool with both parameter schema and annotations. - * @deprecated Use `registerTool` instead. - */ - tool(name: string, paramsSchema: Args, annotations: ToolAnnotations, cb: ToolCallback): RegisteredTool; - /** - * Registers a tool with description, parameter schema, and annotations. - * @deprecated Use `registerTool` instead. - */ - tool(name: string, description: string, paramsSchema: Args, annotations: ToolAnnotations, cb: ToolCallback): RegisteredTool; - /** - * Registers a tool with a config object and callback. - */ - registerTool(name: string, config: { - title?: string; - description?: string; - inputSchema?: InputArgs; - outputSchema?: OutputArgs; - annotations?: ToolAnnotations; - securitySchemes?: SecurityScheme[]; - _meta?: Record; - }, cb: ToolCallback): RegisteredTool; - /** - * Registers a zero-argument prompt `name`, which will run the given function when the client calls it. - * @deprecated Use `registerPrompt` instead. - */ - prompt(name: string, cb: PromptCallback): RegisteredPrompt; - /** - * Registers a zero-argument prompt `name` (with a description) which will run the given function when the client calls it. - * @deprecated Use `registerPrompt` instead. - */ - prompt(name: string, description: string, cb: PromptCallback): RegisteredPrompt; - /** - * Registers a prompt `name` accepting the given arguments, which must be an object containing named properties associated with Zod schemas. When the client calls it, the function will be run with the parsed and validated arguments. - * @deprecated Use `registerPrompt` instead. - */ - prompt(name: string, argsSchema: Args, cb: PromptCallback): RegisteredPrompt; - /** - * Registers a prompt `name` (with a description) accepting the given arguments, which must be an object containing named properties associated with Zod schemas. When the client calls it, the function will be run with the parsed and validated arguments. - * @deprecated Use `registerPrompt` instead. - */ - prompt(name: string, description: string, argsSchema: Args, cb: PromptCallback): RegisteredPrompt; - /** - * Registers a prompt with a config object and callback. - */ - registerPrompt(name: string, config: { - title?: string; - description?: string; - argsSchema?: Args; - }, cb: PromptCallback): RegisteredPrompt; - /** - * Checks if the server is connected to a transport. - * @returns True if the server is connected - */ - isConnected(): boolean; - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON RPC message - * @see LoggingMessageNotification - * @param params - * @param sessionId optional for stateless and backward compatibility - */ - sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string): Promise; - /** - * Sends a resource list changed event to the client, if connected. - */ - sendResourceListChanged(): void; - /** - * Sends a tool list changed event to the client, if connected. - */ - sendToolListChanged(): void; - /** - * Sends a prompt list changed event to the client, if connected. - */ - sendPromptListChanged(): void; -} -/** - * A callback to complete one variable within a resource template's URI template. - */ -export type CompleteResourceTemplateCallback = (value: string, context?: { - arguments?: Record; -}) => string[] | Promise; -/** - * A resource template combines a URI pattern with optional functionality to enumerate - * all resources matching that pattern. - */ -export declare class ResourceTemplate { - private _callbacks; - private _uriTemplate; - constructor(uriTemplate: string | UriTemplate, _callbacks: { - /** - * A callback to list all resources matching this template. This is required to specified, even if `undefined`, to avoid accidentally forgetting resource listing. - */ - list: ListResourcesCallback | undefined; - /** - * An optional callback to autocomplete variables within the URI template. Useful for clients and users to discover possible values. - */ - complete?: { - [variable: string]: CompleteResourceTemplateCallback; - }; - }); - /** - * Gets the URI template pattern. - */ - get uriTemplate(): UriTemplate; - /** - * Gets the list callback, if one was provided. - */ - get listCallback(): ListResourcesCallback | undefined; - /** - * Gets the callback for completing a specific URI template variable, if one was provided. - */ - completeCallback(variable: string): CompleteResourceTemplateCallback | undefined; -} -/** - * Callback for a tool handler registered with Server.tool(). - * - * Parameters will include tool arguments, if applicable, as well as other request handler context. - * - * The callback should return: - * - `structuredContent` if the tool has an outputSchema defined - * - `content` if the tool does not have an outputSchema - * - Both fields are optional but typically one should be provided - */ -export type ToolCallback = Args extends ZodRawShapeCompat ? (args: ShapeOutput, extra: RequestHandlerExtra) => CallToolResult | Promise : Args extends AnySchema ? (args: SchemaOutput, extra: RequestHandlerExtra) => CallToolResult | Promise : (extra: RequestHandlerExtra) => CallToolResult | Promise; -export type RegisteredTool = { - title?: string; - description?: string; - inputSchema?: AnySchema; - outputSchema?: AnySchema; - annotations?: ToolAnnotations; - securitySchemes?: SecurityScheme[]; - _meta?: Record; - callback: ToolCallback; - enabled: boolean; - enable(): void; - disable(): void; - update(updates: { - name?: string | null; - title?: string; - description?: string; - paramsSchema?: InputArgs; - outputSchema?: OutputArgs; - annotations?: ToolAnnotations; - securitySchemes?: SecurityScheme[]; - _meta?: Record; - callback?: ToolCallback; - enabled?: boolean; - }): void; - remove(): void; -}; -/** - * Additional, optional information for annotating a resource. - */ -export type ResourceMetadata = Omit; -/** - * Callback to list all resources matching a given template. - */ -export type ListResourcesCallback = (extra: RequestHandlerExtra) => ListResourcesResult | Promise; -/** - * Callback to read a resource at a given URI. - */ -export type ReadResourceCallback = (uri: URL, extra: RequestHandlerExtra) => ReadResourceResult | Promise; -export type RegisteredResource = { - name: string; - title?: string; - metadata?: ResourceMetadata; - readCallback: ReadResourceCallback; - enabled: boolean; - enable(): void; - disable(): void; - update(updates: { - name?: string; - title?: string; - uri?: string | null; - metadata?: ResourceMetadata; - callback?: ReadResourceCallback; - enabled?: boolean; - }): void; - remove(): void; -}; -/** - * Callback to read a resource at a given URI, following a filled-in URI template. - */ -export type ReadResourceTemplateCallback = (uri: URL, variables: Variables, extra: RequestHandlerExtra) => ReadResourceResult | Promise; -export type RegisteredResourceTemplate = { - resourceTemplate: ResourceTemplate; - title?: string; - metadata?: ResourceMetadata; - readCallback: ReadResourceTemplateCallback; - enabled: boolean; - enable(): void; - disable(): void; - update(updates: { - name?: string | null; - title?: string; - template?: ResourceTemplate; - metadata?: ResourceMetadata; - callback?: ReadResourceTemplateCallback; - enabled?: boolean; - }): void; - remove(): void; -}; -type PromptArgsRawShape = ZodRawShapeCompat; -export type PromptCallback = Args extends PromptArgsRawShape ? (args: ShapeOutput, extra: RequestHandlerExtra) => GetPromptResult | Promise : (extra: RequestHandlerExtra) => GetPromptResult | Promise; -export type RegisteredPrompt = { - title?: string; - description?: string; - argsSchema?: AnyObjectSchema; - callback: PromptCallback; - enabled: boolean; - enable(): void; - disable(): void; - update(updates: { - name?: string | null; - title?: string; - description?: string; - argsSchema?: Args; - callback?: PromptCallback; - enabled?: boolean; - }): void; - remove(): void; -}; -export {}; -//# sourceMappingURL=mcp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/mcp.d.ts.map b/dist/cjs/server/mcp.d.ts.map deleted file mode 100644 index 9ed3a0fd27..0000000000 --- a/dist/cjs/server/mcp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../../../src/server/mcp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACH,SAAS,EACT,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,WAAW,EASd,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EACH,cAAc,EAGd,cAAc,EAOd,QAAQ,EACR,mBAAmB,EAYnB,eAAe,EACf,kBAAkB,EAClB,aAAa,EACb,kBAAkB,EAClB,eAAe,EACf,cAAc,EACd,0BAA0B,EAK7B,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAGnD;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AAC,GACtI,CAAC,KAAK,EAAE,mBAAmB,CAAC,aAAa,EAAE,kBAAkB,CAAC,KAAK,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;AAEpH,MAAM,MAAM,gBAAgB,GAAG;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,eAAe,CAAC;IAC7B,QAAQ,EAAE,cAAc,CAAC,SAAS,GAAG,kBAAkB,CAAC,CAAC;IACzD,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,IAAI,IAAI,CAAC;IACf,OAAO,IAAI,IAAI,CAAC;IAChB,MAAM,CAAC,IAAI,SAAS,kBAAkB,EAAE,OAAO,EAAE;QAC7C,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QACrB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,UAAU,CAAC,EAAE,IAAI,CAAC;QAClB,QAAQ,CAAC,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC;QAChC,OAAO,CAAC,EAAE,OAAO,CAAC;KACrB,GAAG,IAAI,CAAC;IACT,MAAM,IAAI,IAAI,CAAC;CAClB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/mcp.js b/dist/cjs/server/mcp.js deleted file mode 100644 index 06cc0b883c..0000000000 --- a/dist/cjs/server/mcp.js +++ /dev/null @@ -1,758 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ResourceTemplate = exports.McpServer = void 0; -const index_js_1 = require("./index.js"); -const zod_compat_js_1 = require("./zod-compat.js"); -const zod_json_schema_compat_js_1 = require("./zod-json-schema-compat.js"); -const types_js_1 = require("../types.js"); -const completable_js_1 = require("./completable.js"); -const uriTemplate_js_1 = require("../shared/uriTemplate.js"); -const toolNameValidation_js_1 = require("../shared/toolNameValidation.js"); -/** - * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. - * For advanced usage (like sending notifications or setting custom request handlers), use the underlying - * Server instance available via the `server` property. - */ -class McpServer { - constructor(serverInfo, options) { - this._registeredResources = {}; - this._registeredResourceTemplates = {}; - this._registeredTools = {}; - this._registeredPrompts = {}; - this._toolHandlersInitialized = false; - this._completionHandlerInitialized = false; - this._resourceHandlersInitialized = false; - this._promptHandlersInitialized = false; - this.server = new index_js_1.Server(serverInfo, options); - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. - */ - async connect(transport) { - return await this.server.connect(transport); - } - /** - * Closes the connection. - */ - async close() { - await this.server.close(); - } - setToolRequestHandlers() { - if (this._toolHandlersInitialized) { - return; - } - this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListToolsRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.CallToolRequestSchema)); - this.server.registerCapabilities({ - tools: { - listChanged: true - } - }); - this.server.setRequestHandler(types_js_1.ListToolsRequestSchema, () => { - // eslint-disable-next-line no-console - console.log('Tool list handler called'); - return { - tools: Object.entries(this._registeredTools) - .filter(([, tool]) => tool.enabled) - .map(([name, tool]) => { - const toolDefinition = { - name, - title: tool.title, - description: tool.description, - inputSchema: (() => { - const obj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.inputSchema); - return obj - ? (0, zod_json_schema_compat_js_1.toJsonSchemaCompat)(obj, { - strictUnions: true, - pipeStrategy: 'input' - }) - : EMPTY_OBJECT_JSON_SCHEMA; - })(), - annotations: tool.annotations, - securitySchemes: tool.securitySchemes, - _meta: tool._meta - }; - if (tool.outputSchema) { - const obj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.outputSchema); - if (obj) { - toolDefinition.outputSchema = (0, zod_json_schema_compat_js_1.toJsonSchemaCompat)(obj, { - strictUnions: true, - pipeStrategy: 'output' - }); - } - } - return toolDefinition; - }) - }; - }); - this.server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request, extra) => { - const tool = this._registeredTools[request.params.name]; - let result; - try { - if (!tool) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Tool ${request.params.name} not found`); - } - if (!tool.enabled) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); - } - if (tool.inputSchema) { - const cb = tool.callback; - // Try to normalize to object schema first (for raw shapes and object schemas) - // If that fails, use the schema directly (for union/intersection/etc) - const inputObj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.inputSchema); - const schemaToParse = inputObj !== null && inputObj !== void 0 ? inputObj : tool.inputSchema; - const parseResult = await (0, zod_compat_js_1.safeParseAsync)(schemaToParse, request.params.arguments); - if (!parseResult.success) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${request.params.name}: ${(0, zod_compat_js_1.getParseErrorMessage)(parseResult.error)}`); - } - const args = parseResult.data; - result = await Promise.resolve(cb(args, extra)); - } - else { - const cb = tool.callback; - result = await Promise.resolve(cb(extra)); - } - if (tool.outputSchema && !result.isError) { - if (!result.structuredContent) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Output validation error: Tool ${request.params.name} has an output schema but no structured content was provided`); - } - // if the tool has an output schema, validate structured content - const outputObj = (0, zod_compat_js_1.normalizeObjectSchema)(tool.outputSchema); - const parseResult = await (0, zod_compat_js_1.safeParseAsync)(outputObj, result.structuredContent); - if (!parseResult.success) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${request.params.name}: ${(0, zod_compat_js_1.getParseErrorMessage)(parseResult.error)}`); - } - } - } - catch (error) { - if (error instanceof types_js_1.McpError) { - if (error.code === types_js_1.ErrorCode.UrlElicitationRequired) { - throw error; // Return the error to the caller without wrapping in CallToolResult - } - } - return this.createToolError(error instanceof Error ? error.message : String(error)); - } - return result; - }); - this._toolHandlersInitialized = true; - } - /** - * Creates a tool error result. - * - * @param errorMessage - The error message. - * @returns The tool error result. - */ - createToolError(errorMessage) { - return { - content: [ - { - type: 'text', - text: errorMessage - } - ], - isError: true - }; - } - setCompletionRequestHandler() { - if (this._completionHandlerInitialized) { - return; - } - this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.CompleteRequestSchema)); - this.server.registerCapabilities({ - completions: {} - }); - this.server.setRequestHandler(types_js_1.CompleteRequestSchema, async (request) => { - switch (request.params.ref.type) { - case 'ref/prompt': - (0, types_js_1.assertCompleteRequestPrompt)(request); - return this.handlePromptCompletion(request, request.params.ref); - case 'ref/resource': - (0, types_js_1.assertCompleteRequestResourceTemplate)(request); - return this.handleResourceCompletion(request, request.params.ref); - default: - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); - } - }); - this._completionHandlerInitialized = true; - } - async handlePromptCompletion(request, ref) { - const prompt = this._registeredPrompts[ref.name]; - if (!prompt) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${ref.name} not found`); - } - if (!prompt.enabled) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); - } - if (!prompt.argsSchema) { - return EMPTY_COMPLETION_RESULT; - } - const promptShape = (0, zod_compat_js_1.getObjectShape)(prompt.argsSchema); - const field = promptShape === null || promptShape === void 0 ? void 0 : promptShape[request.params.argument.name]; - if (!(0, completable_js_1.isCompletable)(field)) { - return EMPTY_COMPLETION_RESULT; - } - const completer = (0, completable_js_1.getCompleter)(field); - if (!completer) { - return EMPTY_COMPLETION_RESULT; - } - const suggestions = await completer(request.params.argument.value, request.params.context); - return createCompletionResult(suggestions); - } - async handleResourceCompletion(request, ref) { - const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri); - if (!template) { - if (this._registeredResources[ref.uri]) { - // Attempting to autocomplete a fixed resource URI is not an error in the spec (but probably should be). - return EMPTY_COMPLETION_RESULT; - } - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); - } - const completer = template.resourceTemplate.completeCallback(request.params.argument.name); - if (!completer) { - return EMPTY_COMPLETION_RESULT; - } - const suggestions = await completer(request.params.argument.value, request.params.context); - return createCompletionResult(suggestions); - } - setResourceRequestHandlers() { - if (this._resourceHandlersInitialized) { - return; - } - this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListResourcesRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListResourceTemplatesRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ReadResourceRequestSchema)); - this.server.registerCapabilities({ - resources: { - listChanged: true - } - }); - this.server.setRequestHandler(types_js_1.ListResourcesRequestSchema, async (request, extra) => { - const resources = Object.entries(this._registeredResources) - .filter(([_, resource]) => resource.enabled) - .map(([uri, resource]) => ({ - uri, - name: resource.name, - ...resource.metadata - })); - const templateResources = []; - for (const template of Object.values(this._registeredResourceTemplates)) { - if (!template.resourceTemplate.listCallback) { - continue; - } - const result = await template.resourceTemplate.listCallback(extra); - for (const resource of result.resources) { - templateResources.push({ - ...template.metadata, - // the defined resource metadata should override the template metadata if present - ...resource - }); - } - } - return { resources: [...resources, ...templateResources] }; - }); - this.server.setRequestHandler(types_js_1.ListResourceTemplatesRequestSchema, async () => { - const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ - name, - uriTemplate: template.resourceTemplate.uriTemplate.toString(), - ...template.metadata - })); - return { resourceTemplates }; - }); - this.server.setRequestHandler(types_js_1.ReadResourceRequestSchema, async (request, extra) => { - const uri = new URL(request.params.uri); - // First check for exact resource match - const resource = this._registeredResources[uri.toString()]; - if (resource) { - if (!resource.enabled) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Resource ${uri} disabled`); - } - return resource.readCallback(uri, extra); - } - // Then check templates - for (const template of Object.values(this._registeredResourceTemplates)) { - const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); - if (variables) { - return template.readCallback(uri, variables, extra); - } - } - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Resource ${uri} not found`); - }); - this.setCompletionRequestHandler(); - this._resourceHandlersInitialized = true; - } - setPromptRequestHandlers() { - if (this._promptHandlersInitialized) { - return; - } - this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.ListPromptsRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(types_js_1.GetPromptRequestSchema)); - this.server.registerCapabilities({ - prompts: { - listChanged: true - } - }); - this.server.setRequestHandler(types_js_1.ListPromptsRequestSchema, () => ({ - prompts: Object.entries(this._registeredPrompts) - .filter(([, prompt]) => prompt.enabled) - .map(([name, prompt]) => { - return { - name, - title: prompt.title, - description: prompt.description, - arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined - }; - }) - })); - this.server.setRequestHandler(types_js_1.GetPromptRequestSchema, async (request, extra) => { - const prompt = this._registeredPrompts[request.params.name]; - if (!prompt) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); - } - if (!prompt.enabled) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); - } - if (prompt.argsSchema) { - const argsObj = (0, zod_compat_js_1.normalizeObjectSchema)(prompt.argsSchema); - const parseResult = await (0, zod_compat_js_1.safeParseAsync)(argsObj, request.params.arguments); - if (!parseResult.success) { - throw new types_js_1.McpError(types_js_1.ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${(0, zod_compat_js_1.getParseErrorMessage)(parseResult.error)}`); - } - const args = parseResult.data; - const cb = prompt.callback; - return await Promise.resolve(cb(args, extra)); - } - else { - const cb = prompt.callback; - return await Promise.resolve(cb(extra)); - } - }); - this.setCompletionRequestHandler(); - this._promptHandlersInitialized = true; - } - resource(name, uriOrTemplate, ...rest) { - let metadata; - if (typeof rest[0] === 'object') { - metadata = rest.shift(); - } - const readCallback = rest[0]; - if (typeof uriOrTemplate === 'string') { - if (this._registeredResources[uriOrTemplate]) { - throw new Error(`Resource ${uriOrTemplate} is already registered`); - } - const registeredResource = this._createRegisteredResource(name, undefined, uriOrTemplate, metadata, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } - else { - if (this._registeredResourceTemplates[name]) { - throw new Error(`Resource template ${name} is already registered`); - } - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, undefined, uriOrTemplate, metadata, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - registerResource(name, uriOrTemplate, config, readCallback) { - if (typeof uriOrTemplate === 'string') { - if (this._registeredResources[uriOrTemplate]) { - throw new Error(`Resource ${uriOrTemplate} is already registered`); - } - const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } - else { - if (this._registeredResourceTemplates[name]) { - throw new Error(`Resource template ${name} is already registered`); - } - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - _createRegisteredResource(name, title, uri, metadata, readCallback) { - const registeredResource = { - name, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResource.update({ enabled: false }), - enable: () => registeredResource.update({ enabled: true }), - remove: () => registeredResource.update({ uri: null }), - update: updates => { - if (typeof updates.uri !== 'undefined' && updates.uri !== uri) { - delete this._registeredResources[uri]; - if (updates.uri) - this._registeredResources[updates.uri] = registeredResource; - } - if (typeof updates.name !== 'undefined') - registeredResource.name = updates.name; - if (typeof updates.title !== 'undefined') - registeredResource.title = updates.title; - if (typeof updates.metadata !== 'undefined') - registeredResource.metadata = updates.metadata; - if (typeof updates.callback !== 'undefined') - registeredResource.readCallback = updates.callback; - if (typeof updates.enabled !== 'undefined') - registeredResource.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResources[uri] = registeredResource; - return registeredResource; - } - _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { - const registeredResourceTemplate = { - resourceTemplate: template, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResourceTemplate.update({ enabled: false }), - enable: () => registeredResourceTemplate.update({ enabled: true }), - remove: () => registeredResourceTemplate.update({ name: null }), - update: updates => { - if (typeof updates.name !== 'undefined' && updates.name !== name) { - delete this._registeredResourceTemplates[name]; - if (updates.name) - this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; - } - if (typeof updates.title !== 'undefined') - registeredResourceTemplate.title = updates.title; - if (typeof updates.template !== 'undefined') - registeredResourceTemplate.resourceTemplate = updates.template; - if (typeof updates.metadata !== 'undefined') - registeredResourceTemplate.metadata = updates.metadata; - if (typeof updates.callback !== 'undefined') - registeredResourceTemplate.readCallback = updates.callback; - if (typeof updates.enabled !== 'undefined') - registeredResourceTemplate.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResourceTemplates[name] = registeredResourceTemplate; - return registeredResourceTemplate; - } - _createRegisteredPrompt(name, title, description, argsSchema, callback) { - const registeredPrompt = { - title, - description, - argsSchema: argsSchema === undefined ? undefined : (0, zod_compat_js_1.objectFromShape)(argsSchema), - callback, - enabled: true, - disable: () => registeredPrompt.update({ enabled: false }), - enable: () => registeredPrompt.update({ enabled: true }), - remove: () => registeredPrompt.update({ name: null }), - update: updates => { - if (typeof updates.name !== 'undefined' && updates.name !== name) { - delete this._registeredPrompts[name]; - if (updates.name) - this._registeredPrompts[updates.name] = registeredPrompt; - } - if (typeof updates.title !== 'undefined') - registeredPrompt.title = updates.title; - if (typeof updates.description !== 'undefined') - registeredPrompt.description = updates.description; - if (typeof updates.argsSchema !== 'undefined') - registeredPrompt.argsSchema = (0, zod_compat_js_1.objectFromShape)(updates.argsSchema); - if (typeof updates.callback !== 'undefined') - registeredPrompt.callback = updates.callback; - if (typeof updates.enabled !== 'undefined') - registeredPrompt.enabled = updates.enabled; - this.sendPromptListChanged(); - } - }; - this._registeredPrompts[name] = registeredPrompt; - return registeredPrompt; - } - _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, securitySchemes, _meta, callback) { - // Validate tool name according to SEP specification - (0, toolNameValidation_js_1.validateAndWarnToolName)(name); - const registeredTool = { - title, - description, - inputSchema: getZodSchemaObject(inputSchema), - outputSchema: getZodSchemaObject(outputSchema), - annotations, - securitySchemes, - _meta, - callback, - enabled: true, - disable: () => registeredTool.update({ enabled: false }), - enable: () => registeredTool.update({ enabled: true }), - remove: () => registeredTool.update({ name: null }), - update: updates => { - if (typeof updates.name !== 'undefined' && updates.name !== name) { - if (typeof updates.name === 'string') { - (0, toolNameValidation_js_1.validateAndWarnToolName)(updates.name); - } - delete this._registeredTools[name]; - if (updates.name) - this._registeredTools[updates.name] = registeredTool; - } - if (typeof updates.title !== 'undefined') - registeredTool.title = updates.title; - if (typeof updates.description !== 'undefined') - registeredTool.description = updates.description; - if (typeof updates.paramsSchema !== 'undefined') - registeredTool.inputSchema = (0, zod_compat_js_1.objectFromShape)(updates.paramsSchema); - if (typeof updates.callback !== 'undefined') - registeredTool.callback = updates.callback; - if (typeof updates.annotations !== 'undefined') - registeredTool.annotations = updates.annotations; - if (typeof updates.securitySchemes !== 'undefined') - registeredTool.securitySchemes = updates.securitySchemes; - if (typeof updates._meta !== 'undefined') - registeredTool._meta = updates._meta; - if (typeof updates.enabled !== 'undefined') - registeredTool.enabled = updates.enabled; - this.sendToolListChanged(); - } - }; - this._registeredTools[name] = registeredTool; - this.setToolRequestHandlers(); - this.sendToolListChanged(); - return registeredTool; - } - /** - * tool() implementation. Parses arguments passed to overrides defined above. - */ - tool(name, ...rest) { - if (this._registeredTools[name]) { - throw new Error(`Tool ${name} is already registered`); - } - let description; - let inputSchema; - let outputSchema; - let annotations; - // Tool properties are passed as separate arguments, with omissions allowed. - // Support for this style is frozen as of protocol version 2025-03-26. Future additions - // to tool definition should *NOT* be added. - if (typeof rest[0] === 'string') { - description = rest.shift(); - } - // Handle the different overload combinations - if (rest.length > 1) { - // We have at least one more arg before the callback - const firstArg = rest[0]; - if (isZodRawShape(firstArg)) { - // We have a params schema as the first arg - inputSchema = rest.shift(); - // Check if the next arg is potentially annotations - if (rest.length > 1 && typeof rest[0] === 'object' && rest[0] !== null && !isZodRawShape(rest[0])) { - // Case: tool(name, paramsSchema, annotations, cb) - // Or: tool(name, description, paramsSchema, annotations, cb) - annotations = rest.shift(); - } - } - else if (typeof firstArg === 'object' && firstArg !== null) { - // Not a ZodRawShape, so must be annotations in this position - // Case: tool(name, annotations, cb) - // Or: tool(name, description, annotations, cb) - annotations = rest.shift(); - } - } - const callback = rest[0]; - return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, undefined, undefined, callback); - } - /** - * Registers a tool with a config object and callback. - */ - registerTool(name, config, cb) { - if (this._registeredTools[name]) { - throw new Error(`Tool ${name} is already registered`); - } - console.log('registerTool'); - const { title, description, inputSchema, outputSchema, annotations, securitySchemes, _meta } = config; - return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, securitySchemes, _meta, cb); - } - prompt(name, ...rest) { - if (this._registeredPrompts[name]) { - throw new Error(`Prompt ${name} is already registered`); - } - let description; - if (typeof rest[0] === 'string') { - description = rest.shift(); - } - let argsSchema; - if (rest.length > 1) { - argsSchema = rest.shift(); - } - const cb = rest[0]; - const registeredPrompt = this._createRegisteredPrompt(name, undefined, description, argsSchema, cb); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; - } - /** - * Registers a prompt with a config object and callback. - */ - registerPrompt(name, config, cb) { - if (this._registeredPrompts[name]) { - throw new Error(`Prompt ${name} is already registered`); - } - const { title, description, argsSchema } = config; - const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; - } - /** - * Checks if the server is connected to a transport. - * @returns True if the server is connected - */ - isConnected() { - return this.server.transport !== undefined; - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON RPC message - * @see LoggingMessageNotification - * @param params - * @param sessionId optional for stateless and backward compatibility - */ - async sendLoggingMessage(params, sessionId) { - return this.server.sendLoggingMessage(params, sessionId); - } - /** - * Sends a resource list changed event to the client, if connected. - */ - sendResourceListChanged() { - if (this.isConnected()) { - this.server.sendResourceListChanged(); - } - } - /** - * Sends a tool list changed event to the client, if connected. - */ - sendToolListChanged() { - if (this.isConnected()) { - this.server.sendToolListChanged(); - } - } - /** - * Sends a prompt list changed event to the client, if connected. - */ - sendPromptListChanged() { - if (this.isConnected()) { - this.server.sendPromptListChanged(); - } - } -} -exports.McpServer = McpServer; -/** - * A resource template combines a URI pattern with optional functionality to enumerate - * all resources matching that pattern. - */ -class ResourceTemplate { - constructor(uriTemplate, _callbacks) { - this._callbacks = _callbacks; - this._uriTemplate = typeof uriTemplate === 'string' ? new uriTemplate_js_1.UriTemplate(uriTemplate) : uriTemplate; - } - /** - * Gets the URI template pattern. - */ - get uriTemplate() { - return this._uriTemplate; - } - /** - * Gets the list callback, if one was provided. - */ - get listCallback() { - return this._callbacks.list; - } - /** - * Gets the callback for completing a specific URI template variable, if one was provided. - */ - completeCallback(variable) { - var _a; - return (_a = this._callbacks.complete) === null || _a === void 0 ? void 0 : _a[variable]; - } -} -exports.ResourceTemplate = ResourceTemplate; -const EMPTY_OBJECT_JSON_SCHEMA = { - type: 'object', - properties: {} -}; -// Helper to check if an object is a Zod schema (ZodRawShapeCompat) -function isZodRawShape(obj) { - if (typeof obj !== 'object' || obj === null) - return false; - const isEmptyObject = Object.keys(obj).length === 0; - // Check if object is empty or at least one property is a ZodType instance - // Note: use heuristic check to avoid instanceof failure across different Zod versions - return isEmptyObject || Object.values(obj).some(isZodTypeLike); -} -function isZodTypeLike(value) { - return (value !== null && - typeof value === 'object' && - 'parse' in value && - typeof value.parse === 'function' && - 'safeParse' in value && - typeof value.safeParse === 'function'); -} -/** - * Converts a provided Zod schema to a Zod object if it is a ZodRawShape, - * otherwise returns the schema as is. - */ -function getZodSchemaObject(schema) { - if (!schema) { - return undefined; - } - if (isZodRawShape(schema)) { - return (0, zod_compat_js_1.objectFromShape)(schema); - } - return schema; -} -function promptArgumentsFromSchema(schema) { - const shape = (0, zod_compat_js_1.getObjectShape)(schema); - if (!shape) - return []; - return Object.entries(shape).map(([name, field]) => { - // Get description - works for both v3 and v4 - const description = (0, zod_compat_js_1.getSchemaDescription)(field); - // Check if optional - works for both v3 and v4 - const isOptional = (0, zod_compat_js_1.isSchemaOptional)(field); - return { - name, - description, - required: !isOptional - }; - }); -} -function getMethodValue(schema) { - const shape = (0, zod_compat_js_1.getObjectShape)(schema); - const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method; - if (!methodSchema) { - throw new Error('Schema is missing a method literal'); - } - // Extract literal value - works for both v3 and v4 - const value = (0, zod_compat_js_1.getLiteralValue)(methodSchema); - if (typeof value === 'string') { - return value; - } - throw new Error('Schema method literal must be a string'); -} -function createCompletionResult(suggestions) { - return { - completion: { - values: suggestions.slice(0, 100), - total: suggestions.length, - hasMore: suggestions.length > 100 - } - }; -} -const EMPTY_COMPLETION_RESULT = { - completion: { - values: [], - hasMore: false - } -}; -//# sourceMappingURL=mcp.js.map \ No newline at end of file diff --git a/dist/cjs/server/mcp.js.map b/dist/cjs/server/mcp.js.map deleted file mode 100644 index 631cee2ecc..0000000000 --- a/dist/cjs/server/mcp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"mcp.js","sourceRoot":"","sources":["../../../src/server/mcp.ts"],"names":[],"mappings":";;;AAAA,yCAAmD;AACnD,mDAcyB;AACzB,2EAAiE;AACjE,0CAmCqB;AACrB,qDAA+D;AAC/D,6DAAkE;AAGlE,2EAA0E;AAE1E;;;;GAIG;AACH,MAAa,SAAS;IAalB,YAAY,UAA0B,EAAE,OAAuB;QAPvD,yBAAoB,GAA0C,EAAE,CAAC;QACjE,iCAA4B,G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,EAAE;QAC/D,6CAA6C;QAC7C,MAAM,WAAW,GAAG,IAAA,oCAAoB,EAAC,KAAK,CAAC,CAAC;QAChD,+CAA+C;QAC/C,MAAM,UAAU,GAAG,IAAA,gCAAgB,EAAC,KAAK,CAAC,CAAC;QAC3C,OAAO;YACH,IAAI;YACJ,WAAW;YACX,QAAQ,EAAE,CAAC,UAAU;SACxB,CAAC;IACN,CAAC,CAAC,CAAC;AACP,CAAC;AAED,SAAS,cAAc,CAAC,MAAuB;IAC3C,MAAM,KAAK,GAAG,IAAA,8BAAc,EAAC,MAAM,CAAC,CAAC;IACrC,MAAM,YAAY,GAAG,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,MAA+B,CAAC;IAC5D,IAAI,CAAC,YAAY,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;IAC1D,CAAC;IAED,mDAAmD;IACnD,MAAM,KAAK,GAAG,IAAA,+BAAe,EAAC,YAAY,CAAC,CAAC;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC5B,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC9D,CAAC;AAED,SAAS,sBAAsB,CAAC,WAAqB;IACjD,OAAO;QACH,UAAU,EAAE;YACR,MAAM,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC;YACjC,KAAK,EAAE,WAAW,CAAC,MAAM;YACzB,OAAO,EAAE,WAAW,CAAC,MAAM,GAAG,GAAG;SACpC;KACJ,CAAC;AACN,CAAC;AAED,MAAM,uBAAuB,GAAmB;IAC5C,UAAU,EAAE;QACR,MAAM,EAAE,EAAE;QACV,OAAO,EAAE,KAAK;KACjB;CACJ,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/sse.d.ts b/dist/cjs/server/sse.d.ts deleted file mode 100644 index aba8d51209..0000000000 --- a/dist/cjs/server/sse.d.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { IncomingMessage, ServerResponse } from 'node:http'; -import { Transport } from '../shared/transport.js'; -import { JSONRPCMessage, MessageExtraInfo } from '../types.js'; -import { AuthInfo } from './auth/types.js'; -/** - * Configuration options for SSEServerTransport. - */ -export interface SSEServerTransportOptions { - /** - * List of allowed host header values for DNS rebinding protection. - * If not specified, host validation is disabled. - */ - allowedHosts?: string[]; - /** - * List of allowed origin header values for DNS rebinding protection. - * If not specified, origin validation is disabled. - */ - allowedOrigins?: string[]; - /** - * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). - * Default is false for backwards compatibility. - */ - enableDnsRebindingProtection?: boolean; -} -/** - * Server transport for SSE: this will send messages over an SSE connection and receive messages from HTTP POST requests. - * - * This transport is only available in Node.js environments. - * @deprecated SSEServerTransport is deprecated. Use StreamableHTTPServerTransport instead. - */ -export declare class SSEServerTransport implements Transport { - private _endpoint; - private res; - private _sseResponse?; - private _sessionId; - private _options; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; - /** - * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. - */ - constructor(_endpoint: string, res: ServerResponse, options?: SSEServerTransportOptions); - /** - * Validates request headers for DNS rebinding protection. - * @returns Error message if validation fails, undefined if validation passes. - */ - private validateRequestHeaders; - /** - * Handles the initial SSE connection request. - * - * This should be called when a GET request is made to establish the SSE stream. - */ - start(): Promise; - /** - * Handles incoming POST messages. - * - * This should be called when a POST request is made to send a message to the server. - */ - handlePostMessage(req: IncomingMessage & { - auth?: AuthInfo; - }, res: ServerResponse, parsedBody?: unknown): Promise; - /** - * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. - */ - handleMessage(message: unknown, extra?: MessageExtraInfo): Promise; - close(): Promise; - send(message: JSONRPCMessage): Promise; - /** - * Returns the session ID for this transport. - * - * This can be used to route incoming POST requests. - */ - get sessionId(): string; -} -//# sourceMappingURL=sse.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/sse.d.ts.map b/dist/cjs/server/sse.d.ts.map deleted file mode 100644 index c3c267cd8f..0000000000 --- a/dist/cjs/server/sse.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../../src/server/sse.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAwB,gBAAgB,EAAe,MAAM,aAAa,CAAC;AAGlG,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAK3C;;GAEG;AACH,MAAM,WAAW,yBAAyB;IACtC;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IAExB;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAE1B;;;OAGG;IACH,4BAA4B,CAAC,EAAE,OAAO,CAAC;CAC1C;AAED;;;;;GAKG;AACH,qBAAa,kBAAmB,YAAW,SAAS;IAY5C,OAAO,CAAC,SAAS;IACjB,OAAO,CAAC,GAAG;IAZf,OAAO,CAAC,YAAY,CAAC,CAAiB;IACtC,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,QAAQ,CAA4B;IAC5C,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAExE;;OAEG;gBAES,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,cAAc,EAC3B,OAAO,CAAC,EAAE,yBAAyB;IAMvC;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IAyB9B;;;;OAIG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IA8B5B;;;;OAIG;IACG,iBAAiB,CAAC,GAAG,EAAE,eAAe,GAAG;QAAE,IAAI,CAAC,EAAE,QAAQ,CAAA;KAAE,EAAE,GAAG,EAAE,cAAc,EAAE,UAAU,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IA+C7H;;OAEG;IACG,aAAa,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;IAYxE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAMtB,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAQlD;;;;OAIG;IACH,IAAI,SAAS,IAAI,MAAM,CAEtB;CACJ"} \ No newline at end of file diff --git a/dist/cjs/server/sse.js b/dist/cjs/server/sse.js deleted file mode 100644 index d59d47c037..0000000000 --- a/dist/cjs/server/sse.js +++ /dev/null @@ -1,168 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SSEServerTransport = void 0; -const node_crypto_1 = require("node:crypto"); -const types_js_1 = require("../types.js"); -const raw_body_1 = __importDefault(require("raw-body")); -const content_type_1 = __importDefault(require("content-type")); -const url_1 = require("url"); -const MAXIMUM_MESSAGE_SIZE = '4mb'; -/** - * Server transport for SSE: this will send messages over an SSE connection and receive messages from HTTP POST requests. - * - * This transport is only available in Node.js environments. - * @deprecated SSEServerTransport is deprecated. Use StreamableHTTPServerTransport instead. - */ -class SSEServerTransport { - /** - * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. - */ - constructor(_endpoint, res, options) { - this._endpoint = _endpoint; - this.res = res; - this._sessionId = (0, node_crypto_1.randomUUID)(); - this._options = options || { enableDnsRebindingProtection: false }; - } - /** - * Validates request headers for DNS rebinding protection. - * @returns Error message if validation fails, undefined if validation passes. - */ - validateRequestHeaders(req) { - // Skip validation if protection is not enabled - if (!this._options.enableDnsRebindingProtection) { - return undefined; - } - // Validate Host header if allowedHosts is configured - if (this._options.allowedHosts && this._options.allowedHosts.length > 0) { - const hostHeader = req.headers.host; - if (!hostHeader || !this._options.allowedHosts.includes(hostHeader)) { - return `Invalid Host header: ${hostHeader}`; - } - } - // Validate Origin header if allowedOrigins is configured - if (this._options.allowedOrigins && this._options.allowedOrigins.length > 0) { - const originHeader = req.headers.origin; - if (!originHeader || !this._options.allowedOrigins.includes(originHeader)) { - return `Invalid Origin header: ${originHeader}`; - } - } - return undefined; - } - /** - * Handles the initial SSE connection request. - * - * This should be called when a GET request is made to establish the SSE stream. - */ - async start() { - if (this._sseResponse) { - throw new Error('SSEServerTransport already started! If using Server class, note that connect() calls start() automatically.'); - } - this.res.writeHead(200, { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }); - // Send the endpoint event - // Use a dummy base URL because this._endpoint is relative. - // This allows using URL/URLSearchParams for robust parameter handling. - const dummyBase = 'http://localhost'; // Any valid base works - const endpointUrl = new url_1.URL(this._endpoint, dummyBase); - endpointUrl.searchParams.set('sessionId', this._sessionId); - // Reconstruct the relative URL string (pathname + search + hash) - const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash; - this.res.write(`event: endpoint\ndata: ${relativeUrlWithSession}\n\n`); - this._sseResponse = this.res; - this.res.on('close', () => { - var _a; - this._sseResponse = undefined; - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - }); - } - /** - * Handles incoming POST messages. - * - * This should be called when a POST request is made to send a message to the server. - */ - async handlePostMessage(req, res, parsedBody) { - var _a, _b, _c, _d; - if (!this._sseResponse) { - const message = 'SSE connection not established'; - res.writeHead(500).end(message); - throw new Error(message); - } - // Validate request headers for DNS rebinding protection - const validationError = this.validateRequestHeaders(req); - if (validationError) { - res.writeHead(403).end(validationError); - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(validationError)); - return; - } - const authInfo = req.auth; - const requestInfo = { headers: req.headers }; - let body; - try { - const ct = content_type_1.default.parse((_b = req.headers['content-type']) !== null && _b !== void 0 ? _b : ''); - if (ct.type !== 'application/json') { - throw new Error(`Unsupported content-type: ${ct.type}`); - } - body = - parsedBody !== null && parsedBody !== void 0 ? parsedBody : (await (0, raw_body_1.default)(req, { - limit: MAXIMUM_MESSAGE_SIZE, - encoding: (_c = ct.parameters.charset) !== null && _c !== void 0 ? _c : 'utf-8' - })); - } - catch (error) { - res.writeHead(400).end(String(error)); - (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error); - return; - } - try { - await this.handleMessage(typeof body === 'string' ? JSON.parse(body) : body, { requestInfo, authInfo }); - } - catch (_e) { - res.writeHead(400).end(`Invalid message: ${body}`); - return; - } - res.writeHead(202).end('Accepted'); - } - /** - * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. - */ - async handleMessage(message, extra) { - var _a, _b; - let parsedMessage; - try { - parsedMessage = types_js_1.JSONRPCMessageSchema.parse(message); - } - catch (error) { - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - throw error; - } - (_b = this.onmessage) === null || _b === void 0 ? void 0 : _b.call(this, parsedMessage, extra); - } - async close() { - var _a, _b; - (_a = this._sseResponse) === null || _a === void 0 ? void 0 : _a.end(); - this._sseResponse = undefined; - (_b = this.onclose) === null || _b === void 0 ? void 0 : _b.call(this); - } - async send(message) { - if (!this._sseResponse) { - throw new Error('Not connected'); - } - this._sseResponse.write(`event: message\ndata: ${JSON.stringify(message)}\n\n`); - } - /** - * Returns the session ID for this transport. - * - * This can be used to route incoming POST requests. - */ - get sessionId() { - return this._sessionId; - } -} -exports.SSEServerTransport = SSEServerTransport; -//# sourceMappingURL=sse.js.map \ No newline at end of file diff --git a/dist/cjs/server/sse.js.map b/dist/cjs/server/sse.js.map deleted file mode 100644 index 7eaf7edfb3..0000000000 --- a/dist/cjs/server/sse.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"sse.js","sourceRoot":"","sources":["../../../src/server/sse.ts"],"names":[],"mappings":";;;;;;AAAA,6CAAyC;AAGzC,0CAAkG;AAClG,wDAAkC;AAClC,gEAAuC;AAEvC,6BAA0B;AAE1B,MAAM,oBAAoB,GAAG,KAAK,CAAC;AAyBnC;;;;;GAKG;AACH,MAAa,kBAAkB;IAQ3B;;OAEG;IACH,YACY,SAAiB,EACjB,GAAmB,EAC3B,OAAmC;QAF3B,cAAS,GAAT,SAAS,CAAQ;QACjB,QAAG,GAAH,GAAG,CAAgB;QAG3B,IAAI,CAAC,UAAU,GAAG,IAAA,wBAAU,GAAE,CAAC;QAC/B,IAAI,CAAC,QAAQ,GAAG,OAAO,IAAI,EAAE,4BAA4B,EAAE,KAAK,EAAE,CAAC;IACvE,CAAC;IAED;;;OAGG;IACK,sBAAsB,CAAC,GAAoB;QAC/C,+CAA+C;QAC/C,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,4BAA4B,EAAE,CAAC;YAC9C,OAAO,SAAS,CAAC;QACrB,CAAC;QAED,qDAAqD;QACrD,IAAI,IAAI,CAAC,QAAQ,CAAC,YAAY,IAAI,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtE,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,IAAI,CAAC;YACpC,IAAI,CAAC,UAAU,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE,CAAC;gBAClE,OAAO,wBAAwB,UAAU,EAAE,CAAC;YAChD,CAAC;QACL,CAAC;QAED,yDAAyD;QACzD,IAAI,IAAI,CAAC,QAAQ,CAAC,cAAc,IAAI,IAAI,CAAC,QAAQ,CAAC,cAAc,C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,SAAS,CAAC;QAC9B,MAAA,IAAI,CAAC,OAAO,oDAAI,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,OAAuB;QAC9B,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;QACrC,CAAC;QAED,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,yBAAyB,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpF,CAAC;IAED;;;;OAIG;IACH,IAAI,SAAS;QACT,OAAO,IAAI,CAAC,UAAU,CAAC;IAC3B,CAAC;CACJ;AA7KD,gDA6KC"} \ No newline at end of file diff --git a/dist/cjs/server/stdio.d.ts b/dist/cjs/server/stdio.d.ts deleted file mode 100644 index df3029d0da..0000000000 --- a/dist/cjs/server/stdio.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { Readable, Writable } from 'node:stream'; -import { JSONRPCMessage } from '../types.js'; -import { Transport } from '../shared/transport.js'; -/** - * Server transport for stdio: this communicates with a MCP client by reading from the current process' stdin and writing to stdout. - * - * This transport is only available in Node.js environments. - */ -export declare class StdioServerTransport implements Transport { - private _stdin; - private _stdout; - private _readBuffer; - private _started; - constructor(_stdin?: Readable, _stdout?: Writable); - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage) => void; - _ondata: (chunk: Buffer) => void; - _onerror: (error: Error) => void; - /** - * Starts listening for messages on stdin. - */ - start(): Promise; - private processReadBuffer; - close(): Promise; - send(message: JSONRPCMessage): Promise; -} -//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/stdio.d.ts.map b/dist/cjs/server/stdio.d.ts.map deleted file mode 100644 index fdd2dfe48e..0000000000 --- a/dist/cjs/server/stdio.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/server/stdio.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;;;GAIG;AACH,qBAAa,oBAAqB,YAAW,SAAS;IAK9C,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,OAAO;IALnB,OAAO,CAAC,WAAW,CAAgC;IACnD,OAAO,CAAC,QAAQ,CAAS;gBAGb,MAAM,GAAE,QAAwB,EAChC,OAAO,GAAE,QAAyB;IAG9C,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;IAG9C,OAAO,UAAW,MAAM,UAGtB;IACF,QAAQ,UAAW,KAAK,UAEtB;IAEF;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAY5B,OAAO,CAAC,iBAAiB;IAenB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAkB5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAU/C"} \ No newline at end of file diff --git a/dist/cjs/server/stdio.js b/dist/cjs/server/stdio.js deleted file mode 100644 index e60d19caf9..0000000000 --- a/dist/cjs/server/stdio.js +++ /dev/null @@ -1,85 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.StdioServerTransport = void 0; -const node_process_1 = __importDefault(require("node:process")); -const stdio_js_1 = require("../shared/stdio.js"); -/** - * Server transport for stdio: this communicates with a MCP client by reading from the current process' stdin and writing to stdout. - * - * This transport is only available in Node.js environments. - */ -class StdioServerTransport { - constructor(_stdin = node_process_1.default.stdin, _stdout = node_process_1.default.stdout) { - this._stdin = _stdin; - this._stdout = _stdout; - this._readBuffer = new stdio_js_1.ReadBuffer(); - this._started = false; - // Arrow functions to bind `this` properly, while maintaining function identity. - this._ondata = (chunk) => { - this._readBuffer.append(chunk); - this.processReadBuffer(); - }; - this._onerror = (error) => { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }; - } - /** - * Starts listening for messages on stdin. - */ - async start() { - if (this._started) { - throw new Error('StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.'); - } - this._started = true; - this._stdin.on('data', this._ondata); - this._stdin.on('error', this._onerror); - } - processReadBuffer() { - var _a, _b; - while (true) { - try { - const message = this._readBuffer.readMessage(); - if (message === null) { - break; - } - (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message); - } - catch (error) { - (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); - } - } - } - async close() { - var _a; - // Remove our event listeners first - this._stdin.off('data', this._ondata); - this._stdin.off('error', this._onerror); - // Check if we were the only data listener - const remainingDataListeners = this._stdin.listenerCount('data'); - if (remainingDataListeners === 0) { - // Only pause stdin if we were the only listener - // This prevents interfering with other parts of the application that might be using stdin - this._stdin.pause(); - } - // Clear the buffer and notify closure - this._readBuffer.clear(); - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - } - send(message) { - return new Promise(resolve => { - const json = (0, stdio_js_1.serializeMessage)(message); - if (this._stdout.write(json)) { - resolve(); - } - else { - this._stdout.once('drain', resolve); - } - }); - } -} -exports.StdioServerTransport = StdioServerTransport; -//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/dist/cjs/server/stdio.js.map b/dist/cjs/server/stdio.js.map deleted file mode 100644 index 9397ec5d28..0000000000 --- a/dist/cjs/server/stdio.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/server/stdio.ts"],"names":[],"mappings":";;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KAAK,EAAE,CAAC;gBACb,MAAA,IAAI,CAAC,OAAO,qDAAG,KAAc,CAAC,CAAC;YACnC,CAAC;QACL,CAAC;IACL,CAAC;IAED,KAAK,CAAC,KAAK;;QACP,mCAAmC;QACnC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;QACtC,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,OAAO,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC;QAExC,0CAA0C;QAC1C,MAAM,sBAAsB,GAAG,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC;QACjE,IAAI,sBAAsB,KAAK,CAAC,EAAE,CAAC;YAC/B,gDAAgD;YAChD,0FAA0F;YAC1F,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QACxB,CAAC;QAED,sCAAsC;QACtC,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;QACzB,MAAA,IAAI,CAAC,OAAO,oDAAI,CAAC;IACrB,CAAC;IAED,IAAI,CAAC,OAAuB;QACxB,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE;YACzB,MAAM,IAAI,GAAG,IAAA,2BAAgB,EAAC,OAAO,CAAC,CAAC;YACvC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC3B,OAAO,EAAE,CAAC;YACd,CAAC;iBAAM,CAAC;gBACJ,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAhFD,oDAgFC"} \ No newline at end of file diff --git a/dist/cjs/server/streamableHttp.d.ts b/dist/cjs/server/streamableHttp.d.ts deleted file mode 100644 index cdad6d6593..0000000000 --- a/dist/cjs/server/streamableHttp.d.ts +++ /dev/null @@ -1,185 +0,0 @@ -import { IncomingMessage, ServerResponse } from 'node:http'; -import { Transport } from '../shared/transport.js'; -import { MessageExtraInfo, JSONRPCMessage, RequestId } from '../types.js'; -import { AuthInfo } from './auth/types.js'; -export type StreamId = string; -export type EventId = string; -/** - * Interface for resumability support via event storage - */ -export interface EventStore { - /** - * Stores an event for later retrieval - * @param streamId ID of the stream the event belongs to - * @param message The JSON-RPC message to store - * @returns The generated event ID for the stored event - */ - storeEvent(streamId: StreamId, message: JSONRPCMessage): Promise; - replayEventsAfter(lastEventId: EventId, { send }: { - send: (eventId: EventId, message: JSONRPCMessage) => Promise; - }): Promise; -} -/** - * Configuration options for StreamableHTTPServerTransport - */ -export interface StreamableHTTPServerTransportOptions { - /** - * Function that generates a session ID for the transport. - * The session ID SHOULD be globally unique and cryptographically secure (e.g., a securely generated UUID, a JWT, or a cryptographic hash) - * - * Return undefined to disable session management. - */ - sessionIdGenerator: (() => string) | undefined; - /** - * A callback for session initialization events - * This is called when the server initializes a new session. - * Useful in cases when you need to register multiple mcp sessions - * and need to keep track of them. - * @param sessionId The generated session ID - */ - onsessioninitialized?: (sessionId: string) => void | Promise; - /** - * A callback for session close events - * This is called when the server closes a session due to a DELETE request. - * Useful in cases when you need to clean up resources associated with the session. - * Note that this is different from the transport closing, if you are handling - * HTTP requests from multiple nodes you might want to close each - * StreamableHTTPServerTransport after a request is completed while still keeping the - * session open/running. - * @param sessionId The session ID that was closed - */ - onsessionclosed?: (sessionId: string) => void | Promise; - /** - * If true, the server will return JSON responses instead of starting an SSE stream. - * This can be useful for simple request/response scenarios without streaming. - * Default is false (SSE streams are preferred). - */ - enableJsonResponse?: boolean; - /** - * Event store for resumability support - * If provided, resumability will be enabled, allowing clients to reconnect and resume messages - */ - eventStore?: EventStore; - /** - * List of allowed host header values for DNS rebinding protection. - * If not specified, host validation is disabled. - */ - allowedHosts?: string[]; - /** - * List of allowed origin header values for DNS rebinding protection. - * If not specified, origin validation is disabled. - */ - allowedOrigins?: string[]; - /** - * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). - * Default is false for backwards compatibility. - */ - enableDnsRebindingProtection?: boolean; -} -/** - * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. - * It supports both SSE streaming and direct HTTP responses. - * - * Usage example: - * - * ```typescript - * // Stateful mode - server sets the session ID - * const statefulTransport = new StreamableHTTPServerTransport({ - * sessionIdGenerator: () => randomUUID(), - * }); - * - * // Stateless mode - explicitly set session ID to undefined - * const statelessTransport = new StreamableHTTPServerTransport({ - * sessionIdGenerator: undefined, - * }); - * - * // Using with pre-parsed request body - * app.post('/mcp', (req, res) => { - * transport.handleRequest(req, res, req.body); - * }); - * ``` - * - * In stateful mode: - * - Session ID is generated and included in response headers - * - Session ID is always included in initialization responses - * - Requests with invalid session IDs are rejected with 404 Not Found - * - Non-initialization requests without a session ID are rejected with 400 Bad Request - * - State is maintained in-memory (connections, message history) - * - * In stateless mode: - * - No Session ID is included in any responses - * - No session validation is performed - */ -export declare class StreamableHTTPServerTransport implements Transport { - private sessionIdGenerator; - private _started; - private _streamMapping; - private _requestToStreamMapping; - private _requestResponseMap; - private _initialized; - private _enableJsonResponse; - private _standaloneSseStreamId; - private _eventStore?; - private _onsessioninitialized?; - private _onsessionclosed?; - private _allowedHosts?; - private _allowedOrigins?; - private _enableDnsRebindingProtection; - sessionId?: string; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; - constructor(options: StreamableHTTPServerTransportOptions); - /** - * Starts the transport. This is required by the Transport interface but is a no-op - * for the Streamable HTTP transport as connections are managed per-request. - */ - start(): Promise; - /** - * Validates request headers for DNS rebinding protection. - * @returns Error message if validation fails, undefined if validation passes. - */ - private validateRequestHeaders; - /** - * Handles an incoming HTTP request, whether GET or POST - */ - handleRequest(req: IncomingMessage & { - auth?: AuthInfo; - }, res: ServerResponse, parsedBody?: unknown): Promise; - /** - * Handles GET requests for SSE stream - */ - private handleGetRequest; - /** - * Replays events that would have been sent after the specified event ID - * Only used when resumability is enabled - */ - private replayEvents; - /** - * Writes an event to the SSE stream with proper formatting - */ - private writeSSEEvent; - /** - * Handles unsupported requests (PUT, PATCH, etc.) - */ - private handleUnsupportedRequest; - /** - * Handles POST requests containing JSON-RPC messages - */ - private handlePostRequest; - /** - * Handles DELETE requests to terminate sessions - */ - private handleDeleteRequest; - /** - * Validates session ID for non-initialization requests - * Returns true if the session is valid, false otherwise - */ - private validateSession; - private validateProtocolVersion; - close(): Promise; - send(message: JSONRPCMessage, options?: { - relatedRequestId?: RequestId; - }): Promise; -} -//# sourceMappingURL=streamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/streamableHttp.d.ts.map b/dist/cjs/server/streamableHttp.d.ts.map deleted file mode 100644 index b0b33e921d..0000000000 --- a/dist/cjs/server/streamableHttp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"streamableHttp.d.ts","sourceRoot":"","sources":["../../../src/server/streamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EACH,gBAAgB,EAMhB,cAAc,EAEd,SAAS,EAGZ,MAAM,aAAa,CAAC;AAIrB,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAI3C,MAAM,MAAM,QAAQ,GAAG,MAAM,CAAC;AAC9B,MAAM,MAAM,OAAO,GAAG,MAAM,CAAC;AAE7B;;GAEG;AACH,MAAM,WAAW,UAAU;IACvB;;;;;OAKG;IACH,UAAU,CAAC,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAE1E,iBAAiB,CACb,WAAW,EAAE,OAAO,EACpB,EACI,IAAI,EACP,EAAE;QACC,IAAI,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,cAAc,KAAK,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C,CAAW;IACnC,OAAO,CAAC,6BAA6B,CAAU;IAE/C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE,gBAAgB,KAAK,IAAI,CAAC;gBAE5D,OAAO,EAAE,oCAAoC;IAWzD;;;OAGG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAO5B;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IAyB9B;;OAEG;IACG,aAAa,CAAC,GAAG,EAAE,eAAe,GAAG;QAAE,IAAI,CAAC,EAAE,QAAQ,CAAA;KAAE,EAAE,GAAG,EAAE,cAAc,EAAE,UAAU,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IA6BzH;;OAEG;YACW,gBAAgB;IAiF9B;;;OAGG;YACW,YAAY;IAmC1B;;OAEG;IACH,OAAO,CAAC,aAAa;IAWrB;;OAEG;YACW,wBAAwB;IAetC;;OAEG;YACW,iBAAiB;IAuL/B;;OAEG;YACW,mBAAmB;IAYjC;;;OAGG;IACH,OAAO,CAAC,eAAe;IAkEvB,OAAO,CAAC,uBAAuB;IAsBzB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAYtB,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,SAAS,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CA+FjG"} \ No newline at end of file diff --git a/dist/cjs/server/streamableHttp.js b/dist/cjs/server/streamableHttp.js deleted file mode 100644 index c99e9f228a..0000000000 --- a/dist/cjs/server/streamableHttp.js +++ /dev/null @@ -1,631 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.StreamableHTTPServerTransport = void 0; -const types_js_1 = require("../types.js"); -const raw_body_1 = __importDefault(require("raw-body")); -const content_type_1 = __importDefault(require("content-type")); -const node_crypto_1 = require("node:crypto"); -const MAXIMUM_MESSAGE_SIZE = '4mb'; -/** - * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. - * It supports both SSE streaming and direct HTTP responses. - * - * Usage example: - * - * ```typescript - * // Stateful mode - server sets the session ID - * const statefulTransport = new StreamableHTTPServerTransport({ - * sessionIdGenerator: () => randomUUID(), - * }); - * - * // Stateless mode - explicitly set session ID to undefined - * const statelessTransport = new StreamableHTTPServerTransport({ - * sessionIdGenerator: undefined, - * }); - * - * // Using with pre-parsed request body - * app.post('/mcp', (req, res) => { - * transport.handleRequest(req, res, req.body); - * }); - * ``` - * - * In stateful mode: - * - Session ID is generated and included in response headers - * - Session ID is always included in initialization responses - * - Requests with invalid session IDs are rejected with 404 Not Found - * - Non-initialization requests without a session ID are rejected with 400 Bad Request - * - State is maintained in-memory (connections, message history) - * - * In stateless mode: - * - No Session ID is included in any responses - * - No session validation is performed - */ -class StreamableHTTPServerTransport { - constructor(options) { - var _a, _b; - this._started = false; - this._streamMapping = new Map(); - this._requestToStreamMapping = new Map(); - this._requestResponseMap = new Map(); - this._initialized = false; - this._enableJsonResponse = false; - this._standaloneSseStreamId = '_GET_stream'; - this.sessionIdGenerator = options.sessionIdGenerator; - this._enableJsonResponse = (_a = options.enableJsonResponse) !== null && _a !== void 0 ? _a : false; - this._eventStore = options.eventStore; - this._onsessioninitialized = options.onsessioninitialized; - this._onsessionclosed = options.onsessionclosed; - this._allowedHosts = options.allowedHosts; - this._allowedOrigins = options.allowedOrigins; - this._enableDnsRebindingProtection = (_b = options.enableDnsRebindingProtection) !== null && _b !== void 0 ? _b : false; - } - /** - * Starts the transport. This is required by the Transport interface but is a no-op - * for the Streamable HTTP transport as connections are managed per-request. - */ - async start() { - if (this._started) { - throw new Error('Transport already started'); - } - this._started = true; - } - /** - * Validates request headers for DNS rebinding protection. - * @returns Error message if validation fails, undefined if validation passes. - */ - validateRequestHeaders(req) { - // Skip validation if protection is not enabled - if (!this._enableDnsRebindingProtection) { - return undefined; - } - // Validate Host header if allowedHosts is configured - if (this._allowedHosts && this._allowedHosts.length > 0) { - const hostHeader = req.headers.host; - if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { - return `Invalid Host header: ${hostHeader}`; - } - } - // Validate Origin header if allowedOrigins is configured - if (this._allowedOrigins && this._allowedOrigins.length > 0) { - const originHeader = req.headers.origin; - if (!originHeader || !this._allowedOrigins.includes(originHeader)) { - return `Invalid Origin header: ${originHeader}`; - } - } - return undefined; - } - /** - * Handles an incoming HTTP request, whether GET or POST - */ - async handleRequest(req, res, parsedBody) { - var _a; - // Validate request headers for DNS rebinding protection - const validationError = this.validateRequestHeaders(req); - if (validationError) { - res.writeHead(403).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: validationError - }, - id: null - })); - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(validationError)); - return; - } - if (req.method === 'POST') { - await this.handlePostRequest(req, res, parsedBody); - } - else if (req.method === 'GET') { - await this.handleGetRequest(req, res); - } - else if (req.method === 'DELETE') { - await this.handleDeleteRequest(req, res); - } - else { - await this.handleUnsupportedRequest(res); - } - } - /** - * Handles GET requests for SSE stream - */ - async handleGetRequest(req, res) { - // The client MUST include an Accept header, listing text/event-stream as a supported content type. - const acceptHeader = req.headers.accept; - if (!(acceptHeader === null || acceptHeader === void 0 ? void 0 : acceptHeader.includes('text/event-stream'))) { - res.writeHead(406).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Not Acceptable: Client must accept text/event-stream' - }, - id: null - })); - return; - } - // If an Mcp-Session-Id is returned by the server during initialization, - // clients using the Streamable HTTP transport MUST include it - // in the Mcp-Session-Id header on all of their subsequent HTTP requests. - if (!this.validateSession(req, res)) { - return; - } - if (!this.validateProtocolVersion(req, res)) { - return; - } - // Handle resumability: check for Last-Event-ID header - if (this._eventStore) { - const lastEventId = req.headers['last-event-id']; - if (lastEventId) { - await this.replayEvents(lastEventId, res); - return; - } - } - // The server MUST either return Content-Type: text/event-stream in response to this HTTP GET, - // or else return HTTP 405 Method Not Allowed - const headers = { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }; - // After initialization, always include the session ID if we have one - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - // Check if there's already an active standalone SSE stream for this session - if (this._streamMapping.get(this._standaloneSseStreamId) !== undefined) { - // Only one GET SSE stream is allowed per session - res.writeHead(409).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Conflict: Only one SSE stream is allowed per session' - }, - id: null - })); - return; - } - // We need to send headers immediately as messages will arrive much later, - // otherwise the client will just wait for the first message - res.writeHead(200, headers).flushHeaders(); - // Assign the response to the standalone SSE stream - this._streamMapping.set(this._standaloneSseStreamId, res); - // Set up close handler for client disconnects - res.on('close', () => { - this._streamMapping.delete(this._standaloneSseStreamId); - }); - // Add error handler for standalone SSE stream - res.on('error', error => { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }); - } - /** - * Replays events that would have been sent after the specified event ID - * Only used when resumability is enabled - */ - async replayEvents(lastEventId, res) { - var _a, _b; - if (!this._eventStore) { - return; - } - try { - const headers = { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }; - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - res.writeHead(200, headers).flushHeaders(); - const streamId = await ((_a = this._eventStore) === null || _a === void 0 ? void 0 : _a.replayEventsAfter(lastEventId, { - send: async (eventId, message) => { - var _a; - if (!this.writeSSEEvent(res, message, eventId)) { - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error('Failed replay events')); - res.end(); - } - } - })); - this._streamMapping.set(streamId, res); - // Add error handler for replay stream - res.on('error', error => { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }); - } - catch (error) { - (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); - } - } - /** - * Writes an event to the SSE stream with proper formatting - */ - writeSSEEvent(res, message, eventId) { - let eventData = `event: message\n`; - // Include event ID if provided - this is important for resumability - if (eventId) { - eventData += `id: ${eventId}\n`; - } - eventData += `data: ${JSON.stringify(message)}\n\n`; - return res.write(eventData); - } - /** - * Handles unsupported requests (PUT, PATCH, etc.) - */ - async handleUnsupportedRequest(res) { - res.writeHead(405, { - Allow: 'GET, POST, DELETE' - }).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Method not allowed.' - }, - id: null - })); - } - /** - * Handles POST requests containing JSON-RPC messages - */ - async handlePostRequest(req, res, parsedBody) { - var _a, _b, _c, _d, _e; - try { - // Validate the Accept header - const acceptHeader = req.headers.accept; - // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types. - if (!(acceptHeader === null || acceptHeader === void 0 ? void 0 : acceptHeader.includes('application/json')) || !acceptHeader.includes('text/event-stream')) { - res.writeHead(406).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Not Acceptable: Client must accept both application/json and text/event-stream' - }, - id: null - })); - return; - } - const ct = req.headers['content-type']; - if (!ct || !ct.includes('application/json')) { - res.writeHead(415).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Unsupported Media Type: Content-Type must be application/json' - }, - id: null - })); - return; - } - const authInfo = req.auth; - const requestInfo = { headers: req.headers }; - let rawMessage; - if (parsedBody !== undefined) { - rawMessage = parsedBody; - } - else { - const parsedCt = content_type_1.default.parse(ct); - const body = await (0, raw_body_1.default)(req, { - limit: MAXIMUM_MESSAGE_SIZE, - encoding: (_a = parsedCt.parameters.charset) !== null && _a !== void 0 ? _a : 'utf-8' - }); - rawMessage = JSON.parse(body.toString()); - } - let messages; - // handle batch and single messages - if (Array.isArray(rawMessage)) { - messages = rawMessage.map(msg => types_js_1.JSONRPCMessageSchema.parse(msg)); - } - else { - messages = [types_js_1.JSONRPCMessageSchema.parse(rawMessage)]; - } - // Check if this is an initialization request - // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/ - const isInitializationRequest = messages.some(types_js_1.isInitializeRequest); - if (isInitializationRequest) { - // If it's a server with session management and the session ID is already set we should reject the request - // to avoid re-initialization. - if (this._initialized && this.sessionId !== undefined) { - res.writeHead(400).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32600, - message: 'Invalid Request: Server already initialized' - }, - id: null - })); - return; - } - if (messages.length > 1) { - res.writeHead(400).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32600, - message: 'Invalid Request: Only one initialization request is allowed' - }, - id: null - })); - return; - } - this.sessionId = (_b = this.sessionIdGenerator) === null || _b === void 0 ? void 0 : _b.call(this); - this._initialized = true; - // If we have a session ID and an onsessioninitialized handler, call it immediately - // This is needed in cases where the server needs to keep track of multiple sessions - if (this.sessionId && this._onsessioninitialized) { - await Promise.resolve(this._onsessioninitialized(this.sessionId)); - } - } - if (!isInitializationRequest) { - // If an Mcp-Session-Id is returned by the server during initialization, - // clients using the Streamable HTTP transport MUST include it - // in the Mcp-Session-Id header on all of their subsequent HTTP requests. - if (!this.validateSession(req, res)) { - return; - } - // Mcp-Protocol-Version header is required for all requests after initialization. - if (!this.validateProtocolVersion(req, res)) { - return; - } - } - // check if it contains requests - const hasRequests = messages.some(types_js_1.isJSONRPCRequest); - if (!hasRequests) { - // if it only contains notifications or responses, return 202 - res.writeHead(202).end(); - // handle each message - for (const message of messages) { - (_c = this.onmessage) === null || _c === void 0 ? void 0 : _c.call(this, message, { authInfo, requestInfo }); - } - } - else if (hasRequests) { - // The default behavior is to use SSE streaming - // but in some cases server will return JSON responses - const streamId = (0, node_crypto_1.randomUUID)(); - if (!this._enableJsonResponse) { - const headers = { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache', - Connection: 'keep-alive' - }; - // After initialization, always include the session ID if we have one - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - res.writeHead(200, headers); - } - // Store the response for this request to send messages back through this connection - // We need to track by request ID to maintain the connection - for (const message of messages) { - if ((0, types_js_1.isJSONRPCRequest)(message)) { - this._streamMapping.set(streamId, res); - this._requestToStreamMapping.set(message.id, streamId); - } - } - // Set up close handler for client disconnects - res.on('close', () => { - this._streamMapping.delete(streamId); - }); - // Add error handler for stream write errors - res.on('error', error => { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }); - // handle each message - for (const message of messages) { - (_d = this.onmessage) === null || _d === void 0 ? void 0 : _d.call(this, message, { authInfo, requestInfo }); - } - // The server SHOULD NOT close the SSE stream before sending all JSON-RPC responses - // This will be handled by the send() method when responses are ready - } - } - catch (error) { - // return JSON-RPC formatted error - res.writeHead(400).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32700, - message: 'Parse error', - data: String(error) - }, - id: null - })); - (_e = this.onerror) === null || _e === void 0 ? void 0 : _e.call(this, error); - } - } - /** - * Handles DELETE requests to terminate sessions - */ - async handleDeleteRequest(req, res) { - var _a; - if (!this.validateSession(req, res)) { - return; - } - if (!this.validateProtocolVersion(req, res)) { - return; - } - await Promise.resolve((_a = this._onsessionclosed) === null || _a === void 0 ? void 0 : _a.call(this, this.sessionId)); - await this.close(); - res.writeHead(200).end(); - } - /** - * Validates session ID for non-initialization requests - * Returns true if the session is valid, false otherwise - */ - validateSession(req, res) { - if (this.sessionIdGenerator === undefined) { - // If the sessionIdGenerator ID is not set, the session management is disabled - // and we don't need to validate the session ID - return true; - } - if (!this._initialized) { - // If the server has not been initialized yet, reject all requests - res.writeHead(400).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: Server not initialized' - }, - id: null - })); - return false; - } - const sessionId = req.headers['mcp-session-id']; - if (!sessionId) { - // Non-initialization requests without a session ID should return 400 Bad Request - res.writeHead(400).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: Mcp-Session-Id header is required' - }, - id: null - })); - return false; - } - else if (Array.isArray(sessionId)) { - res.writeHead(400).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: Mcp-Session-Id header must be a single value' - }, - id: null - })); - return false; - } - else if (sessionId !== this.sessionId) { - // Reject requests with invalid session ID with 404 Not Found - res.writeHead(404).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32001, - message: 'Session not found' - }, - id: null - })); - return false; - } - return true; - } - validateProtocolVersion(req, res) { - var _a; - let protocolVersion = (_a = req.headers['mcp-protocol-version']) !== null && _a !== void 0 ? _a : types_js_1.DEFAULT_NEGOTIATED_PROTOCOL_VERSION; - if (Array.isArray(protocolVersion)) { - protocolVersion = protocolVersion[protocolVersion.length - 1]; - } - if (!types_js_1.SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) { - res.writeHead(400).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: `Bad Request: Unsupported protocol version (supported versions: ${types_js_1.SUPPORTED_PROTOCOL_VERSIONS.join(', ')})` - }, - id: null - })); - return false; - } - return true; - } - async close() { - var _a; - // Close all SSE connections - this._streamMapping.forEach(response => { - response.end(); - }); - this._streamMapping.clear(); - // Clear any pending responses - this._requestResponseMap.clear(); - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - } - async send(message, options) { - let requestId = options === null || options === void 0 ? void 0 : options.relatedRequestId; - if ((0, types_js_1.isJSONRPCResponse)(message) || (0, types_js_1.isJSONRPCError)(message)) { - // If the message is a response, use the request ID from the message - requestId = message.id; - } - // Check if this message should be sent on the standalone SSE stream (no request ID) - // Ignore notifications from tools (which have relatedRequestId set) - // Those will be sent via dedicated response SSE streams - if (requestId === undefined) { - // For standalone SSE streams, we can only send requests and notifications - if ((0, types_js_1.isJSONRPCResponse)(message) || (0, types_js_1.isJSONRPCError)(message)) { - throw new Error('Cannot send a response on a standalone SSE stream unless resuming a previous client request'); - } - const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); - if (standaloneSse === undefined) { - // The spec says the server MAY send messages on the stream, so it's ok to discard if no stream - return; - } - // Generate and store event ID if event store is provided - let eventId; - if (this._eventStore) { - // Stores the event and gets the generated event ID - eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); - } - // Send the message to the standalone SSE stream - this.writeSSEEvent(standaloneSse, message, eventId); - return; - } - // Get the response for this request - const streamId = this._requestToStreamMapping.get(requestId); - const response = this._streamMapping.get(streamId); - if (!streamId) { - throw new Error(`No connection established for request ID: ${String(requestId)}`); - } - if (!this._enableJsonResponse) { - // For SSE responses, generate event ID if event store is provided - let eventId; - if (this._eventStore) { - eventId = await this._eventStore.storeEvent(streamId, message); - } - if (response) { - // Write the event to the response stream - this.writeSSEEvent(response, message, eventId); - } - } - if ((0, types_js_1.isJSONRPCResponse)(message) || (0, types_js_1.isJSONRPCError)(message)) { - this._requestResponseMap.set(requestId, message); - const relatedIds = Array.from(this._requestToStreamMapping.entries()) - .filter(([_, streamId]) => this._streamMapping.get(streamId) === response) - .map(([id]) => id); - // Check if we have responses for all requests using this connection - const allResponsesReady = relatedIds.every(id => this._requestResponseMap.has(id)); - if (allResponsesReady) { - if (!response) { - throw new Error(`No connection established for request ID: ${String(requestId)}`); - } - if (this._enableJsonResponse) { - // All responses ready, send as JSON - const headers = { - 'Content-Type': 'application/json' - }; - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - const responses = relatedIds.map(id => this._requestResponseMap.get(id)); - response.writeHead(200, headers); - if (responses.length === 1) { - response.end(JSON.stringify(responses[0])); - } - else { - response.end(JSON.stringify(responses)); - } - } - else { - // End the SSE stream - response.end(); - } - // Clean up - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - } - } - } -} -exports.StreamableHTTPServerTransport = StreamableHTTPServerTransport; -//# sourceMappingURL=streamableHttp.js.map \ No newline at end of file diff --git a/dist/cjs/server/streamableHttp.js.map b/dist/cjs/server/streamableHttp.js.map deleted file mode 100644 index 45bfddb41f..0000000000 --- a/dist/cjs/server/streamableHttp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"streamableHttp.js","sourceRoot":"","sources":["../../../src/server/streamableHttp.ts"],"names":[],"mappings":";;;;;;AAEA,0CAYqB;AACrB,wDAAkC;AAClC,gEAAuC;AACvC,6CAAyC;AAGzC,MAAM,oBAAoB,GAAG,KAAK,CAAC;AA4FnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAa,6BAA6B;IAsBtC,YAAY,OAA6C;;QAnBjD,aAAQ,GAAY,KAAK,CAAC;QAC1B,mBAAc,GAAgC,IAAI,GAAG,EAAE,CAAC;QACxD,4BAAuB,GAA2B,IAAI,GAAG,EAAE,CAAC;QAC5D,wBAAmB,GAAmC,IAAI,GAAG,EAAE,CAAC;QAChE,iBAAY,GAAY,KAAK,CAAC;QAC9B,wBAAmB,GAAY,KAAK,CAAC;QACrC,2BAAsB,GAAW,aAAa,CAAC;QAcnD,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC;QACrD,IAAI,CAAC,mBAAmB,GAAG,MAAA,OAAO,CAAC,kBAAkB,mCAAI,KAAK,CAAC;QAC/D,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC;QACtC,IAAI,CAAC,qBAAqB,GAAG,OAAO,CAAC,oBAAoB,CAAC;QAC1D,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC,eAAe,CAAC;QAChD,IAAI,CAAC,aAAa,GAAG,OAAO,CAAC,YAAY,CAAC;QAC1C,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,cAAc,CAAC;QAC9C,IAAI,CAAC,6BAA6B,GAA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IAAI,CAAC,mBAAmB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;oBACpC,IAAI,CAAC,uBAAuB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBAC5C,CAAC;YACL,CAAC;QACL,CAAC;IACL,CAAC;CACJ;AAppBD,sEAopBC"} \ No newline at end of file diff --git a/dist/cjs/server/zod-compat.d.ts b/dist/cjs/server/zod-compat.d.ts deleted file mode 100644 index 13fb9723c5..0000000000 --- a/dist/cjs/server/zod-compat.d.ts +++ /dev/null @@ -1,82 +0,0 @@ -import type * as z3 from 'zod/v3'; -import type * as z4 from 'zod/v4/core'; -export type AnySchema = z3.ZodTypeAny | z4.$ZodType; -export type AnyObjectSchema = z3.AnyZodObject | z4.$ZodObject | AnySchema; -export type ZodRawShapeCompat = Record; -export interface ZodV3Internal { - _def?: { - typeName?: string; - value?: unknown; - values?: unknown[]; - shape?: Record | (() => Record); - description?: string; - }; - shape?: Record | (() => Record); - value?: unknown; -} -export interface ZodV4Internal { - _zod?: { - def?: { - typeName?: string; - value?: unknown; - values?: unknown[]; - shape?: Record | (() => Record); - description?: string; - }; - }; - value?: unknown; -} -export type SchemaOutput = S extends z3.ZodTypeAny ? z3.infer : S extends z4.$ZodType ? z4.output : never; -export type SchemaInput = S extends z3.ZodTypeAny ? z3.input : S extends z4.$ZodType ? z4.input : never; -/** - * Infers the output type from a ZodRawShapeCompat (raw shape object). - * Maps over each key in the shape and infers the output type from each schema. - */ -export type ShapeOutput = { - [K in keyof Shape]: SchemaOutput; -}; -export declare function isZ4Schema(s: AnySchema): s is z4.$ZodType; -export declare function objectFromShape(shape: ZodRawShapeCompat): AnyObjectSchema; -export declare function safeParse(schema: S, data: unknown): { - success: true; - data: SchemaOutput; -} | { - success: false; - error: unknown; -}; -export declare function safeParseAsync(schema: S, data: unknown): Promise<{ - success: true; - data: SchemaOutput; -} | { - success: false; - error: unknown; -}>; -export declare function getObjectShape(schema: AnyObjectSchema | undefined): Record | undefined; -/** - * Normalizes a schema to an object schema. Handles both: - * - Already-constructed object schemas (v3 or v4) - * - Raw shapes that need to be wrapped into object schemas - */ -export declare function normalizeObjectSchema(schema: AnySchema | ZodRawShapeCompat | undefined): AnyObjectSchema | undefined; -/** - * Safely extracts an error message from a parse result error. - * Zod errors can have different structures, so we handle various cases. - */ -export declare function getParseErrorMessage(error: unknown): string; -/** - * Gets the description from a schema, if available. - * Works with both Zod v3 and v4. - */ -export declare function getSchemaDescription(schema: AnySchema): string | undefined; -/** - * Checks if a schema is optional. - * Works with both Zod v3 and v4. - */ -export declare function isSchemaOptional(schema: AnySchema): boolean; -/** - * Gets the literal value from a schema, if it's a literal schema. - * Works with both Zod v3 and v4. - * Returns undefined if the schema is not a literal or the value cannot be determined. - */ -export declare function getLiteralValue(schema: AnySchema): unknown; -//# sourceMappingURL=zod-compat.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/zod-compat.d.ts.map b/dist/cjs/server/zod-compat.d.ts.map deleted file mode 100644 index 608ca930c3..0000000000 --- a/dist/cjs/server/zod-compat.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"zod-compat.d.ts","sourceRoot":"","sources":["../../../src/server/zod-compat.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,KAAK,EAAE,MAAM,QAAQ,CAAC;AAClC,OAAO,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAMvC,MAAM,MAAM,SAAS,GAAG,EAAE,CAAC,UAAU,GAAG,EAAE,CAAC,QAAQ,CAAC;AACpD,MAAM,MAAM,eAAe,GAAG,EAAE,CAAC,YAAY,GAAG,EAAE,CAAC,UAAU,GAAG,SAAS,CAAC;AAC1E,MAAM,MAAM,iBAAiB,GAAG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,CAAC;AAI1D,MAAM,WAAW,aAAa;IAC1B,IAAI,CAAC,EAAE;QACH,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,KAAK,CAAC,EAAE,OAAO,CAAC;QAChB,MAAM,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,CAQ1E;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAW3D;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAwB1D"} \ No newline at end of file diff --git a/dist/cjs/server/zod-compat.js b/dist/cjs/server/zod-compat.js deleted file mode 100644 index 602a9bf188..0000000000 --- a/dist/cjs/server/zod-compat.js +++ /dev/null @@ -1,252 +0,0 @@ -"use strict"; -// zod-compat.ts -// ---------------------------------------------------- -// Unified types + helpers to accept Zod v3 and v4 (Mini) -// ---------------------------------------------------- -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isZ4Schema = isZ4Schema; -exports.objectFromShape = objectFromShape; -exports.safeParse = safeParse; -exports.safeParseAsync = safeParseAsync; -exports.getObjectShape = getObjectShape; -exports.normalizeObjectSchema = normalizeObjectSchema; -exports.getParseErrorMessage = getParseErrorMessage; -exports.getSchemaDescription = getSchemaDescription; -exports.isSchemaOptional = isSchemaOptional; -exports.getLiteralValue = getLiteralValue; -const z3rt = __importStar(require("zod/v3")); -const z4mini = __importStar(require("zod/v4-mini")); -// --- Runtime detection --- -function isZ4Schema(s) { - // Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3 - const schema = s; - return !!schema._zod; -} -// --- Schema construction --- -function objectFromShape(shape) { - const values = Object.values(shape); - if (values.length === 0) - return z4mini.object({}); // default to v4 Mini - const allV4 = values.every(isZ4Schema); - const allV3 = values.every(s => !isZ4Schema(s)); - if (allV4) - return z4mini.object(shape); - if (allV3) - return z3rt.object(shape); - throw new Error('Mixed Zod versions detected in object shape.'); -} -// --- Unified parsing --- -function safeParse(schema, data) { - if (isZ4Schema(schema)) { - // Mini exposes top-level safeParse - const result = z4mini.safeParse(schema, data); - return result; - } - const v3Schema = schema; - const result = v3Schema.safeParse(data); - return result; -} -async function safeParseAsync(schema, data) { - if (isZ4Schema(schema)) { - // Mini exposes top-level safeParseAsync - const result = await z4mini.safeParseAsync(schema, data); - return result; - } - const v3Schema = schema; - const result = await v3Schema.safeParseAsync(data); - return result; -} -// --- Shape extraction --- -function getObjectShape(schema) { - var _a, _b; - if (!schema) - return undefined; - // Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape` - let rawShape; - if (isZ4Schema(schema)) { - const v4Schema = schema; - rawShape = (_b = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def) === null || _b === void 0 ? void 0 : _b.shape; - } - else { - const v3Schema = schema; - rawShape = v3Schema.shape; - } - if (!rawShape) - return undefined; - if (typeof rawShape === 'function') { - try { - return rawShape(); - } - catch (_c) { - return undefined; - } - } - return rawShape; -} -// --- Schema normalization --- -/** - * Normalizes a schema to an object schema. Handles both: - * - Already-constructed object schemas (v3 or v4) - * - Raw shapes that need to be wrapped into object schemas - */ -function normalizeObjectSchema(schema) { - var _a; - if (!schema) - return undefined; - // First check if it's a raw shape (Record) - // Raw shapes don't have _def or _zod properties and aren't schemas themselves - if (typeof schema === 'object') { - // Check if it's actually a ZodRawShapeCompat (not a schema instance) - // by checking if it lacks schema-like internal properties - const asV3 = schema; - const asV4 = schema; - // If it's not a schema instance (no _def or _zod), it might be a raw shape - if (!asV3._def && !asV4._zod) { - // Check if all values are schemas (heuristic to confirm it's a raw shape) - const values = Object.values(schema); - if (values.length > 0 && - values.every(v => typeof v === 'object' && - v !== null && - (v._def !== undefined || - v._zod !== undefined || - typeof v.parse === 'function'))) { - return objectFromShape(schema); - } - } - } - // If we get here, it should be an AnySchema (not a raw shape) - // Check if it's already an object schema - if (isZ4Schema(schema)) { - // Check if it's a v4 object - const v4Schema = schema; - const def = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def; - if (def && (def.typeName === 'object' || def.shape !== undefined)) { - return schema; - } - } - else { - // Check if it's a v3 object - const v3Schema = schema; - if (v3Schema.shape !== undefined) { - return schema; - } - } - return undefined; -} -// --- Error message extraction --- -/** - * Safely extracts an error message from a parse result error. - * Zod errors can have different structures, so we handle various cases. - */ -function getParseErrorMessage(error) { - if (error && typeof error === 'object') { - // Try common error structures - if ('message' in error && typeof error.message === 'string') { - return error.message; - } - if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) { - const firstIssue = error.issues[0]; - if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) { - return String(firstIssue.message); - } - } - // Fallback: try to stringify the error - try { - return JSON.stringify(error); - } - catch (_a) { - return String(error); - } - } - return String(error); -} -// --- Schema metadata access --- -/** - * Gets the description from a schema, if available. - * Works with both Zod v3 and v4. - */ -function getSchemaDescription(schema) { - var _a, _b, _c, _d; - if (isZ4Schema(schema)) { - const v4Schema = schema; - return (_b = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def) === null || _b === void 0 ? void 0 : _b.description; - } - const v3Schema = schema; - // v3 may have description on the schema itself or in _def - return (_c = schema.description) !== null && _c !== void 0 ? _c : (_d = v3Schema._def) === null || _d === void 0 ? void 0 : _d.description; -} -/** - * Checks if a schema is optional. - * Works with both Zod v3 and v4. - */ -function isSchemaOptional(schema) { - var _a, _b, _c; - if (isZ4Schema(schema)) { - const v4Schema = schema; - return ((_b = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def) === null || _b === void 0 ? void 0 : _b.typeName) === 'ZodOptional'; - } - const v3Schema = schema; - // v3 has isOptional() method - if (typeof schema.isOptional === 'function') { - return schema.isOptional(); - } - return ((_c = v3Schema._def) === null || _c === void 0 ? void 0 : _c.typeName) === 'ZodOptional'; -} -/** - * Gets the literal value from a schema, if it's a literal schema. - * Works with both Zod v3 and v4. - * Returns undefined if the schema is not a literal or the value cannot be determined. - */ -function getLiteralValue(schema) { - var _a; - if (isZ4Schema(schema)) { - const v4Schema = schema; - const def = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def; - if (def) { - // Try various ways to get the literal value - if (def.value !== undefined) - return def.value; - if (Array.isArray(def.values) && def.values.length > 0) { - return def.values[0]; - } - } - } - const v3Schema = schema; - const def = v3Schema._def; - if (def) { - if (def.value !== undefined) - return def.value; - if (Array.isArray(def.values) && def.values.length > 0) { - return def.values[0]; - } - } - // Fallback: check for direct value property (some Zod versions) - const directValue = schema.value; - if (directValue !== undefined) - return directValue; - return undefined; -} -//# sourceMappingURL=zod-compat.js.map \ No newline at end of file diff --git a/dist/cjs/server/zod-compat.js.map b/dist/cjs/server/zod-compat.js.map deleted file mode 100644 index ef6828d204..0000000000 --- a/dist/cjs/server/zod-compat.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"zod-compat.js","sourceRoot":"","sources":["../../../src/server/zod-compat.ts"],"names":[],"mappings":";AAAA,gBAAgB;AAChB,uDAAuD;AACvD,yDAAyD;AACzD,uDAAuD;;;;;;;;;;;;;;;;;;;;;;;;;AAsDvD,gCAIC;AAGD,0CAWC;AAGD,8BAYC;AAED,wCAYC;AAGD,wCAyBC;AAQD,sDAiDC;AAOD,oDAoBC;AAOD,oDAQC;AAMD,4CAWC;AAOD,0CAwBC;AA/QD,6CAA+B;AAC/B,oDAAsC;AA+CtC,4BAA4B;AAC5B,SAAgB,UAAU,C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AAG,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACrD,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QACzB,CAAC;IACL,CAAC;IACD,gEAAgE;IAChE,MAAM,WAAW,GAAI,MAA8B,CAAC,KAAK,CAAC;IAC1D,IAAI,WAAW,KAAK,SAAS;QAAE,OAAO,WAAW,CAAC;IAClD,OAAO,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/server/zod-json-schema-compat.d.ts b/dist/cjs/server/zod-json-schema-compat.d.ts deleted file mode 100644 index 3a04452b47..0000000000 --- a/dist/cjs/server/zod-json-schema-compat.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { AnySchema, AnyObjectSchema } from './zod-compat.js'; -type JsonSchema = Record; -type CommonOpts = { - strictUnions?: boolean; - pipeStrategy?: 'input' | 'output'; - target?: 'jsonSchema7' | 'draft-7' | 'jsonSchema2019-09' | 'draft-2020-12'; -}; -export declare function toJsonSchemaCompat(schema: AnyObjectSchema, opts?: CommonOpts): JsonSchema; -export declare function getMethodLiteral(schema: AnyObjectSchema): string; -export declare function parseWithCompat(schema: AnySchema, data: unknown): unknown; -export {}; -//# sourceMappingURL=zod-json-schema-compat.d.ts.map \ No newline at end of file diff --git a/dist/cjs/server/zod-json-schema-compat.d.ts.map b/dist/cjs/server/zod-json-schema-compat.d.ts.map deleted file mode 100644 index 0b851bf50e..0000000000 --- a/dist/cjs/server/zod-json-schema-compat.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"zod-json-schema-compat.d.ts","sourceRoot":"","sources":["../../../src/server/zod-json-schema-compat.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,SAAS,EAAE,eAAe,EAA0D,MAAM,iBAAiB,CAAC;AAGrH,KAAK,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAG1C,KAAK,UAAU,GAAG;IACd,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;IAClC,MAAM,CAAC,EAAE,aAAa,GAAG,SAAS,GAAG,mBAAmB,GAAG,eAAe,CAAC;CAC9E,CAAC;AASF,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,eAAe,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,UAAU,CAczF;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,eAAe,GAAG,MAAM,CAahE;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,GAAG,OAAO,CAMzE"} \ No newline at end of file diff --git a/dist/cjs/server/zod-json-schema-compat.js b/dist/cjs/server/zod-json-schema-compat.js deleted file mode 100644 index e42265d4c6..0000000000 --- a/dist/cjs/server/zod-json-schema-compat.js +++ /dev/null @@ -1,80 +0,0 @@ -"use strict"; -// zod-json-schema-compat.ts -// ---------------------------------------------------- -// JSON Schema conversion for both Zod v3 and Zod v4 (Mini) -// v3 uses your vendored converter; v4 uses Mini's toJSONSchema -// ---------------------------------------------------- -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.toJsonSchemaCompat = toJsonSchemaCompat; -exports.getMethodLiteral = getMethodLiteral; -exports.parseWithCompat = parseWithCompat; -const z4mini = __importStar(require("zod/v4-mini")); -const zod_compat_js_1 = require("./zod-compat.js"); -const zod_to_json_schema_1 = require("zod-to-json-schema"); -function mapMiniTarget(t) { - if (!t) - return 'draft-7'; - if (t === 'jsonSchema7' || t === 'draft-7') - return 'draft-7'; - if (t === 'jsonSchema2019-09' || t === 'draft-2020-12') - return 'draft-2020-12'; - return 'draft-7'; // fallback -} -function toJsonSchemaCompat(schema, opts) { - var _a, _b, _c; - if ((0, zod_compat_js_1.isZ4Schema)(schema)) { - // v4 branch — use Mini's built-in toJSONSchema - return z4mini.toJSONSchema(schema, { - target: mapMiniTarget(opts === null || opts === void 0 ? void 0 : opts.target), - io: (_a = opts === null || opts === void 0 ? void 0 : opts.pipeStrategy) !== null && _a !== void 0 ? _a : 'input' - }); - } - // v3 branch — use vendored converter - return (0, zod_to_json_schema_1.zodToJsonSchema)(schema, { - strictUnions: (_b = opts === null || opts === void 0 ? void 0 : opts.strictUnions) !== null && _b !== void 0 ? _b : true, - pipeStrategy: (_c = opts === null || opts === void 0 ? void 0 : opts.pipeStrategy) !== null && _c !== void 0 ? _c : 'input' - }); -} -function getMethodLiteral(schema) { - const shape = (0, zod_compat_js_1.getObjectShape)(schema); - const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method; - if (!methodSchema) { - throw new Error('Schema is missing a method literal'); - } - const value = (0, zod_compat_js_1.getLiteralValue)(methodSchema); - if (typeof value !== 'string') { - throw new Error('Schema method literal must be a string'); - } - return value; -} -function parseWithCompat(schema, data) { - const result = (0, zod_compat_js_1.safeParse)(schema, data); - if (!result.success) { - throw result.error; - } - return result.data; -} -//# sourceMappingURL=zod-json-schema-compat.js.map \ No newline at end of file diff --git a/dist/cjs/server/zod-json-schema-compat.js.map b/dist/cjs/server/zod-json-schema-compat.js.map deleted file mode 100644 index 4cda29da48..0000000000 --- a/dist/cjs/server/zod-json-schema-compat.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"zod-json-schema-compat.js","sourceRoot":"","sources":["../../../src/server/zod-json-schema-compat.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,uDAAuD;AACvD,2DAA2D;AAC3D,+DAA+D;AAC/D,uDAAuD;;;;;;;;;;;;;;;;;;;;;;;;;AA0BvD,gDAcC;AAED,4CAaC;AAED,0CAMC;AA1DD,oDAAsC;AAEtC,mDAAqH;AACrH,2DAAqD;AAWrD,SAAS,aAAa,CAAC,CAAmC;IACtD,IAAI,CAAC,CAAC;QAAE,OAAO,SAAS,CAAC;IACzB,IAAI,CAAC,KAAK,aAAa,IAAI,CAAC,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC7D,IAAI,CAAC,KAAK,mBAAmB,IAAI,CAAC,KAAK,eAAe;QAAE,OAAO,eAAe,CAAC;IAC/E,OAAO,SAAS,CAAC,CAAC,WAAW;AACjC,CAAC;AAED,SAAgB,kBAAkB,CAAC,MAAuB,EAAE,IAAiB;;IACzE,IAAI,IAAA,0BAAU,EAAC,MAAM,CAAC,EAAE,CAAC;QACrB,+CAA+C;QAC/C,OAAO,MAAM,CAAC,YAAY,CAAC,MAAsB,EAAE;YAC/C,MAAM,EAAE,aAAa,CAAC,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,CAAC;YACnC,EAAE,EAAE,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,YAAY,mCAAI,OAAO;SACpC,CAAe,CAAC;IACrB,CAAC;IAED,qCAAqC;IACrC,OAAO,IAAA,oCAAe,EAAC,MAAuB,EAAE;QAC5C,YAAY,EAAE,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,YAAY,mCAAI,IAAI;QACxC,YAAY,EAAE,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,YAAY,mCAAI,OAAO;KAC9C,CAAe,CAAC;AACrB,CAAC;AAED,SAAgB,gBAAgB,CAAC,MAAuB;IACpD,MAAM,KAAK,GAAG,IAAA,8BAAc,EAAC,MAAM,CAAC,CAAC;IACrC,MAAM,YAAY,GAAG,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,MAA+B,CAAC;IAC5D,IAAI,CAAC,YAAY,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;IAC1D,CAAC;IAED,MAAM,KAAK,GAAG,IAAA,+BAAe,EAAC,YAAY,CAAC,CAAC;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;IAC9D,CAAC;IAED,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,SAAgB,eAAe,CAAC,MAAiB,EAAE,IAAa;IAC5D,MAAM,MAAM,GAAG,IAAA,yBAAS,EAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACvC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QAClB,MAAM,MAAM,CAAC,KAAK,CAAC;IACvB,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC;AACvB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/auth-utils.d.ts b/dist/cjs/shared/auth-utils.d.ts deleted file mode 100644 index c966e30e74..0000000000 --- a/dist/cjs/shared/auth-utils.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Utilities for handling OAuth resource URIs. - */ -/** - * Converts a server URL to a resource URL by removing the fragment. - * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". - * Keeps everything else unchanged (scheme, domain, port, path, query). - */ -export declare function resourceUrlFromServerUrl(url: URL | string): URL; -/** - * Checks if a requested resource URL matches a configured resource URL. - * A requested resource matches if it has the same scheme, domain, port, - * and its path starts with the configured resource's path. - * - * @param requestedResource The resource URL being requested - * @param configuredResource The resource URL that has been configured - * @returns true if the requested resource matches the configured resource, false otherwise - */ -export declare function checkResourceAllowed({ requestedResource, configuredResource }: { - requestedResource: URL | string; - configuredResource: URL | string; -}): boolean; -//# sourceMappingURL=auth-utils.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/auth-utils.d.ts.map b/dist/cjs/shared/auth-utils.d.ts.map deleted file mode 100644 index 30873de552..0000000000 --- a/dist/cjs/shared/auth-utils.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"auth-utils.d.ts","sourceRoot":"","sources":["../../../src/shared/auth-utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,GAAG,GAAG,CAI/D;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,EACjC,iBAAiB,EACjB,kBAAkB,EACrB,EAAE;IACC,iBAAiB,EAAE,GAAG,GAAG,MAAM,CAAC;IAChC,kBAAkB,EAAE,GAAG,GAAG,MAAM,CAAC;CACpC,GAAG,OAAO,CAwBV"} \ No newline at end of file diff --git a/dist/cjs/shared/auth-utils.js b/dist/cjs/shared/auth-utils.js deleted file mode 100644 index f2fe617344..0000000000 --- a/dist/cjs/shared/auth-utils.js +++ /dev/null @@ -1,48 +0,0 @@ -"use strict"; -/** - * Utilities for handling OAuth resource URIs. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.resourceUrlFromServerUrl = resourceUrlFromServerUrl; -exports.checkResourceAllowed = checkResourceAllowed; -/** - * Converts a server URL to a resource URL by removing the fragment. - * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". - * Keeps everything else unchanged (scheme, domain, port, path, query). - */ -function resourceUrlFromServerUrl(url) { - const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href); - resourceURL.hash = ''; // Remove fragment - return resourceURL; -} -/** - * Checks if a requested resource URL matches a configured resource URL. - * A requested resource matches if it has the same scheme, domain, port, - * and its path starts with the configured resource's path. - * - * @param requestedResource The resource URL being requested - * @param configuredResource The resource URL that has been configured - * @returns true if the requested resource matches the configured resource, false otherwise - */ -function checkResourceAllowed({ requestedResource, configuredResource }) { - const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href); - const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href); - // Compare the origin (scheme, domain, and port) - if (requested.origin !== configured.origin) { - return false; - } - // Handle cases like requested=/foo and configured=/foo/ - if (requested.pathname.length < configured.pathname.length) { - return false; - } - // Check if the requested path starts with the configured path - // Ensure both paths end with / for proper comparison - // This ensures that if we have paths like "/api" and "/api/users", - // we properly detect that "/api/users" is a subpath of "/api" - // By adding a trailing slash if missing, we avoid false positives - // where paths like "/api123" would incorrectly match "/api" - const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/'; - const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/'; - return requestedPath.startsWith(configuredPath); -} -//# sourceMappingURL=auth-utils.js.map \ No newline at end of file diff --git a/dist/cjs/shared/auth-utils.js.map b/dist/cjs/shared/auth-utils.js.map deleted file mode 100644 index 4a71b257bb..0000000000 --- a/dist/cjs/shared/auth-utils.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"auth-utils.js","sourceRoot":"","sources":["../../../src/shared/auth-utils.ts"],"names":[],"mappings":";AAAA;;GAEG;;AAOH,4DAIC;AAWD,oDA8BC;AAlDD;;;;GAIG;AACH,SAAgB,wBAAwB,CAAC,GAAiB;IACtD,MAAM,WAAW,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAC/E,WAAW,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,kBAAkB;IACzC,OAAO,WAAW,CAAC;AACvB,CAAC;AAED;;;;;;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 100644 index c9e723a002..0000000000 --- a/dist/cjs/shared/auth.d.ts +++ /dev/null @@ -1,240 +0,0 @@ -import * as z from 'zod/v4'; -/** - * Reusable URL validation that disallows javascript: scheme - */ -export declare const SafeUrlSchema: z.ZodURL; -/** - * RFC 9728 OAuth Protected Resource Metadata - */ -export declare const OAuthProtectedResourceMetadataSchema: z.ZodObject<{ - resource: z.ZodString; - authorization_servers: z.ZodOptional>; - jwks_uri: z.ZodOptional; - scopes_supported: z.ZodOptional>; - bearer_methods_supported: z.ZodOptional>; - resource_signing_alg_values_supported: z.ZodOptional>; - resource_name: z.ZodOptional; - resource_documentation: z.ZodOptional; - resource_policy_uri: z.ZodOptional; - resource_tos_uri: z.ZodOptional; - tls_client_certificate_bound_access_tokens: z.ZodOptional; - authorization_details_types_supported: z.ZodOptional>; - dpop_signing_alg_values_supported: z.ZodOptional>; - dpop_bound_access_tokens_required: z.ZodOptional; -}, z.core.$loose>; -/** - * RFC 8414 OAuth 2.0 Authorization Server Metadata - */ -export declare const OAuthMetadataSchema: z.ZodObject<{ - issuer: z.ZodString; - authorization_endpoint: z.ZodURL; - token_endpoint: z.ZodURL; - registration_endpoint: z.ZodOptional; - scopes_supported: z.ZodOptional>; - response_types_supported: z.ZodArray; - response_modes_supported: z.ZodOptional>; - grant_types_supported: z.ZodOptional>; - token_endpoint_auth_methods_supported: z.ZodOptional>; - token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; - service_documentation: z.ZodOptional; - revocation_endpoint: z.ZodOptional; - revocation_endpoint_auth_methods_supported: z.ZodOptional>; - revocation_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; - introspection_endpoint: z.ZodOptional; - introspection_endpoint_auth_methods_supported: z.ZodOptional>; - introspection_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; - code_challenge_methods_supported: z.ZodOptional>; - client_id_metadata_document_supported: z.ZodOptional; -}, z.core.$loose>; -/** - * OpenID Connect Discovery 1.0 Provider Metadata - * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata - */ -export declare const OpenIdProviderMetadataSchema: z.ZodObject<{ - issuer: z.ZodString; - authorization_endpoint: z.ZodURL; - token_endpoint: z.ZodURL; - userinfo_endpoint: z.ZodOptional; - jwks_uri: z.ZodURL; - registration_endpoint: z.ZodOptional; - scopes_supported: z.ZodOptional>; - response_types_supported: z.ZodArray; - response_modes_supported: z.ZodOptional>; - grant_types_supported: z.ZodOptional>; - acr_values_supported: z.ZodOptional>; - subject_types_supported: z.ZodArray; - id_token_signing_alg_values_supported: z.ZodArray; - id_token_encryption_alg_values_supported: z.ZodOptional>; - id_token_encryption_enc_values_supported: z.ZodOptional>; - userinfo_signing_alg_values_supported: z.ZodOptional>; - userinfo_encryption_alg_values_supported: z.ZodOptional>; - userinfo_encryption_enc_values_supported: z.ZodOptional>; - request_object_signing_alg_values_supported: z.ZodOptional>; - request_object_encryption_alg_values_supported: z.ZodOptional>; - request_object_encryption_enc_values_supported: z.ZodOptional>; - token_endpoint_auth_methods_supported: z.ZodOptional>; - token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; - display_values_supported: z.ZodOptional>; - claim_types_supported: z.ZodOptional>; - claims_supported: z.ZodOptional>; - service_documentation: z.ZodOptional; - claims_locales_supported: z.ZodOptional>; - ui_locales_supported: z.ZodOptional>; - claims_parameter_supported: z.ZodOptional; - request_parameter_supported: z.ZodOptional; - request_uri_parameter_supported: z.ZodOptional; - require_request_uri_registration: z.ZodOptional; - op_policy_uri: z.ZodOptional; - op_tos_uri: z.ZodOptional; - client_id_metadata_document_supported: z.ZodOptional; -}, z.core.$loose>; -/** - * OpenID Connect Discovery metadata that may include OAuth 2.0 fields - * This schema represents the real-world scenario where OIDC providers - * return a mix of OpenID Connect and OAuth 2.0 metadata fields - */ -export declare const OpenIdProviderDiscoveryMetadataSchema: z.ZodObject<{ - code_challenge_methods_supported: z.ZodOptional>; - issuer: z.ZodString; - authorization_endpoint: z.ZodURL; - token_endpoint: z.ZodURL; - userinfo_endpoint: z.ZodOptional; - jwks_uri: z.ZodURL; - registration_endpoint: z.ZodOptional; - scopes_supported: z.ZodOptional>; - response_types_supported: z.ZodArray; - response_modes_supported: z.ZodOptional>; - grant_types_supported: z.ZodOptional>; - acr_values_supported: z.ZodOptional>; - subject_types_supported: z.ZodArray; - id_token_signing_alg_values_supported: z.ZodArray; - id_token_encryption_alg_values_supported: z.ZodOptional>; - id_token_encryption_enc_values_supported: z.ZodOptional>; - userinfo_signing_alg_values_supported: z.ZodOptional>; - userinfo_encryption_alg_values_supported: z.ZodOptional>; - userinfo_encryption_enc_values_supported: z.ZodOptional>; - request_object_signing_alg_values_supported: z.ZodOptional>; - request_object_encryption_alg_values_supported: z.ZodOptional>; - request_object_encryption_enc_values_supported: z.ZodOptional>; - token_endpoint_auth_methods_supported: z.ZodOptional>; - token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; - display_values_supported: z.ZodOptional>; - claim_types_supported: z.ZodOptional>; - claims_supported: z.ZodOptional>; - service_documentation: z.ZodOptional; - claims_locales_supported: z.ZodOptional>; - ui_locales_supported: z.ZodOptional>; - claims_parameter_supported: z.ZodOptional; - request_parameter_supported: z.ZodOptional; - request_uri_parameter_supported: z.ZodOptional; - require_request_uri_registration: z.ZodOptional; - op_policy_uri: z.ZodOptional; - op_tos_uri: z.ZodOptional; - client_id_metadata_document_supported: z.ZodOptional; -}, z.core.$strip>; -/** - * OAuth 2.1 token response - */ -export declare const OAuthTokensSchema: z.ZodObject<{ - access_token: z.ZodString; - id_token: z.ZodOptional; - token_type: z.ZodString; - expires_in: z.ZodOptional; - scope: z.ZodOptional; - refresh_token: z.ZodOptional; -}, z.core.$strip>; -/** - * OAuth 2.1 error response - */ -export declare const OAuthErrorResponseSchema: z.ZodObject<{ - error: z.ZodString; - error_description: z.ZodOptional; - error_uri: z.ZodOptional; -}, z.core.$strip>; -/** - * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri - */ -export declare const OptionalSafeUrlSchema: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata - */ -export declare const OAuthClientMetadataSchema: z.ZodObject<{ - redirect_uris: z.ZodArray; - token_endpoint_auth_method: z.ZodOptional; - grant_types: z.ZodOptional>; - response_types: z.ZodOptional>; - client_name: z.ZodOptional; - client_uri: z.ZodOptional; - logo_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; - scope: z.ZodOptional; - contacts: z.ZodOptional>; - tos_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; - policy_uri: z.ZodOptional; - jwks_uri: z.ZodOptional; - jwks: z.ZodOptional; - software_id: z.ZodOptional; - software_version: z.ZodOptional; - software_statement: z.ZodOptional; -}, z.core.$strip>; -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration client information - */ -export declare const OAuthClientInformationSchema: z.ZodObject<{ - client_id: z.ZodString; - client_secret: z.ZodOptional; - client_id_issued_at: z.ZodOptional; - client_secret_expires_at: z.ZodOptional; -}, z.core.$strip>; -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) - */ -export declare const OAuthClientInformationFullSchema: z.ZodObject<{ - redirect_uris: z.ZodArray; - token_endpoint_auth_method: z.ZodOptional; - grant_types: z.ZodOptional>; - response_types: z.ZodOptional>; - client_name: z.ZodOptional; - client_uri: z.ZodOptional; - logo_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; - scope: z.ZodOptional; - contacts: z.ZodOptional>; - tos_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; - policy_uri: z.ZodOptional; - jwks_uri: z.ZodOptional; - jwks: z.ZodOptional; - software_id: z.ZodOptional; - software_version: z.ZodOptional; - software_statement: z.ZodOptional; - client_id: z.ZodString; - client_secret: z.ZodOptional; - client_id_issued_at: z.ZodOptional; - client_secret_expires_at: z.ZodOptional; -}, z.core.$strip>; -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration error response - */ -export declare const OAuthClientRegistrationErrorSchema: z.ZodObject<{ - error: z.ZodString; - error_description: z.ZodOptional; -}, z.core.$strip>; -/** - * RFC 7009 OAuth 2.0 Token Revocation request - */ -export declare const OAuthTokenRevocationRequestSchema: z.ZodObject<{ - token: z.ZodString; - token_type_hint: z.ZodOptional; -}, z.core.$strip>; -export type OAuthMetadata = z.infer; -export type OpenIdProviderMetadata = z.infer; -export type OpenIdProviderDiscoveryMetadata = z.infer; -export type OAuthTokens = z.infer; -export type OAuthErrorResponse = z.infer; -export type OAuthClientMetadata = z.infer; -export type OAuthClientInformation = z.infer; -export type OAuthClientInformationFull = z.infer; -export type OAuthClientInformationMixed = OAuthClientInformation | OAuthClientInformationFull; -export type OAuthClientRegistrationError = z.infer; -export type OAuthTokenRevocationRequest = z.infer; -export type OAuthProtectedResourceMetadata = z.infer; -export type AuthorizationServerMetadata = OAuthMetadata | OpenIdProviderDiscoveryMetadata; -//# sourceMappingURL=auth.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/auth.d.ts.map b/dist/cjs/shared/auth.d.ts.map deleted file mode 100644 index 031a88fb92..0000000000 --- a/dist/cjs/shared/auth.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/shared/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B;;GAEG;AACH,eAAO,MAAM,aAAa,UAmBrB,CAAC;AAEN;;GAEG;AACH,eAAO,MAAM,oCAAoC;;;;;;;;;;;;;;;iBAe/C,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;iBAoB9B,CAAC;AAEH;;;GAGG;AACH,eAAO,MAAM,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAqCvC,CAAC;AAEH;;;;GAIG;AACH,e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AC1F,MAAM,MAAM,2BAA2B,GAAG,sBAAsB,GAAG,0BAA0B,CAAC;AAC9F,MAAM,MAAM,4BAA4B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kCAAkC,CAAC,CAAC;AAC9F,MAAM,MAAM,2BAA2B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iCAAiC,CAAC,CAAC;AAC5F,MAAM,MAAM,8BAA8B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oCAAoC,CAAC,CAAC;AAGlG,MAAM,MAAM,2BAA2B,GAAG,aAAa,GAAG,+BAA+B,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/auth.js b/dist/cjs/shared/auth.js deleted file mode 100644 index a3bcf877bd..0000000000 --- a/dist/cjs/shared/auth.js +++ /dev/null @@ -1,224 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OAuthTokenRevocationRequestSchema = exports.OAuthClientRegistrationErrorSchema = exports.OAuthClientInformationFullSchema = exports.OAuthClientInformationSchema = exports.OAuthClientMetadataSchema = exports.OptionalSafeUrlSchema = exports.OAuthErrorResponseSchema = exports.OAuthTokensSchema = exports.OpenIdProviderDiscoveryMetadataSchema = exports.OpenIdProviderMetadataSchema = exports.OAuthMetadataSchema = exports.OAuthProtectedResourceMetadataSchema = exports.SafeUrlSchema = void 0; -const z = __importStar(require("zod/v4")); -/** - * Reusable URL validation that disallows javascript: scheme - */ -exports.SafeUrlSchema = z - .url() - .superRefine((val, ctx) => { - if (!URL.canParse(val)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'URL must be parseable', - fatal: true - }); - return z.NEVER; - } -}) - .refine(url => { - const u = new URL(url); - return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:'; -}, { message: 'URL cannot use javascript:, data:, or vbscript: scheme' }); -/** - * RFC 9728 OAuth Protected Resource Metadata - */ -exports.OAuthProtectedResourceMetadataSchema = z.looseObject({ - resource: z.string().url(), - authorization_servers: z.array(exports.SafeUrlSchema).optional(), - jwks_uri: z.string().url().optional(), - scopes_supported: z.array(z.string()).optional(), - bearer_methods_supported: z.array(z.string()).optional(), - resource_signing_alg_values_supported: z.array(z.string()).optional(), - resource_name: z.string().optional(), - resource_documentation: z.string().optional(), - resource_policy_uri: z.string().url().optional(), - resource_tos_uri: z.string().url().optional(), - tls_client_certificate_bound_access_tokens: z.boolean().optional(), - authorization_details_types_supported: z.array(z.string()).optional(), - dpop_signing_alg_values_supported: z.array(z.string()).optional(), - dpop_bound_access_tokens_required: z.boolean().optional() -}); -/** - * RFC 8414 OAuth 2.0 Authorization Server Metadata - */ -exports.OAuthMetadataSchema = z.looseObject({ - issuer: z.string(), - authorization_endpoint: exports.SafeUrlSchema, - token_endpoint: exports.SafeUrlSchema, - registration_endpoint: exports.SafeUrlSchema.optional(), - scopes_supported: z.array(z.string()).optional(), - response_types_supported: z.array(z.string()), - response_modes_supported: z.array(z.string()).optional(), - grant_types_supported: z.array(z.string()).optional(), - token_endpoint_auth_methods_supported: z.array(z.string()).optional(), - token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - service_documentation: exports.SafeUrlSchema.optional(), - revocation_endpoint: exports.SafeUrlSchema.optional(), - revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(), - revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - introspection_endpoint: z.string().optional(), - introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(), - introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - code_challenge_methods_supported: z.array(z.string()).optional(), - client_id_metadata_document_supported: z.boolean().optional() -}); -/** - * OpenID Connect Discovery 1.0 Provider Metadata - * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata - */ -exports.OpenIdProviderMetadataSchema = z.looseObject({ - issuer: z.string(), - authorization_endpoint: exports.SafeUrlSchema, - token_endpoint: exports.SafeUrlSchema, - userinfo_endpoint: exports.SafeUrlSchema.optional(), - jwks_uri: exports.SafeUrlSchema, - registration_endpoint: exports.SafeUrlSchema.optional(), - scopes_supported: z.array(z.string()).optional(), - response_types_supported: z.array(z.string()), - response_modes_supported: z.array(z.string()).optional(), - grant_types_supported: z.array(z.string()).optional(), - acr_values_supported: z.array(z.string()).optional(), - subject_types_supported: z.array(z.string()), - id_token_signing_alg_values_supported: z.array(z.string()), - id_token_encryption_alg_values_supported: z.array(z.string()).optional(), - id_token_encryption_enc_values_supported: z.array(z.string()).optional(), - userinfo_signing_alg_values_supported: z.array(z.string()).optional(), - userinfo_encryption_alg_values_supported: z.array(z.string()).optional(), - userinfo_encryption_enc_values_supported: z.array(z.string()).optional(), - request_object_signing_alg_values_supported: z.array(z.string()).optional(), - request_object_encryption_alg_values_supported: z.array(z.string()).optional(), - request_object_encryption_enc_values_supported: z.array(z.string()).optional(), - token_endpoint_auth_methods_supported: z.array(z.string()).optional(), - token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - display_values_supported: z.array(z.string()).optional(), - claim_types_supported: z.array(z.string()).optional(), - claims_supported: z.array(z.string()).optional(), - service_documentation: z.string().optional(), - claims_locales_supported: z.array(z.string()).optional(), - ui_locales_supported: z.array(z.string()).optional(), - claims_parameter_supported: z.boolean().optional(), - request_parameter_supported: z.boolean().optional(), - request_uri_parameter_supported: z.boolean().optional(), - require_request_uri_registration: z.boolean().optional(), - op_policy_uri: exports.SafeUrlSchema.optional(), - op_tos_uri: exports.SafeUrlSchema.optional(), - client_id_metadata_document_supported: z.boolean().optional() -}); -/** - * OpenID Connect Discovery metadata that may include OAuth 2.0 fields - * This schema represents the real-world scenario where OIDC providers - * return a mix of OpenID Connect and OAuth 2.0 metadata fields - */ -exports.OpenIdProviderDiscoveryMetadataSchema = z.object({ - ...exports.OpenIdProviderMetadataSchema.shape, - ...exports.OAuthMetadataSchema.pick({ - code_challenge_methods_supported: true - }).shape -}); -/** - * OAuth 2.1 token response - */ -exports.OAuthTokensSchema = z - .object({ - access_token: z.string(), - id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect - token_type: z.string(), - expires_in: z.number().optional(), - scope: z.string().optional(), - refresh_token: z.string().optional() -}) - .strip(); -/** - * OAuth 2.1 error response - */ -exports.OAuthErrorResponseSchema = z.object({ - error: z.string(), - error_description: z.string().optional(), - error_uri: z.string().optional() -}); -/** - * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri - */ -exports.OptionalSafeUrlSchema = exports.SafeUrlSchema.optional().or(z.literal('').transform(() => undefined)); -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata - */ -exports.OAuthClientMetadataSchema = z - .object({ - redirect_uris: z.array(exports.SafeUrlSchema), - token_endpoint_auth_method: z.string().optional(), - grant_types: z.array(z.string()).optional(), - response_types: z.array(z.string()).optional(), - client_name: z.string().optional(), - client_uri: exports.SafeUrlSchema.optional(), - logo_uri: exports.OptionalSafeUrlSchema, - scope: z.string().optional(), - contacts: z.array(z.string()).optional(), - tos_uri: exports.OptionalSafeUrlSchema, - policy_uri: z.string().optional(), - jwks_uri: exports.SafeUrlSchema.optional(), - jwks: z.any().optional(), - software_id: z.string().optional(), - software_version: z.string().optional(), - software_statement: z.string().optional() -}) - .strip(); -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration client information - */ -exports.OAuthClientInformationSchema = z - .object({ - client_id: z.string(), - client_secret: z.string().optional(), - client_id_issued_at: z.number().optional(), - client_secret_expires_at: z.number().optional() -}) - .strip(); -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) - */ -exports.OAuthClientInformationFullSchema = exports.OAuthClientMetadataSchema.merge(exports.OAuthClientInformationSchema); -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration error response - */ -exports.OAuthClientRegistrationErrorSchema = z - .object({ - error: z.string(), - error_description: z.string().optional() -}) - .strip(); -/** - * RFC 7009 OAuth 2.0 Token Revocation request - */ -exports.OAuthTokenRevocationRequestSchema = z - .object({ - token: z.string(), - token_type_hint: z.string().optional() -}) - .strip(); -//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/dist/cjs/shared/auth.js.map b/dist/cjs/shared/auth.js.map deleted file mode 100644 index fda5b3ed9d..0000000000 --- a/dist/cjs/shared/auth.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/shared/auth.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,0CAA4B;AAE5B;;GAEG;AACU,QAAA,aAAa,GAAG,CAAC;KACzB,GAAG,EAAE;KACL,WAAW,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;IACtB,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACrB,GAAG,CAAC,QAAQ,CAAC;YACT,IAAI,EAAE,CAAC,CAAC,YAAY,CAAC,MAAM;YAC3B,OAAO,EAAE,uBAAuB;YAChC,KAAK,EAAE,IAAI;SACd,CAAC,CAAC;QAEH,OAAO,CAAC,CAAC,KAAK,CAAC;IACnB,CAAC;AACL,CAAC,CAAC;KACD,MA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AC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACzC,CAAC;KACD,KAAK,EAAE,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/metadataUtils.d.ts b/dist/cjs/shared/metadataUtils.d.ts deleted file mode 100644 index c0e738bab0..0000000000 --- a/dist/cjs/shared/metadataUtils.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { BaseMetadata } from '../types.js'; -/** - * Utilities for working with BaseMetadata objects. - */ -/** - * Gets the display name for an object with BaseMetadata. - * For tools, the precedence is: title → annotations.title → name - * For other objects: title → name - * This implements the spec requirement: "if no title is provided, name should be used for display purposes" - */ -export declare function getDisplayName(metadata: BaseMetadata & { - annotations?: { - title?: string; - }; -}): string; -//# sourceMappingURL=metadataUtils.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/metadataUtils.d.ts.map b/dist/cjs/shared/metadataUtils.d.ts.map deleted file mode 100644 index 596805eb34..0000000000 --- a/dist/cjs/shared/metadataUtils.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"metadataUtils.d.ts","sourceRoot":"","sources":["../../../src/shared/metadataUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C;;GAEG;AAEH;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,YAAY,GAAG;IAAE,WAAW,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,GAAG,MAAM,CAapG"} \ No newline at end of file diff --git a/dist/cjs/shared/metadataUtils.js b/dist/cjs/shared/metadataUtils.js deleted file mode 100644 index 07e8ec4c4e..0000000000 --- a/dist/cjs/shared/metadataUtils.js +++ /dev/null @@ -1,26 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getDisplayName = getDisplayName; -/** - * Utilities for working with BaseMetadata objects. - */ -/** - * Gets the display name for an object with BaseMetadata. - * For tools, the precedence is: title → annotations.title → name - * For other objects: title → name - * This implements the spec requirement: "if no title is provided, name should be used for display purposes" - */ -function getDisplayName(metadata) { - var _a; - // First check for title (not undefined and not empty string) - if (metadata.title !== undefined && metadata.title !== '') { - return metadata.title; - } - // Then check for annotations.title (only present in Tool objects) - if ((_a = metadata.annotations) === null || _a === void 0 ? void 0 : _a.title) { - return metadata.annotations.title; - } - // Finally fall back to name - return metadata.name; -} -//# sourceMappingURL=metadataUtils.js.map \ No newline at end of file diff --git a/dist/cjs/shared/metadataUtils.js.map b/dist/cjs/shared/metadataUtils.js.map deleted file mode 100644 index e9e9cc69e1..0000000000 --- a/dist/cjs/shared/metadataUtils.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"metadataUtils.js","sourceRoot":"","sources":["../../../src/shared/metadataUtils.ts"],"names":[],"mappings":";;AAYA,wCAaC;AAvBD;;GAEG;AAEH;;;;;GAKG;AACH,SAAgB,cAAc,CAAC,QAA6D;;IACxF,6DAA6D;IAC7D,IAAI,QAAQ,CAAC,KAAK,KAAK,SAAS,IAAI,QAAQ,CAAC,KAAK,KAAK,EAAE,EAAE,CAAC;QACxD,OAAO,QAAQ,CAAC,KAAK,CAAC;IAC1B,CAAC;IAED,kEAAkE;IAClE,IAAI,MAAA,QAAQ,CAAC,WAAW,0CAAE,KAAK,EAAE,CAAC;QAC9B,OAAO,QAAQ,CAAC,WAAW,CAAC,KAAK,CAAC;IACtC,CAAC;IAED,4BAA4B;IAC5B,OAAO,QAAQ,CAAC,IAAI,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/protocol.d.ts b/dist/cjs/shared/protocol.d.ts deleted file mode 100644 index fb23686184..0000000000 --- a/dist/cjs/shared/protocol.d.ts +++ /dev/null @@ -1,226 +0,0 @@ -import { AnySchema, AnyObjectSchema, SchemaOutput } from '../server/zod-compat.js'; -import { ClientCapabilities, JSONRPCRequest, Notification, Progress, Request, RequestId, Result, ServerCapabilities, RequestMeta, RequestInfo } from '../types.js'; -import { Transport, TransportSendOptions } from './transport.js'; -import { AuthInfo } from '../server/auth/types.js'; -/** - * Callback for progress notifications. - */ -export type ProgressCallback = (progress: Progress) => void; -/** - * Additional initialization options. - */ -export type ProtocolOptions = { - /** - * Whether to restrict emitted requests to only those that the remote side has indicated that they can handle, through their advertised capabilities. - * - * Note that this DOES NOT affect checking of _local_ side capabilities, as it is considered a logic error to mis-specify those. - * - * Currently this defaults to false, for backwards compatibility with SDK versions that did not advertise capabilities correctly. In future, this will default to true. - */ - enforceStrictCapabilities?: boolean; - /** - * An array of notification method names that should be automatically debounced. - * Any notifications with a method in this list will be coalesced if they - * occur in the same tick of the event loop. - * e.g., ['notifications/tools/list_changed'] - */ - debouncedNotificationMethods?: string[]; -}; -/** - * The default request timeout, in miliseconds. - */ -export declare const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; -/** - * Options that can be given per request. - */ -export type RequestOptions = { - /** - * If set, requests progress notifications from the remote end (if supported). When progress notifications are received, this callback will be invoked. - */ - onprogress?: ProgressCallback; - /** - * Can be used to cancel an in-flight request. This will cause an AbortError to be raised from request(). - */ - signal?: AbortSignal; - /** - * A timeout (in milliseconds) for this request. If exceeded, an McpError with code `RequestTimeout` will be raised from request(). - * - * If not specified, `DEFAULT_REQUEST_TIMEOUT_MSEC` will be used as the timeout. - */ - timeout?: number; - /** - * If true, receiving a progress notification will reset the request timeout. - * This is useful for long-running operations that send periodic progress updates. - * Default: false - */ - resetTimeoutOnProgress?: boolean; - /** - * Maximum total time (in milliseconds) to wait for a response. - * If exceeded, an McpError with code `RequestTimeout` will be raised, regardless of progress notifications. - * If not specified, there is no maximum total timeout. - */ - maxTotalTimeout?: number; -} & TransportSendOptions; -/** - * Options that can be given per notification. - */ -export type NotificationOptions = { - /** - * May be used to indicate to the transport which incoming request to associate this outgoing notification with. - */ - relatedRequestId?: RequestId; -}; -/** - * Extra data given to request handlers. - */ -export type RequestHandlerExtra = { - /** - * An abort signal used to communicate if the request was cancelled from the sender's side. - */ - signal: AbortSignal; - /** - * Information about a validated access token, provided to request handlers. - */ - authInfo?: AuthInfo; - /** - * The session ID from the transport, if available. - */ - sessionId?: string; - /** - * Metadata from the original request. - */ - _meta?: RequestMeta; - /** - * The JSON-RPC ID of the request being handled. - * This can be useful for tracking or logging purposes. - */ - requestId: RequestId; - /** - * The original HTTP request. - */ - requestInfo?: RequestInfo; - /** - * Sends a notification that relates to the current request being handled. - * - * This is used by certain transports to correctly associate related messages. - */ - sendNotification: (notification: SendNotificationT) => Promise; - /** - * Sends a request that relates to the current request being handled. - * - * This is used by certain transports to correctly associate related messages. - */ - sendRequest: (request: SendRequestT, resultSchema: U, options?: RequestOptions) => Promise>; -}; -/** - * Implements MCP protocol framing on top of a pluggable transport, including - * features like request/response linking, notifications, and progress. - */ -export declare abstract class Protocol { - private _options?; - private _transport?; - private _requestMessageId; - private _requestHandlers; - private _requestHandlerAbortControllers; - private _notificationHandlers; - private _responseHandlers; - private _progressHandlers; - private _timeoutInfo; - private _pendingDebouncedNotifications; - /** - * Callback for when the connection is closed for any reason. - * - * This is invoked when close() is called as well. - */ - onclose?: () => void; - /** - * Callback for when an error occurs. - * - * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. - */ - onerror?: (error: Error) => void; - /** - * A handler to invoke for any request types that do not have their own handler installed. - */ - fallbackRequestHandler?: (request: JSONRPCRequest, extra: RequestHandlerExtra) => Promise; - /** - * A handler to invoke for any notification types that do not have their own handler installed. - */ - fallbackNotificationHandler?: (notification: Notification) => Promise; - constructor(_options?: ProtocolOptions | undefined); - private _setupTimeout; - private _resetTimeout; - private _cleanupTimeout; - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. - */ - connect(transport: Transport): Promise; - private _onclose; - private _onerror; - private _onnotification; - private _onrequest; - private _onprogress; - private _onresponse; - get transport(): Transport | undefined; - /** - * Closes the connection. - */ - close(): Promise; - /** - * A method to check if a capability is supported by the remote side, for the given method to be called. - * - * This should be implemented by subclasses. - */ - protected abstract assertCapabilityForMethod(method: SendRequestT['method']): void; - /** - * A method to check if a notification is supported by the local side, for the given method to be sent. - * - * This should be implemented by subclasses. - */ - protected abstract assertNotificationCapability(method: SendNotificationT['method']): void; - /** - * A method to check if a request handler is supported by the local side, for the given method to be handled. - * - * This should be implemented by subclasses. - */ - protected abstract assertRequestHandlerCapability(method: string): void; - /** - * Sends a request and wait for a response. - * - * Do not use this method to emit notifications! Use notification() instead. - */ - request(request: SendRequestT, resultSchema: T, options?: RequestOptions): Promise>; - /** - * Emits a notification, which is a one-way message that does not expect a response. - */ - notification(notification: SendNotificationT, options?: NotificationOptions): Promise; - /** - * Registers a handler to invoke when this protocol object receives a request with the given method. - * - * Note that this will replace any previous request handler for the same method. - */ - setRequestHandler(requestSchema: T, handler: (request: SchemaOutput, extra: RequestHandlerExtra) => SendResultT | Promise): void; - /** - * Removes the request handler for the given method. - */ - removeRequestHandler(method: string): void; - /** - * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. - */ - assertCanSetRequestHandler(method: string): void; - /** - * Registers a handler to invoke when this protocol object receives a notification with the given method. - * - * Note that this will replace any previous notification handler for the same method. - */ - setNotificationHandler(notificationSchema: T, handler: (notification: SchemaOutput) => void | Promise): void; - /** - * Removes the notification handler for the given method. - */ - removeNotificationHandler(method: string): void; -} -export declare function mergeCapabilities(base: ServerCapabilities, additional: Partial): ServerCapabilities; -export declare function mergeCapabilities(base: ClientCapabilities, additional: Partial): ClientCapabilities; -//# sourceMappingURL=protocol.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/protocol.d.ts.map b/dist/cjs/shared/protocol.d.ts.map deleted file mode 100644 index 4aa2bd57cb..0000000000 --- a/dist/cjs/shared/protocol.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../../../src/shared/protocol.ts"],"names":[],"mappings":"AAA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G;;;;OAIG;IACH,iBAAiB,CAAC,CAAC,SAAS,eAAe,EACvC,aAAa,EAAE,CAAC,EAChB,OAAO,EAAE,CACL,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,EACxB,KAAK,EAAE,mBAAmB,CAAC,YAAY,EAAE,iBAAiB,CAAC,KAC1D,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,GACxC,IAAI;IAUP;;OAEG;IACH,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAI1C;;OAEG;IACH,0BAA0B,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAMhD;;;;OAIG;IACH,sBAAsB,CAAC,CAAC,SAAS,eAAe,EAC5C,kBAAkB,EAAE,CAAC,EACrB,OAAO,EAAE,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GACjE,IAAI;IAQP;;OAEG;IACH,yBAAyB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;CAGlD;AAMD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,kBAAkB,CAAC;AACzH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,kBAAkB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/protocol.js b/dist/cjs/shared/protocol.js deleted file mode 100644 index c684b8bd72..0000000000 --- a/dist/cjs/shared/protocol.js +++ /dev/null @@ -1,442 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Protocol = exports.DEFAULT_REQUEST_TIMEOUT_MSEC = void 0; -exports.mergeCapabilities = mergeCapabilities; -const zod_compat_js_1 = require("../server/zod-compat.js"); -const types_js_1 = require("../types.js"); -const zod_json_schema_compat_js_1 = require("../server/zod-json-schema-compat.js"); -/** - * The default request timeout, in miliseconds. - */ -exports.DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; -/** - * Implements MCP protocol framing on top of a pluggable transport, including - * features like request/response linking, notifications, and progress. - */ -class Protocol { - constructor(_options) { - this._options = _options; - this._requestMessageId = 0; - this._requestHandlers = new Map(); - this._requestHandlerAbortControllers = new Map(); - this._notificationHandlers = new Map(); - this._responseHandlers = new Map(); - this._progressHandlers = new Map(); - this._timeoutInfo = new Map(); - this._pendingDebouncedNotifications = new Set(); - this.setNotificationHandler(types_js_1.CancelledNotificationSchema, notification => { - const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); - controller === null || controller === void 0 ? void 0 : controller.abort(notification.params.reason); - }); - this.setNotificationHandler(types_js_1.ProgressNotificationSchema, notification => { - this._onprogress(notification); - }); - this.setRequestHandler(types_js_1.PingRequestSchema, - // Automatic pong by default. - _request => ({})); - } - _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { - this._timeoutInfo.set(messageId, { - timeoutId: setTimeout(onTimeout, timeout), - startTime: Date.now(), - timeout, - maxTotalTimeout, - resetTimeoutOnProgress, - onTimeout - }); - } - _resetTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (!info) - return false; - const totalElapsed = Date.now() - info.startTime; - if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { - this._timeoutInfo.delete(messageId); - throw types_js_1.McpError.fromError(types_js_1.ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', { - maxTotalTimeout: info.maxTotalTimeout, - totalElapsed - }); - } - clearTimeout(info.timeoutId); - info.timeoutId = setTimeout(info.onTimeout, info.timeout); - return true; - } - _cleanupTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (info) { - clearTimeout(info.timeoutId); - this._timeoutInfo.delete(messageId); - } - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. - */ - async connect(transport) { - var _a, _b, _c; - this._transport = transport; - const _onclose = (_a = this.transport) === null || _a === void 0 ? void 0 : _a.onclose; - this._transport.onclose = () => { - _onclose === null || _onclose === void 0 ? void 0 : _onclose(); - this._onclose(); - }; - const _onerror = (_b = this.transport) === null || _b === void 0 ? void 0 : _b.onerror; - this._transport.onerror = (error) => { - _onerror === null || _onerror === void 0 ? void 0 : _onerror(error); - this._onerror(error); - }; - const _onmessage = (_c = this._transport) === null || _c === void 0 ? void 0 : _c.onmessage; - this._transport.onmessage = (message, extra) => { - _onmessage === null || _onmessage === void 0 ? void 0 : _onmessage(message, extra); - if ((0, types_js_1.isJSONRPCResponse)(message) || (0, types_js_1.isJSONRPCError)(message)) { - this._onresponse(message); - } - else if ((0, types_js_1.isJSONRPCRequest)(message)) { - this._onrequest(message, extra); - } - else if ((0, types_js_1.isJSONRPCNotification)(message)) { - this._onnotification(message); - } - else { - this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); - } - }; - await this._transport.start(); - } - _onclose() { - var _a; - const responseHandlers = this._responseHandlers; - this._responseHandlers = new Map(); - this._progressHandlers.clear(); - this._pendingDebouncedNotifications.clear(); - this._transport = undefined; - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - const error = types_js_1.McpError.fromError(types_js_1.ErrorCode.ConnectionClosed, 'Connection closed'); - for (const handler of responseHandlers.values()) { - handler(error); - } - } - _onerror(error) { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - } - _onnotification(notification) { - var _a; - const handler = (_a = this._notificationHandlers.get(notification.method)) !== null && _a !== void 0 ? _a : this.fallbackNotificationHandler; - // Ignore notifications not being subscribed to. - if (handler === undefined) { - return; - } - // Starting with Promise.resolve() puts any synchronous errors into the monad as well. - Promise.resolve() - .then(() => handler(notification)) - .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`))); - } - _onrequest(request, extra) { - var _a, _b; - const handler = (_a = this._requestHandlers.get(request.method)) !== null && _a !== void 0 ? _a : this.fallbackRequestHandler; - // Capture the current transport at request time to ensure responses go to the correct client - const capturedTransport = this._transport; - if (handler === undefined) { - capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({ - jsonrpc: '2.0', - id: request.id, - error: { - code: types_js_1.ErrorCode.MethodNotFound, - message: 'Method not found' - } - }).catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`))); - return; - } - const abortController = new AbortController(); - this._requestHandlerAbortControllers.set(request.id, abortController); - const fullExtra = { - signal: abortController.signal, - sessionId: capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId, - _meta: (_b = request.params) === null || _b === void 0 ? void 0 : _b._meta, - sendNotification: notification => this.notification(notification, { relatedRequestId: request.id }), - sendRequest: (r, resultSchema, options) => this.request(r, resultSchema, { ...options, relatedRequestId: request.id }), - authInfo: extra === null || extra === void 0 ? void 0 : extra.authInfo, - requestId: request.id, - requestInfo: extra === null || extra === void 0 ? void 0 : extra.requestInfo - }; - // Starting with Promise.resolve() puts any synchronous errors into the monad as well. - Promise.resolve() - .then(() => handler(request, fullExtra)) - .then(result => { - if (abortController.signal.aborted) { - return; - } - return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({ - result, - jsonrpc: '2.0', - id: request.id - }); - }, error => { - var _a; - if (abortController.signal.aborted) { - return; - } - return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({ - jsonrpc: '2.0', - id: request.id, - error: { - code: Number.isSafeInteger(error['code']) ? error['code'] : types_js_1.ErrorCode.InternalError, - message: (_a = error.message) !== null && _a !== void 0 ? _a : 'Internal error', - ...(error['data'] !== undefined && { data: error['data'] }) - } - }); - }) - .catch(error => this._onerror(new Error(`Failed to send response: ${error}`))) - .finally(() => { - this._requestHandlerAbortControllers.delete(request.id); - }); - } - _onprogress(notification) { - const { progressToken, ...params } = notification.params; - const messageId = Number(progressToken); - const handler = this._progressHandlers.get(messageId); - if (!handler) { - this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); - return; - } - const responseHandler = this._responseHandlers.get(messageId); - const timeoutInfo = this._timeoutInfo.get(messageId); - if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { - try { - this._resetTimeout(messageId); - } - catch (error) { - responseHandler(error); - return; - } - } - handler(params); - } - _onresponse(response) { - const messageId = Number(response.id); - const handler = this._responseHandlers.get(messageId); - if (handler === undefined) { - this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); - return; - } - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - if ((0, types_js_1.isJSONRPCResponse)(response)) { - handler(response); - } - else { - const error = types_js_1.McpError.fromError(response.error.code, response.error.message, response.error.data); - handler(error); - } - } - get transport() { - return this._transport; - } - /** - * Closes the connection. - */ - async close() { - var _a; - await ((_a = this._transport) === null || _a === void 0 ? void 0 : _a.close()); - } - /** - * Sends a request and wait for a response. - * - * Do not use this method to emit notifications! Use notification() instead. - */ - request(request, resultSchema, options) { - const { relatedRequestId, resumptionToken, onresumptiontoken } = options !== null && options !== void 0 ? options : {}; - return new Promise((resolve, reject) => { - var _a, _b, _c, _d, _e, _f; - if (!this._transport) { - reject(new Error('Not connected')); - return; - } - if (((_a = this._options) === null || _a === void 0 ? void 0 : _a.enforceStrictCapabilities) === true) { - this.assertCapabilityForMethod(request.method); - } - (_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.throwIfAborted(); - const messageId = this._requestMessageId++; - const jsonrpcRequest = { - ...request, - jsonrpc: '2.0', - id: messageId - }; - if (options === null || options === void 0 ? void 0 : options.onprogress) { - this._progressHandlers.set(messageId, options.onprogress); - jsonrpcRequest.params = { - ...request.params, - _meta: { - ...(((_c = request.params) === null || _c === void 0 ? void 0 : _c._meta) || {}), - progressToken: messageId - } - }; - } - const cancel = (reason) => { - var _a; - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - (_a = this._transport) === null || _a === void 0 ? void 0 : _a.send({ - jsonrpc: '2.0', - method: 'notifications/cancelled', - params: { - requestId: messageId, - reason: String(reason) - } - }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`))); - reject(reason); - }; - this._responseHandlers.set(messageId, response => { - var _a; - if ((_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.aborted) { - return; - } - if (response instanceof Error) { - return reject(response); - } - try { - const parseResult = (0, zod_compat_js_1.safeParse)(resultSchema, response.result); - if (!parseResult.success) { - // Type guard: if success is false, error is guaranteed to exist - reject(parseResult.error); - } - else { - resolve(parseResult.data); - } - } - catch (error) { - reject(error); - } - }); - (_d = options === null || options === void 0 ? void 0 : options.signal) === null || _d === void 0 ? void 0 : _d.addEventListener('abort', () => { - var _a; - cancel((_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.reason); - }); - const timeout = (_e = options === null || options === void 0 ? void 0 : options.timeout) !== null && _e !== void 0 ? _e : exports.DEFAULT_REQUEST_TIMEOUT_MSEC; - const timeoutHandler = () => cancel(types_js_1.McpError.fromError(types_js_1.ErrorCode.RequestTimeout, 'Request timed out', { timeout })); - this._setupTimeout(messageId, timeout, options === null || options === void 0 ? void 0 : options.maxTotalTimeout, timeoutHandler, (_f = options === null || options === void 0 ? void 0 : options.resetTimeoutOnProgress) !== null && _f !== void 0 ? _f : false); - this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => { - this._cleanupTimeout(messageId); - reject(error); - }); - }); - } - /** - * Emits a notification, which is a one-way message that does not expect a response. - */ - async notification(notification, options) { - var _a, _b; - if (!this._transport) { - throw new Error('Not connected'); - } - this.assertNotificationCapability(notification.method); - const debouncedMethods = (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.debouncedNotificationMethods) !== null && _b !== void 0 ? _b : []; - // A notification can only be debounced if it's in the list AND it's "simple" - // (i.e., has no parameters and no related request ID that could be lost). - const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !(options === null || options === void 0 ? void 0 : options.relatedRequestId); - if (canDebounce) { - // If a notification of this type is already scheduled, do nothing. - if (this._pendingDebouncedNotifications.has(notification.method)) { - return; - } - // Mark this notification type as pending. - this._pendingDebouncedNotifications.add(notification.method); - // Schedule the actual send to happen in the next microtask. - // This allows all synchronous calls in the current event loop tick to be coalesced. - Promise.resolve().then(() => { - var _a; - // Un-mark the notification so the next one can be scheduled. - this._pendingDebouncedNotifications.delete(notification.method); - // SAFETY CHECK: If the connection was closed while this was pending, abort. - if (!this._transport) { - return; - } - const jsonrpcNotification = { - ...notification, - jsonrpc: '2.0' - }; - // Send the notification, but don't await it here to avoid blocking. - // Handle potential errors with a .catch(). - (_a = this._transport) === null || _a === void 0 ? void 0 : _a.send(jsonrpcNotification, options).catch(error => this._onerror(error)); - }); - // Return immediately. - return; - } - const jsonrpcNotification = { - ...notification, - jsonrpc: '2.0' - }; - await this._transport.send(jsonrpcNotification, options); - } - /** - * Registers a handler to invoke when this protocol object receives a request with the given method. - * - * Note that this will replace any previous request handler for the same method. - */ - setRequestHandler(requestSchema, handler) { - const method = (0, zod_json_schema_compat_js_1.getMethodLiteral)(requestSchema); - this.assertRequestHandlerCapability(method); - this._requestHandlers.set(method, (request, extra) => { - const parsed = (0, zod_json_schema_compat_js_1.parseWithCompat)(requestSchema, request); - return Promise.resolve(handler(parsed, extra)); - }); - } - /** - * Removes the request handler for the given method. - */ - removeRequestHandler(method) { - this._requestHandlers.delete(method); - } - /** - * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. - */ - assertCanSetRequestHandler(method) { - if (this._requestHandlers.has(method)) { - throw new Error(`A request handler for ${method} already exists, which would be overridden`); - } - } - /** - * Registers a handler to invoke when this protocol object receives a notification with the given method. - * - * Note that this will replace any previous notification handler for the same method. - */ - setNotificationHandler(notificationSchema, handler) { - const method = (0, zod_json_schema_compat_js_1.getMethodLiteral)(notificationSchema); - this._notificationHandlers.set(method, notification => { - const parsed = (0, zod_json_schema_compat_js_1.parseWithCompat)(notificationSchema, notification); - return Promise.resolve(handler(parsed)); - }); - } - /** - * Removes the notification handler for the given method. - */ - removeNotificationHandler(method) { - this._notificationHandlers.delete(method); - } -} -exports.Protocol = Protocol; -function isPlainObject(value) { - return value !== null && typeof value === 'object' && !Array.isArray(value); -} -function mergeCapabilities(base, additional) { - const result = { ...base }; - for (const key in additional) { - const k = key; - const addValue = additional[k]; - if (addValue === undefined) - continue; - const baseValue = result[k]; - if (isPlainObject(baseValue) && isPlainObject(addValue)) { - result[k] = { ...baseValue, ...addValue }; - } - else { - result[k] = addValue; - } - } - return result; -} -//# sourceMappingURL=protocol.js.map \ No newline at end of file diff --git a/dist/cjs/shared/protocol.js.map b/dist/cjs/shared/protocol.js.map deleted file mode 100644 index 3ebb4c7ca0..0000000000 --- a/dist/cjs/shared/protocol.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../../src/shared/protocol.ts"],"names":[],"mappings":";;;AAqsBA,8CAcC;AAntBD,2DAA8F;AAC9F,0CAyBqB;AAGrB,mFAAwF;AA4BxF;;GAEG;AACU,QAAA,4BAA4B,GAAG,KAAK,CAAC;AA8GlD;;;GAGG;AACH,MAAsB,QAAQ;IAsC1B,YAAoB,QAA0B;QAA1B,aAAQ,GAAR,QAAQ,CAAkB;QApCtC,sBAAiB,GAAG,CAAC,CAAC;QACtB,qBAAgB,GAGpB,IAAI,GAAG,EAAE,CAAC;QACN,oCAA+B,GAAoC,IAAI,GAAG,EAAE,CAAC;QAC7E,0BAAqB,GAAsE,IAAI,GAAG,EAAE,CAAC;QACrG,sBAAiB,GAA6D,IAAI,GAAG,EAAE,CAAC;QACxF,sBAAiB,GAAkC,IAAI,GAAG,EAAE,CAAC;QAC7D,iBAAY,GAA6B,IAAI,GAAG,EAAE,CAAC;QACnD,mCAA8B,GAAG,IAAI,GAAG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I,aAAa,CAAC,SAAS,CAAC,IAAI,aAAa,CAAC,QAAQ,CAAC,EAAE,CAAC;YACtD,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,GAAI,SAAqC,EAAE,GAAI,QAAoC,EAAiB,CAAC;QACvH,CAAC;aAAM,CAAC;YACJ,MAAM,CAAC,CAAC,CAAC,GAAG,QAAuB,CAAC;QACxC,CAAC;IACL,CAAC;IACD,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/stdio.d.ts b/dist/cjs/shared/stdio.d.ts deleted file mode 100644 index 0830a48bc7..0000000000 --- a/dist/cjs/shared/stdio.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { JSONRPCMessage } from '../types.js'; -/** - * Buffers a continuous stdio stream into discrete JSON-RPC messages. - */ -export declare class ReadBuffer { - private _buffer?; - append(chunk: Buffer): void; - readMessage(): JSONRPCMessage | null; - clear(): void; -} -export declare function deserializeMessage(line: string): JSONRPCMessage; -export declare function serializeMessage(message: JSONRPCMessage): string; -//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/stdio.d.ts.map b/dist/cjs/shared/stdio.d.ts.map deleted file mode 100644 index 8f97f2ab10..0000000000 --- a/dist/cjs/shared/stdio.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/shared/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AAEnE;;GAEG;AACH,qBAAa,UAAU;IACnB,OAAO,CAAC,OAAO,CAAC,CAAS;IAEzB,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAI3B,WAAW,IAAI,cAAc,GAAG,IAAI;IAepC,KAAK,IAAI,IAAI;CAGhB;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,CAE/D;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,GAAG,MAAM,CAEhE"} \ No newline at end of file diff --git a/dist/cjs/shared/stdio.js b/dist/cjs/shared/stdio.js deleted file mode 100644 index 540ee56827..0000000000 --- a/dist/cjs/shared/stdio.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ReadBuffer = void 0; -exports.deserializeMessage = deserializeMessage; -exports.serializeMessage = serializeMessage; -const types_js_1 = require("../types.js"); -/** - * Buffers a continuous stdio stream into discrete JSON-RPC messages. - */ -class ReadBuffer { - append(chunk) { - this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; - } - readMessage() { - if (!this._buffer) { - return null; - } - const index = this._buffer.indexOf('\n'); - if (index === -1) { - return null; - } - const line = this._buffer.toString('utf8', 0, index).replace(/\r$/, ''); - this._buffer = this._buffer.subarray(index + 1); - return deserializeMessage(line); - } - clear() { - this._buffer = undefined; - } -} -exports.ReadBuffer = ReadBuffer; -function deserializeMessage(line) { - return types_js_1.JSONRPCMessageSchema.parse(JSON.parse(line)); -} -function serializeMessage(message) { - return JSON.stringify(message) + '\n'; -} -//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/dist/cjs/shared/stdio.js.map b/dist/cjs/shared/stdio.js.map deleted file mode 100644 index 89fbc1a66c..0000000000 --- a/dist/cjs/shared/stdio.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/shared/stdio.ts"],"names":[],"mappings":";;;AAgCA,gDAEC;AAED,4CAEC;AAtCD,0CAAmE;AAEnE;;GAEG;AACH,MAAa,UAAU;IAGnB,MAAM,CAAC,KAAa;QAChB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAC/E,CAAC;IAED,WAAW;QACP,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAChB,OAAO,IAAI,CAAC;QAChB,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACzC,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE,CAAC;YACf,OAAO,IAAI,CAAC;QAChB,CAAC;QAED,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACxE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QAChD,OAAO,kBAAkB,CAAC,IAAI,CAAC,CAAC;IACpC,CAAC;IAED,KAAK;QACD,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;IAC7B,CAAC;CACJ;AAzBD,gCAyBC;AAED,SAAgB,kBAAkB,CAAC,IAAY;IAC3C,OAAO,+BAAoB,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;AACxD,CAAC;AAED,SAAgB,gBAAgB,CAAC,OAAuB;IACpD,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;AAC1C,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/toolNameValidation.d.ts b/dist/cjs/shared/toolNameValidation.d.ts deleted file mode 100644 index 3cf94bf78e..0000000000 --- a/dist/cjs/shared/toolNameValidation.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Tool name validation utilities according to SEP: Specify Format for Tool Names - * - * Tool names SHOULD be between 1 and 128 characters in length (inclusive). - * Tool names are case-sensitive. - * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits - * (0-9), underscore (_), dash (-), and dot (.). - * Tool names SHOULD NOT contain spaces, commas, or other special characters. - */ -/** - * Validates a tool name according to the SEP specification - * @param name - The tool name to validate - * @returns An object containing validation result and any warnings - */ -export declare function validateToolName(name: string): { - isValid: boolean; - warnings: string[]; -}; -/** - * Issues warnings for non-conforming tool names - * @param name - The tool name that triggered the warnings - * @param warnings - Array of warning messages - */ -export declare function issueToolNameWarning(name: string, warnings: string[]): void; -/** - * Validates a tool name and issues warnings for non-conforming names - * @param name - The tool name to validate - * @returns true if the name is valid, false otherwise - */ -export declare function validateAndWarnToolName(name: string): boolean; -//# sourceMappingURL=toolNameValidation.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/toolNameValidation.d.ts.map b/dist/cjs/shared/toolNameValidation.d.ts.map deleted file mode 100644 index d81f0156e6..0000000000 --- a/dist/cjs/shared/toolNameValidation.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"toolNameValidation.d.ts","sourceRoot":"","sources":["../../../src/shared/toolNameValidation.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAOH;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG;IAC5C,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,MAAM,EAAE,CAAC;CACtB,CA0DA;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,CAY3E;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAO7D"} \ No newline at end of file diff --git a/dist/cjs/shared/toolNameValidation.js b/dist/cjs/shared/toolNameValidation.js deleted file mode 100644 index cd9d930788..0000000000 --- a/dist/cjs/shared/toolNameValidation.js +++ /dev/null @@ -1,97 +0,0 @@ -"use strict"; -/** - * Tool name validation utilities according to SEP: Specify Format for Tool Names - * - * Tool names SHOULD be between 1 and 128 characters in length (inclusive). - * Tool names are case-sensitive. - * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits - * (0-9), underscore (_), dash (-), and dot (.). - * Tool names SHOULD NOT contain spaces, commas, or other special characters. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.validateToolName = validateToolName; -exports.issueToolNameWarning = issueToolNameWarning; -exports.validateAndWarnToolName = validateAndWarnToolName; -/** - * Regular expression for valid tool names according to SEP-986 specification - */ -const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; -/** - * Validates a tool name according to the SEP specification - * @param name - The tool name to validate - * @returns An object containing validation result and any warnings - */ -function validateToolName(name) { - const warnings = []; - // Check length - if (name.length === 0) { - return { - isValid: false, - warnings: ['Tool name cannot be empty'] - }; - } - if (name.length > 128) { - return { - isValid: false, - warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] - }; - } - // Check for specific problematic patterns (these are warnings, not validation failures) - if (name.includes(' ')) { - warnings.push('Tool name contains spaces, which may cause parsing issues'); - } - if (name.includes(',')) { - warnings.push('Tool name contains commas, which may cause parsing issues'); - } - // Check for potentially confusing patterns (leading/trailing dashes, dots, slashes) - if (name.startsWith('-') || name.endsWith('-')) { - warnings.push('Tool name starts or ends with a dash, which may cause parsing issues in some contexts'); - } - if (name.startsWith('.') || name.endsWith('.')) { - warnings.push('Tool name starts or ends with a dot, which may cause parsing issues in some contexts'); - } - // Check for invalid characters - if (!TOOL_NAME_REGEX.test(name)) { - const invalidChars = name - .split('') - .filter(char => !/[A-Za-z0-9._-]/.test(char)) - .filter((char, index, arr) => arr.indexOf(char) === index); // Remove duplicates - warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c => `"${c}"`).join(', ')}`, 'Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)'); - return { - isValid: false, - warnings - }; - } - return { - isValid: true, - warnings - }; -} -/** - * Issues warnings for non-conforming tool names - * @param name - The tool name that triggered the warnings - * @param warnings - Array of warning messages - */ -function issueToolNameWarning(name, warnings) { - if (warnings.length > 0) { - console.warn(`Tool name validation warning for "${name}":`); - for (const warning of warnings) { - console.warn(` - ${warning}`); - } - console.warn('Tool registration will proceed, but this may cause compatibility issues.'); - console.warn('Consider updating the tool name to conform to the MCP tool naming standard.'); - console.warn('See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.'); - } -} -/** - * Validates a tool name and issues warnings for non-conforming names - * @param name - The tool name to validate - * @returns true if the name is valid, false otherwise - */ -function validateAndWarnToolName(name) { - const result = validateToolName(name); - // Always issue warnings for any validation issues (both invalid names and warnings) - issueToolNameWarning(name, result.warnings); - return result.isValid; -} -//# sourceMappingURL=toolNameValidation.js.map \ No newline at end of file diff --git a/dist/cjs/shared/toolNameValidation.js.map b/dist/cjs/shared/toolNameValidation.js.map deleted file mode 100644 index ad136cc304..0000000000 --- a/dist/cjs/shared/toolNameValidation.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"toolNameValidation.js","sourceRoot":"","sources":["../../../src/shared/toolNameValidation.ts"],"names":[],"mappings":";AAAA;;;;;;;;GAQG;;AAYH,4CA6DC;AAOD,oDAYC;AAOD,0DAOC;AAxGD;;GAEG;AACH,MAAM,eAAe,GAAG,yBAAyB,CAAC;AAElD;;;;GAIG;AACH,SAAgB,gBAAgB,CAAC,IAAY;IAIzC,MAAM,QAAQ,GAAa,EAAE,CAAC;IAE9B,eAAe;IACf,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACpB,OAAO;YACH,OAAO,EAAE,KAAK;YACd,QAAQ,EAAE,CAAC,2BAA2B,CAAC;SAC1C,CAAC;IACN,CAAC;IAED,IAAI,IAAI,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC;QACpB,OAAO;YACH,OAAO,EAAE,KAAK;YACd,QAAQ,EAAE,CAAC,gEAAgE,IAAI,CAAC,MAAM,GAAG,CAAC;SAC7F,CAAC;IACN,CAAC;IAED,wFAAwF;IACxF,IAAI,IAAI,CAAC,QAAQ,CAAC,GA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;KACX,CAAC;AACN,CAAC;AAED;;;;GAIG;AACH,SAAgB,oBAAoB,CAAC,IAAY,EAAE,QAAkB;IACjE,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACtB,OAAO,CAAC,IAAI,CAAC,qCAAqC,IAAI,IAAI,CAAC,CAAC;QAC5D,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;YAC7B,OAAO,CAAC,IAAI,CAAC,OAAO,OAAO,EAAE,CAAC,CAAC;QACnC,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,0EAA0E,CAAC,CAAC;QACzF,OAAO,CAAC,IAAI,CAAC,6EAA6E,CAAC,CAAC;QAC5F,OAAO,CAAC,IAAI,CACR,oIAAoI,CACvI,CAAC;IACN,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,SAAgB,uBAAuB,CAAC,IAAY;IAChD,MAAM,MAAM,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAEtC,oFAAoF;IACpF,oBAAoB,CAAC,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;IAE5C,OAAO,MAAM,CAAC,OAAO,CAAC;AAC1B,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/transport.d.ts b/dist/cjs/shared/transport.d.ts deleted file mode 100644 index 7fb5efab77..0000000000 --- a/dist/cjs/shared/transport.d.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types.js'; -export type FetchLike = (url: string | URL, init?: RequestInit) => Promise; -/** - * Normalizes HeadersInit to a plain Record for manipulation. - * Handles Headers objects, arrays of tuples, and plain objects. - */ -export declare function normalizeHeaders(headers: HeadersInit | undefined): Record; -/** - * Creates a fetch function that includes base RequestInit options. - * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. - * - * @param baseFetch - The base fetch function to wrap (defaults to global fetch) - * @param baseInit - The base RequestInit to merge with each request - * @returns A wrapped fetch function that merges base options with call-specific options - */ -export declare function createFetchWithInit(baseFetch?: FetchLike, baseInit?: RequestInit): FetchLike; -/** - * Options for sending a JSON-RPC message. - */ -export type TransportSendOptions = { - /** - * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with. - */ - relatedRequestId?: RequestId; - /** - * The resumption token used to continue long-running requests that were interrupted. - * - * This allows clients to reconnect and continue from where they left off, if supported by the transport. - */ - resumptionToken?: string; - /** - * A callback that is invoked when the resumption token changes, if supported by the transport. - * - * This allows clients to persist the latest token for potential reconnection. - */ - onresumptiontoken?: (token: string) => void; -}; -/** - * Describes the minimal contract for a MCP transport that a client or server can communicate over. - */ -export interface Transport { - /** - * Starts processing messages on the transport, including any connection steps that might need to be taken. - * - * This method should only be called after callbacks are installed, or else messages may be lost. - * - * NOTE: This method should not be called explicitly when using Client, Server, or Protocol classes, as they will implicitly call start(). - */ - start(): Promise; - /** - * Sends a JSON-RPC message (request or response). - * - * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with. - */ - send(message: JSONRPCMessage, options?: TransportSendOptions): Promise; - /** - * Closes the connection. - */ - close(): Promise; - /** - * Callback for when the connection is closed for any reason. - * - * This should be invoked when close() is called as well. - */ - onclose?: () => void; - /** - * Callback for when an error occurs. - * - * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. - */ - onerror?: (error: Error) => void; - /** - * Callback for when a message (request or response) is received over the connection. - * - * Includes the requestInfo and authInfo if the transport is authenticated. - * - * The requestInfo can be used to get the original request information (headers, etc.) - */ - onmessage?: (message: T, extra?: MessageExtraInfo) => void; - /** - * The session ID generated for this connection. - */ - sessionId?: string; - /** - * Sets the protocol version used for the connection (called when the initialize response is received). - */ - setProtocolVersion?: (version: string) => void; -} -//# sourceMappingURL=transport.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/transport.d.ts.map b/dist/cjs/shared/transport.d.ts.map deleted file mode 100644 index 7a3d837df8..0000000000 --- a/dist/cjs/shared/transport.d.ts.map +++ /dev/null @@ -1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CAAC,CAAC,SAAS,cAAc,EAAE,OAAO,EAAE,CAAC,EAAE,KAAK,CAAC,EAAE,gBAAgB,KAAK,IAAI,CAAC;IAErF;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,kBAAkB,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;CAClD"} \ No newline at end of file diff --git a/dist/cjs/shared/transport.js b/dist/cjs/shared/transport.js deleted file mode 100644 index 9618d067c8..0000000000 --- a/dist/cjs/shared/transport.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.normalizeHeaders = normalizeHeaders; -exports.createFetchWithInit = createFetchWithInit; -/** - * Normalizes HeadersInit to a plain Record for manipulation. - * Handles Headers objects, arrays of tuples, and plain objects. - */ -function normalizeHeaders(headers) { - if (!headers) - return {}; - if (headers instanceof Headers) { - return Object.fromEntries(headers.entries()); - } - if (Array.isArray(headers)) { - return Object.fromEntries(headers); - } - return { ...headers }; -} -/** - * Creates a fetch function that includes base RequestInit options. - * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. - * - * @param baseFetch - The base fetch function to wrap (defaults to global fetch) - * @param baseInit - The base RequestInit to merge with each request - * @returns A wrapped fetch function that merges base options with call-specific options - */ -function createFetchWithInit(baseFetch = fetch, baseInit) { - if (!baseInit) { - return baseFetch; - } - // Return a wrapped fetch that merges base RequestInit with call-specific init - return async (url, init) => { - const mergedInit = { - ...baseInit, - ...init, - // Headers need special handling - merge instead of replace - headers: (init === null || init === void 0 ? void 0 : init.headers) ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers - }; - return baseFetch(url, mergedInit); - }; -} -//# sourceMappingURL=transport.js.map \ No newline at end of file diff --git a/dist/cjs/shared/transport.js.map b/dist/cjs/shared/transport.js.map deleted file mode 100644 index 3c8cb5f837..0000000000 --- a/dist/cjs/shared/transport.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../src/shared/transport.ts"],"names":[],"mappings":";;AAQA,4CAYC;AAUD,kDAeC;AAzCD;;;GAGG;AACH,SAAgB,gBAAgB,CAAC,OAAgC;IAC7D,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,CAAC;IAExB,IAAI,OAAO,YAAY,OAAO,EAAE,CAAC;QAC7B,OAAO,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IACjD,CAAC;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACzB,OAAO,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,EAAE,GAAI,OAAkC,EAAE,CAAC;AACtD,CAAC;AAED;;;;;;;GAOG;AACH,SAAgB,mBAAmB,CAAC,YAAuB,KAAK,EAAE,QAAsB;IACpF,IAAI,CAAC,QAAQ,EAAE,CAAC;QACZ,OAAO,SAAS,CAAC;IACrB,CAAC;IAED,8EAA8E;IAC9E,OAAO,KAAK,EAAE,GAAiB,EAAE,IAAkB,EAAqB,EAAE;QACtE,MAAM,UAAU,GAAgB;YAC5B,GAAG,QAAQ;YACX,GAAG,IAAI;YACP,2DAA2D;YAC3D,OAAO,EAAE,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,EAAC,CAAC,CAAC,EAAE,GAAG,gBAAgB,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,GAAG,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO;SAC3H,CAAC;QACF,OAAO,SAAS,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC;IACtC,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/uriTemplate.d.ts b/dist/cjs/shared/uriTemplate.d.ts deleted file mode 100644 index 175e329b66..0000000000 --- a/dist/cjs/shared/uriTemplate.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -export type Variables = Record; -export declare class UriTemplate { - /** - * Returns true if the given string contains any URI template expressions. - * A template expression is a sequence of characters enclosed in curly braces, - * like {foo} or {?bar}. - */ - static isTemplate(str: string): boolean; - private static validateLength; - private readonly template; - private readonly parts; - get variableNames(): string[]; - constructor(template: string); - toString(): string; - private parse; - private getOperator; - private getNames; - private encodeValue; - private expandPart; - expand(variables: Variables): string; - private escapeRegExp; - private partToRegExp; - match(uri: string): Variables | null; -} -//# sourceMappingURL=uriTemplate.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/uriTemplate.d.ts.map b/dist/cjs/shared/uriTemplate.d.ts.map deleted file mode 100644 index 052e91851e..0000000000 --- a/dist/cjs/shared/uriTemplate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"uriTemplate.d.ts","sourceRoot":"","sources":["../../../src/shared/uriTemplate.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC;AAO1D,qBAAa,WAAW;IACpB;;;;OAIG;IACH,MAAM,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAMvC,OAAO,CAAC,MAAM,CAAC,cAAc;IAK7B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAyF;IAE/G,IAAI,aAAa,IAAI,MAAM,EAAE,CAE5B;gBAEW,QAAQ,EAAE,MAAM;IAM5B,QAAQ,IAAI,MAAM;IAIlB,OAAO,CAAC,KAAK;IA8Cb,OAAO,CAAC,WAAW;IAKnB,OAAO,CAAC,QAAQ;IAShB,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,UAAU;IAsDlB,MAAM,CAAC,SAAS,EAAE,SAAS,GAAG,MAAM;IA4BpC,OAAO,CAAC,YAAY;IAIpB,OAAO,CAAC,YAAY;IAkDpB,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;CAuCvC"} \ No newline at end of file diff --git a/dist/cjs/shared/uriTemplate.js b/dist/cjs/shared/uriTemplate.js deleted file mode 100644 index baad5d9746..0000000000 --- a/dist/cjs/shared/uriTemplate.js +++ /dev/null @@ -1,243 +0,0 @@ -"use strict"; -// Claude-authored implementation of RFC 6570 URI Templates -Object.defineProperty(exports, "__esModule", { value: true }); -exports.UriTemplate = void 0; -const MAX_TEMPLATE_LENGTH = 1000000; // 1MB -const MAX_VARIABLE_LENGTH = 1000000; // 1MB -const MAX_TEMPLATE_EXPRESSIONS = 10000; -const MAX_REGEX_LENGTH = 1000000; // 1MB -class UriTemplate { - /** - * Returns true if the given string contains any URI template expressions. - * A template expression is a sequence of characters enclosed in curly braces, - * like {foo} or {?bar}. - */ - static isTemplate(str) { - // Look for any sequence of characters between curly braces - // that isn't just whitespace - return /\{[^}\s]+\}/.test(str); - } - static validateLength(str, max, context) { - if (str.length > max) { - throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); - } - } - get variableNames() { - return this.parts.flatMap(part => (typeof part === 'string' ? [] : part.names)); - } - constructor(template) { - UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, 'Template'); - this.template = template; - this.parts = this.parse(template); - } - toString() { - return this.template; - } - parse(template) { - const parts = []; - let currentText = ''; - let i = 0; - let expressionCount = 0; - while (i < template.length) { - if (template[i] === '{') { - if (currentText) { - parts.push(currentText); - currentText = ''; - } - const end = template.indexOf('}', i); - if (end === -1) - throw new Error('Unclosed template expression'); - expressionCount++; - if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) { - throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); - } - const expr = template.slice(i + 1, end); - const operator = this.getOperator(expr); - const exploded = expr.includes('*'); - const names = this.getNames(expr); - const name = names[0]; - // Validate variable name length - for (const name of names) { - UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name'); - } - parts.push({ name, operator, names, exploded }); - i = end + 1; - } - else { - currentText += template[i]; - i++; - } - } - if (currentText) { - parts.push(currentText); - } - return parts; - } - getOperator(expr) { - const operators = ['+', '#', '.', '/', '?', '&']; - return operators.find(op => expr.startsWith(op)) || ''; - } - getNames(expr) { - const operator = this.getOperator(expr); - return expr - .slice(operator.length) - .split(',') - .map(name => name.replace('*', '').trim()) - .filter(name => name.length > 0); - } - encodeValue(value, operator) { - UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, 'Variable value'); - if (operator === '+' || operator === '#') { - return encodeURI(value); - } - return encodeURIComponent(value); - } - expandPart(part, variables) { - if (part.operator === '?' || part.operator === '&') { - const pairs = part.names - .map(name => { - const value = variables[name]; - if (value === undefined) - return ''; - const encoded = Array.isArray(value) - ? value.map(v => this.encodeValue(v, part.operator)).join(',') - : this.encodeValue(value.toString(), part.operator); - return `${name}=${encoded}`; - }) - .filter(pair => pair.length > 0); - if (pairs.length === 0) - return ''; - const separator = part.operator === '?' ? '?' : '&'; - return separator + pairs.join('&'); - } - if (part.names.length > 1) { - const values = part.names.map(name => variables[name]).filter(v => v !== undefined); - if (values.length === 0) - return ''; - return values.map(v => (Array.isArray(v) ? v[0] : v)).join(','); - } - const value = variables[part.name]; - if (value === undefined) - return ''; - const values = Array.isArray(value) ? value : [value]; - const encoded = values.map(v => this.encodeValue(v, part.operator)); - switch (part.operator) { - case '': - return encoded.join(','); - case '+': - return encoded.join(','); - case '#': - return '#' + encoded.join(','); - case '.': - return '.' + encoded.join('.'); - case '/': - return '/' + encoded.join('/'); - default: - return encoded.join(','); - } - } - expand(variables) { - let result = ''; - let hasQueryParam = false; - for (const part of this.parts) { - if (typeof part === 'string') { - result += part; - continue; - } - const expanded = this.expandPart(part, variables); - if (!expanded) - continue; - // Convert ? to & if we already have a query parameter - if ((part.operator === '?' || part.operator === '&') && hasQueryParam) { - result += expanded.replace('?', '&'); - } - else { - result += expanded; - } - if (part.operator === '?' || part.operator === '&') { - hasQueryParam = true; - } - } - return result; - } - escapeRegExp(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - } - partToRegExp(part) { - const patterns = []; - // Validate variable name length for matching - for (const name of part.names) { - UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name'); - } - if (part.operator === '?' || part.operator === '&') { - for (let i = 0; i < part.names.length; i++) { - const name = part.names[i]; - const prefix = i === 0 ? '\\' + part.operator : '&'; - patterns.push({ - pattern: prefix + this.escapeRegExp(name) + '=([^&]+)', - name - }); - } - return patterns; - } - let pattern; - const name = part.name; - switch (part.operator) { - case '': - pattern = part.exploded ? '([^/]+(?:,[^/]+)*)' : '([^/,]+)'; - break; - case '+': - case '#': - pattern = '(.+)'; - break; - case '.': - pattern = '\\.([^/,]+)'; - break; - case '/': - pattern = '/' + (part.exploded ? '([^/]+(?:,[^/]+)*)' : '([^/,]+)'); - break; - default: - pattern = '([^/]+)'; - } - patterns.push({ pattern, name }); - return patterns; - } - match(uri) { - UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, 'URI'); - let pattern = '^'; - const names = []; - for (const part of this.parts) { - if (typeof part === 'string') { - pattern += this.escapeRegExp(part); - } - else { - const patterns = this.partToRegExp(part); - for (const { pattern: partPattern, name } of patterns) { - pattern += partPattern; - names.push({ name, exploded: part.exploded }); - } - } - } - pattern += '$'; - UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, 'Generated regex pattern'); - const regex = new RegExp(pattern); - const match = uri.match(regex); - if (!match) - return null; - const result = {}; - for (let i = 0; i < names.length; i++) { - const { name, exploded } = names[i]; - const value = match[i + 1]; - const cleanName = name.replace('*', ''); - if (exploded && value.includes(',')) { - result[cleanName] = value.split(','); - } - else { - result[cleanName] = value; - } - } - return result; - } -} -exports.UriTemplate = UriTemplate; -//# sourceMappingURL=uriTemplate.js.map \ No newline at end of file diff --git a/dist/cjs/shared/uriTemplate.js.map b/dist/cjs/shared/uriTemplate.js.map deleted file mode 100644 index 75c5c50e2a..0000000000 --- a/dist/cjs/shared/uriTemplate.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"uriTemplate.js","sourceRoot":"","sources":["../../../src/shared/uriTemplate.ts"],"names":[],"mappings":";AAAA,2DAA2D;;;AAI3D,MAAM,mBAAmB,GAAG,OAAO,CAAC,CAAC,MAAM;AAC3C,MAAM,mBAAmB,GAAG,OAAO,CAAC,CAAC,MAAM;AAC3C,MAAM,wBAAwB,GAAG,KAAK,CAAC;AACvC,MAAM,gBAAgB,GAAG,OAAO,CAAC,CAAC,MAAM;AAExC,MAAa,WAAW;IACpB;;;;OAIG;IACH,MAAM,CAAC,UAAU,CAAC,GAAW;QACzB,2DAA2D;QAC3D,6BAA6B;QAC7B,OAAO,aAAa,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACnC,CAAC;IAEO,MAAM,CAAC,cAAc,CAAC,GAAW,EAAE,GAAW,EAAE,OAAe;QACnE,IAAI,GAAG,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC;YACnB,MAAM,IAAI,KAAK,CAAC,GAAG,OAAO,8BAA8B,GAAG,oBAAoB,GAAG,CAAC,MAAM,GAAG,CAAC,CAAC;QAClG,CAAC;IACL,CAAC;IAID,IAAI,aAAa;QACb,OAAO,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;IACpF,CAAC;IAED,YAAY,QAAgB;QACxB,WAAW,CAAC,cAAc,CAAC,QAAQ,EAAE,mBAAmB,EAAE,UAAU,CAAC,CAAC;QACtE,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;IACtC,CAAC;IAED,QAAQ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,CAAC;QAC7B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACpC,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;YACpC,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;YAC3B,MAAM,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;YAExC,IAAI,QAAQ,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;gBAClC,MAAM,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YACzC,CAAC;iBAAM,CAAC;gBACJ,MAAM,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC;YAC9B,CAAC;QACL,CAAC;QAED,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ;AArRD,kCAqRC"} \ No newline at end of file diff --git a/dist/cjs/shared/zodTestMatrix.d.ts b/dist/cjs/shared/zodTestMatrix.d.ts deleted file mode 100644 index 7dafd4ce93..0000000000 --- a/dist/cjs/shared/zodTestMatrix.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import * as z3 from 'zod/v3'; -import * as z4 from 'zod/v4'; -export type ZNamespace = typeof z3 & typeof z4; -export declare const zodTestMatrix: readonly [{ - readonly zodVersionLabel: "Zod v3"; - readonly z: ZNamespace; - readonly isV3: true; - readonly isV4: false; -}, { - readonly zodVersionLabel: "Zod v4"; - readonly z: ZNamespace; - readonly isV3: false; - readonly isV4: true; -}]; -export type ZodMatrixEntry = (typeof zodTestMatrix)[number]; -//# sourceMappingURL=zodTestMatrix.d.ts.map \ No newline at end of file diff --git a/dist/cjs/shared/zodTestMatrix.d.ts.map b/dist/cjs/shared/zodTestMatrix.d.ts.map deleted file mode 100644 index 3842fb1c32..0000000000 --- a/dist/cjs/shared/zodTestMatrix.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"zodTestMatrix.d.ts","sourceRoot":"","sources":["../../../src/shared/zodTestMatrix.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC7B,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAG7B,MAAM,MAAM,UAAU,GAAG,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC;AAE/C,eAAO,MAAM,aAAa;;gBAGT,UAAU;;;;;gBAMV,UAAU;;;EAIjB,CAAC;AAEX,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,aAAa,CAAC,CAAC,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/shared/zodTestMatrix.js b/dist/cjs/shared/zodTestMatrix.js deleted file mode 100644 index 92627ab249..0000000000 --- a/dist/cjs/shared/zodTestMatrix.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.zodTestMatrix = void 0; -const z3 = __importStar(require("zod/v3")); -const z4 = __importStar(require("zod/v4")); -exports.zodTestMatrix = [ - { - zodVersionLabel: 'Zod v3', - z: z3, - isV3: true, - isV4: false - }, - { - zodVersionLabel: 'Zod v4', - z: z4, - isV3: false, - isV4: true - } -]; -//# sourceMappingURL=zodTestMatrix.js.map \ No newline at end of file diff --git a/dist/cjs/shared/zodTestMatrix.js.map b/dist/cjs/shared/zodTestMatrix.js.map deleted file mode 100644 index 55cc0b0ace..0000000000 --- a/dist/cjs/shared/zodTestMatrix.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"zodTestMatrix.js","sourceRoot":"","sources":["../../../src/shared/zodTestMatrix.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,2CAA6B;AAC7B,2CAA6B;AAKhB,QAAA,aAAa,GAAG;IACzB;QACI,eAAe,EAAE,QAAQ;QACzB,CAAC,EAAE,EAAgB;QACnB,IAAI,EAAE,IAAa;QACnB,IAAI,EAAE,KAAc;KACvB;IACD;QACI,eAAe,EAAE,QAAQ;QACzB,CAAC,EAAE,EAAgB;QACnB,IAAI,EAAE,KAAc;QACpB,IAAI,EAAE,IAAa;KACtB;CACK,CAAC"} \ No newline at end of file diff --git a/dist/cjs/spec.types.d.ts b/dist/cjs/spec.types.d.ts deleted file mode 100644 index bf6a90f80c..0000000000 --- a/dist/cjs/spec.types.d.ts +++ /dev/null @@ -1,2033 +0,0 @@ -/** - * This file is automatically generated from the Model Context Protocol specification. - * - * Source: https://github.com/modelcontextprotocol/modelcontextprotocol - * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts - * Last updated from commit: 4528444698f76e6d0337e58d2941d5d3485d779d - * - * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. - * To update this file, run: npm run fetch:spec-types - */ -/** - * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. - * - * @category JSON-RPC - */ -export type JSONRPCMessage = JSONRPCRequest | JSONRPCNotification | JSONRPCResponse | JSONRPCError; -/** @internal */ -export declare const LATEST_PROTOCOL_VERSION = "DRAFT-2025-v3"; -/** @internal */ -export declare const JSONRPC_VERSION = "2.0"; -/** - * A progress token, used to associate progress notifications with the original request. - * - * @category Common Types - */ -export type ProgressToken = string | number; -/** - * An opaque token used to represent a cursor for pagination. - * - * @category Common Types - */ -export type Cursor = string; -/** - * Common params for any request. - * - * @internal - */ -export interface RequestParams { - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - /** - * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. - */ - progressToken?: ProgressToken; - [key: string]: unknown; - }; -} -/** @internal */ -export interface Request { - method: string; - params?: { - [key: string]: any; - }; -} -/** @internal */ -export interface NotificationParams { - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** @internal */ -export interface Notification { - method: string; - params?: { - [key: string]: any; - }; -} -/** - * @category Common Types - */ -export interface Result { - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; - [key: string]: unknown; -} -/** - * @category Common Types - */ -export interface Error { - /** - * The error type that occurred. - */ - code: number; - /** - * A short description of the error. The message SHOULD be limited to a concise single sentence. - */ - message: string; - /** - * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). - */ - data?: unknown; -} -/** - * A uniquely identifying ID for a request in JSON-RPC. - * - * @category Common Types - */ -export type RequestId = string | number; -/** - * A request that expects a response. - * - * @category JSON-RPC - */ -export interface JSONRPCRequest extends Request { - jsonrpc: typeof JSONRPC_VERSION; - id: RequestId; -} -/** - * A notification which does not expect a response. - * - * @category JSON-RPC - */ -export interface JSONRPCNotification extends Notification { - jsonrpc: typeof JSONRPC_VERSION; -} -/** - * A successful (non-error) response to a request. - * - * @category JSON-RPC - */ -export interface JSONRPCResponse { - jsonrpc: typeof JSONRPC_VERSION; - id: RequestId; - result: Result; -} -export declare const PARSE_ERROR = -32700; -export declare const INVALID_REQUEST = -32600; -export declare const METHOD_NOT_FOUND = -32601; -export declare const INVALID_PARAMS = -32602; -export declare const INTERNAL_ERROR = -32603; -/** @internal */ -export declare const URL_ELICITATION_REQUIRED = -32042; -/** - * A response to a request that indicates an error occurred. - * - * @category JSON-RPC - */ -export interface JSONRPCError { - jsonrpc: typeof JSONRPC_VERSION; - id: RequestId; - error: Error; -} -/** - * An error response that indicates that the server requires the client to provide additional information via an elicitation request. - * - * @internal - */ -export interface URLElicitationRequiredError extends Omit { - error: Error & { - code: typeof URL_ELICITATION_REQUIRED; - data: { - elicitations: ElicitRequestURLParams[]; - [key: string]: unknown; - }; - }; -} -/** - * A response that indicates success but carries no data. - * - * @category Common Types - */ -export type EmptyResult = Result; -/** - * Parameters for a `notifications/cancelled` notification. - * - * @category `notifications/cancelled` - */ -export interface CancelledNotificationParams extends NotificationParams { - /** - * The ID of the request to cancel. - * - * This MUST correspond to the ID of a request previously issued in the same direction. - */ - requestId: RequestId; - /** - * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. - */ - reason?: string; -} -/** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its `initialize` request. - * - * @category `notifications/cancelled` - */ -export interface CancelledNotification extends JSONRPCNotification { - method: "notifications/cancelled"; - params: CancelledNotificationParams; -} -/** - * Parameters for an `initialize` request. - * - * @category `initialize` - */ -export interface InitializeRequestParams extends RequestParams { - /** - * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. - */ - protocolVersion: string; - capabilities: ClientCapabilities; - clientInfo: Implementation; -} -/** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - * - * @category `initialize` - */ -export interface InitializeRequest extends JSONRPCRequest { - method: "initialize"; - params: InitializeRequestParams; -} -/** - * After receiving an initialize request from the client, the server sends this response. - * - * @category `initialize` - */ -export interface InitializeResult extends Result { - /** - * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. - */ - protocolVersion: string; - capabilities: ServerCapabilities; - serverInfo: Implementation; - /** - * Instructions describing how to use the server and its features. - * - * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. - */ - instructions?: string; -} -/** - * This notification is sent from the client to the server after initialization has finished. - * - * @category `notifications/initialized` - */ -export interface InitializedNotification extends JSONRPCNotification { - method: "notifications/initialized"; - params?: NotificationParams; -} -/** - * 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. - * - * @category `initialize` - */ -export interface ClientCapabilities { - /** - * Experimental, non-standard capabilities that the client supports. - */ - experimental?: { - [key: string]: object; - }; - /** - * Present if the client supports listing roots. - */ - roots?: { - /** - * Whether the client supports notifications for changes to the roots list. - */ - listChanged?: boolean; - }; - /** - * Present if the client supports sampling from an LLM. - */ - sampling?: { - /** - * Whether the client supports context inclusion via includeContext parameter. - * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). - */ - context?: object; - /** - * Whether the client supports tool use via tools and toolChoice parameters. - */ - tools?: object; - }; - /** - * Present if the client supports elicitation from the server. - */ - elicitation?: { - form?: object; - url?: object; - }; -} -/** - * 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. - * - * @category `initialize` - */ -export interface ServerCapabilities { - /** - * Experimental, non-standard capabilities that the server supports. - */ - experimental?: { - [key: string]: object; - }; - /** - * Present if the server supports sending log messages to the client. - */ - logging?: object; - /** - * Present if the server supports argument autocompletion suggestions. - */ - completions?: object; - /** - * Present if the server offers any prompt templates. - */ - prompts?: { - /** - * Whether this server supports notifications for changes to the prompt list. - */ - listChanged?: boolean; - }; - /** - * Present if the server offers any resources to read. - */ - resources?: { - /** - * Whether this server supports subscribing to resource updates. - */ - subscribe?: boolean; - /** - * Whether this server supports notifications for changes to the resource list. - */ - listChanged?: boolean; - }; - /** - * Present if the server offers any tools to call. - */ - tools?: { - /** - * Whether this server supports notifications for changes to the tool list. - */ - listChanged?: boolean; - }; -} -/** - * An optionally-sized icon that can be displayed in a user interface. - * - * @category Common Types - */ -export interface Icon { - /** - * A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a - * `data:` URI with Base64-encoded image data. - * - * Consumers SHOULD takes steps to ensure URLs serving icons are from the - * same domain as the client/server or a trusted domain. - * - * Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain - * executable JavaScript. - * - * @format uri - */ - src: string; - /** - * Optional MIME type override if the source MIME type is missing or generic. - * For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`. - */ - mimeType?: string; - /** - * Optional array of strings that specify sizes at which the icon can be used. - * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. - * - * If not provided, the client should assume that the icon can be used at any size. - */ - sizes?: string[]; - /** - * Optional specifier for the theme this icon is designed for. `light` indicates - * the icon is designed to be used with a light background, and `dark` indicates - * the icon is designed to be used with a dark background. - * - * If not provided, the client should assume the icon can be used with any theme. - */ - theme?: "light" | "dark"; -} -/** - * Base interface to add `icons` property. - * - * @internal - */ -export interface Icons { - /** - * Optional set of sized icons that the client can display in a user interface. - * - * Clients that support rendering icons MUST support at least the following MIME types: - * - `image/png` - PNG images (safe, universal compatibility) - * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) - * - * Clients that support rendering icons SHOULD also support: - * - `image/svg+xml` - SVG images (scalable but requires security precautions) - * - `image/webp` - WebP images (modern, efficient format) - */ - icons?: Icon[]; -} -/** - * Base interface for metadata with name (identifier) and title (display name) properties. - * - * @internal - */ -export interface BaseMetadata { - /** - * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present). - */ - name: string; - /** - * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, - * even by those unfamiliar with domain-specific terminology. - * - * If not provided, the name should be used for display (except for Tool, - * where `annotations.title` should be given precedence over using `name`, - * if present). - */ - title?: string; -} -/** - * Describes the MCP implementation. - * - * @category `initialize` - */ -export interface Implementation extends BaseMetadata, Icons { - version: string; - /** - * An optional URL of the website for this implementation. - * - * @format uri - */ - websiteUrl?: string; -} -/** - * 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. - * - * @category `ping` - */ -export interface PingRequest extends JSONRPCRequest { - method: "ping"; - params?: RequestParams; -} -/** - * Parameters for a `notifications/progress` notification. - * - * @category `notifications/progress` - */ -export interface ProgressNotificationParams extends NotificationParams { - /** - * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. - */ - progressToken: ProgressToken; - /** - * The progress thus far. This should increase every time progress is made, even if the total is unknown. - * - * @TJS-type number - */ - progress: number; - /** - * Total number of items to process (or total progress required), if known. - * - * @TJS-type number - */ - total?: number; - /** - * An optional message describing the current progress. - */ - message?: string; -} -/** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - * - * @category `notifications/progress` - */ -export interface ProgressNotification extends JSONRPCNotification { - method: "notifications/progress"; - params: ProgressNotificationParams; -} -/** - * Common parameters for paginated requests. - * - * @internal - */ -export interface PaginatedRequestParams extends RequestParams { - /** - * An opaque token representing the current pagination position. - * If provided, the server should return results starting after this cursor. - */ - cursor?: Cursor; -} -/** @internal */ -export interface PaginatedRequest extends JSONRPCRequest { - params?: PaginatedRequestParams; -} -/** @internal */ -export interface PaginatedResult extends Result { - /** - * An opaque token representing the pagination position after the last returned result. - * If present, there may be more results available. - */ - nextCursor?: Cursor; -} -/** - * Sent from the client to request a list of resources the server has. - * - * @category `resources/list` - */ -export interface ListResourcesRequest extends PaginatedRequest { - method: "resources/list"; -} -/** - * The server's response to a resources/list request from the client. - * - * @category `resources/list` - */ -export interface ListResourcesResult extends PaginatedResult { - resources: Resource[]; -} -/** - * Sent from the client to request a list of resource templates the server has. - * - * @category `resources/templates/list` - */ -export interface ListResourceTemplatesRequest extends PaginatedRequest { - method: "resources/templates/list"; -} -/** - * The server's response to a resources/templates/list request from the client. - * - * @category `resources/templates/list` - */ -export interface ListResourceTemplatesResult extends PaginatedResult { - resourceTemplates: ResourceTemplate[]; -} -/** - * Common parameters when working with resources. - * - * @internal - */ -export interface ResourceRequestParams extends RequestParams { - /** - * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it. - * - * @format uri - */ - uri: string; -} -/** - * Parameters for a `resources/read` request. - * - * @category `resources/read` - */ -export interface ReadResourceRequestParams extends ResourceRequestParams { -} -/** - * Sent from the client to the server, to read a specific resource URI. - * - * @category `resources/read` - */ -export interface ReadResourceRequest extends JSONRPCRequest { - method: "resources/read"; - params: ReadResourceRequestParams; -} -/** - * The server's response to a resources/read request from the client. - * - * @category `resources/read` - */ -export interface ReadResourceResult extends Result { - contents: (TextResourceContents | BlobResourceContents)[]; -} -/** - * 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. - * - * @category `notifications/resources/list_changed` - */ -export interface ResourceListChangedNotification extends JSONRPCNotification { - method: "notifications/resources/list_changed"; - params?: NotificationParams; -} -/** - * Parameters for a `resources/subscribe` request. - * - * @category `resources/subscribe` - */ -export interface SubscribeRequestParams extends ResourceRequestParams { -} -/** - * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. - * - * @category `resources/subscribe` - */ -export interface SubscribeRequest extends JSONRPCRequest { - method: "resources/subscribe"; - params: SubscribeRequestParams; -} -/** - * Parameters for a `resources/unsubscribe` request. - * - * @category `resources/unsubscribe` - */ -export interface UnsubscribeRequestParams extends ResourceRequestParams { -} -/** - * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. - * - * @category `resources/unsubscribe` - */ -export interface UnsubscribeRequest extends JSONRPCRequest { - method: "resources/unsubscribe"; - params: UnsubscribeRequestParams; -} -/** - * Parameters for a `notifications/resources/updated` notification. - * - * @category `notifications/resources/updated` - */ -export interface ResourceUpdatedNotificationParams extends NotificationParams { - /** - * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. - * - * @format uri - */ - uri: string; -} -/** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. - * - * @category `notifications/resources/updated` - */ -export interface ResourceUpdatedNotification extends JSONRPCNotification { - method: "notifications/resources/updated"; - params: ResourceUpdatedNotificationParams; -} -/** - * A known resource that the server is capable of reading. - * - * @category `resources/list` - */ -export interface Resource extends BaseMetadata, Icons { - /** - * The URI of this resource. - * - * @format uri - */ - uri: string; - /** - * A description of what this resource represents. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description?: string; - /** - * The MIME type of this resource, if known. - */ - mimeType?: string; - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - /** - * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. - * - * This can be used by Hosts to display file sizes and estimate context window usage. - */ - size?: number; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * A template description for resources available on the server. - * - * @category `resources/templates/list` - */ -export interface ResourceTemplate extends BaseMetadata, Icons { - /** - * A URI template (according to RFC 6570) that can be used to construct resource URIs. - * - * @format uri-template - */ - uriTemplate: string; - /** - * A description of what this template is for. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description?: string; - /** - * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. - */ - mimeType?: string; - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * The contents of a specific resource or sub-resource. - * - * @internal - */ -export interface ResourceContents { - /** - * The URI of this resource. - * - * @format uri - */ - uri: string; - /** - * The MIME type of this resource, if known. - */ - mimeType?: string; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * @category Content - */ -export interface TextResourceContents extends ResourceContents { - /** - * The text of the item. This must only be set if the item can actually be represented as text (not binary data). - */ - text: string; -} -/** - * @category Content - */ -export interface BlobResourceContents extends ResourceContents { - /** - * A base64-encoded string representing the binary data of the item. - * - * @format byte - */ - blob: string; -} -/** - * Sent from the client to request a list of prompts and prompt templates the server has. - * - * @category `prompts/list` - */ -export interface ListPromptsRequest extends PaginatedRequest { - method: "prompts/list"; -} -/** - * The server's response to a prompts/list request from the client. - * - * @category `prompts/list` - */ -export interface ListPromptsResult extends PaginatedResult { - prompts: Prompt[]; -} -/** - * Parameters for a `prompts/get` request. - * - * @category `prompts/get` - */ -export interface GetPromptRequestParams extends RequestParams { - /** - * The name of the prompt or prompt template. - */ - name: string; - /** - * Arguments to use for templating the prompt. - */ - arguments?: { - [key: string]: string; - }; -} -/** - * Used by the client to get a prompt provided by the server. - * - * @category `prompts/get` - */ -export interface GetPromptRequest extends JSONRPCRequest { - method: "prompts/get"; - params: GetPromptRequestParams; -} -/** - * The server's response to a prompts/get request from the client. - * - * @category `prompts/get` - */ -export interface GetPromptResult extends Result { - /** - * An optional description for the prompt. - */ - description?: string; - messages: PromptMessage[]; -} -/** - * A prompt or prompt template that the server offers. - * - * @category `prompts/list` - */ -export interface Prompt extends BaseMetadata, Icons { - /** - * An optional description of what this prompt provides - */ - description?: string; - /** - * A list of arguments to use for templating the prompt. - */ - arguments?: PromptArgument[]; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * Describes an argument that a prompt can accept. - * - * @category `prompts/list` - */ -export interface PromptArgument extends BaseMetadata { - /** - * A human-readable description of the argument. - */ - description?: string; - /** - * Whether this argument must be provided. - */ - required?: boolean; -} -/** - * The sender or recipient of messages and data in a conversation. - * - * @category Common Types - */ -export type Role = "user" | "assistant"; -/** - * Describes a message returned as part of a prompt. - * - * This is similar to `SamplingMessage`, but also supports the embedding of - * resources from the MCP server. - * - * @category `prompts/get` - */ -export interface PromptMessage { - role: Role; - content: ContentBlock; -} -/** - * A resource that the server is capable of reading, included in a prompt or tool call result. - * - * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. - * - * @category Content - */ -export interface ResourceLink extends Resource { - type: "resource_link"; -} -/** - * The contents of a resource, embedded into a prompt or tool call result. - * - * It is up to the client how best to render embedded resources for the benefit - * of the LLM and/or the user. - * - * @category Content - */ -export interface EmbeddedResource { - type: "resource"; - resource: TextResourceContents | BlobResourceContents; - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * 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. - * - * @category `notifications/prompts/list_changed` - */ -export interface PromptListChangedNotification extends JSONRPCNotification { - method: "notifications/prompts/list_changed"; - params?: NotificationParams; -} -/** - * Sent from the client to request a list of tools the server has. - * - * @category `tools/list` - */ -export interface ListToolsRequest extends PaginatedRequest { - method: "tools/list"; -} -/** - * The server's response to a tools/list request from the client. - * - * @category `tools/list` - */ -export interface ListToolsResult extends PaginatedResult { - tools: Tool[]; -} -/** - * The server's response to a tool call. - * - * @category `tools/call` - */ -export interface CallToolResult extends Result { - /** - * A list of content objects that represent the unstructured result of the tool call. - */ - content: ContentBlock[]; - /** - * An optional JSON object that represents the structured result of the tool call. - */ - structuredContent?: { - [key: string]: unknown; - }; - /** - * Whether the tool call ended in an error. - * - * If not set, this is assumed to be false (the call was successful). - * - * Any errors that originate from the tool SHOULD be reported inside the result - * object, with `isError` set to true, _not_ as an MCP protocol-level error - * response. Otherwise, the LLM would not be able to see that an error occurred - * and self-correct. - * - * However, any errors in _finding_ the tool, an error indicating that the - * server does not support tool calls, or any other exceptional conditions, - * should be reported as an MCP error response. - */ - isError?: boolean; -} -/** - * Parameters for a `tools/call` request. - * - * @category `tools/call` - */ -export interface CallToolRequestParams extends RequestParams { - /** - * The name of the tool. - */ - name: string; - /** - * Arguments to use for the tool call. - */ - arguments?: { - [key: string]: unknown; - }; -} -/** - * Used by the client to invoke a tool provided by the server. - * - * @category `tools/call` - */ -export interface CallToolRequest extends JSONRPCRequest { - method: "tools/call"; - params: CallToolRequestParams; -} -/** - * 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. - * - * @category `notifications/tools/list_changed` - */ -export interface ToolListChangedNotification extends JSONRPCNotification { - method: "notifications/tools/list_changed"; - params?: NotificationParams; -} -/** - * Security scheme indicating no authentication is required. - * - * @category `tools/list` - */ -export interface NoAuthSecurityScheme { - type: "noauth"; -} -/** - * Security scheme indicating OAuth 2.0 authentication is required. - * - * @category `tools/list` - */ -export interface OAuth2SecurityScheme { - type: "oauth2"; - /** - * Optional list of OAuth 2.0 scopes required for this tool. - */ - scopes?: string[]; -} -/** - * A security scheme that can be used to authenticate tool calls. - * - * @category `tools/list` - */ -export type SecurityScheme = NoAuthSecurityScheme | OAuth2SecurityScheme; -/** - * Additional properties describing a Tool to clients. - * - * NOTE: all properties in ToolAnnotations are **hints**. - * They are not guaranteed to provide a faithful description of - * tool behavior (including descriptive properties like `title`). - * - * Clients should never make tool use decisions based on ToolAnnotations - * received from untrusted servers. - * - * @category `tools/list` - */ -export interface ToolAnnotations { - /** - * A human-readable title for the tool. - */ - title?: string; - /** - * If true, the tool does not modify its environment. - * - * Default: false - */ - readOnlyHint?: boolean; - /** - * If true, the tool may perform destructive updates to its environment. - * If false, the tool performs only additive updates. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: true - */ - destructiveHint?: boolean; - /** - * If true, calling the tool repeatedly with the same arguments - * will have no additional effect on its environment. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: false - */ - idempotentHint?: boolean; - /** - * If true, this tool may interact with an "open world" of external - * entities. If false, the tool's domain of interaction is closed. - * For example, the world of a web search tool is open, whereas that - * of a memory tool is not. - * - * Default: true - */ - openWorldHint?: boolean; -} -/** - * Definition for a tool the client can call. - * - * @category `tools/list` - */ -export interface Tool extends BaseMetadata, Icons { - /** - * A human-readable description of the tool. - * - * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. - */ - description?: string; - /** - * A JSON Schema object defining the expected parameters for the tool. - */ - inputSchema: { - type: "object"; - properties?: { - [key: string]: object; - }; - required?: string[]; - }; - /** - * An optional JSON Schema object defining the structure of the tool's output returned in - * the structuredContent field of a CallToolResult. - */ - outputSchema?: { - type: "object"; - properties?: { - [key: string]: object; - }; - required?: string[]; - }; - /** - * Optional additional tool information. - * - * Display name precedence order is: title, annotations.title, then name. - */ - annotations?: ToolAnnotations; - /** - * Optional list of security schemes supported by this tool. - * If missing, the tool follows the server's default authentication policy. - * If present, lists the supported authentication schemes (e.g., "noauth", "oauth2"). - */ - securitySchemes?: SecurityScheme[]; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * Parameters for a `logging/setLevel` request. - * - * @category `logging/setLevel` - */ -export interface SetLevelRequestParams extends RequestParams { - /** - * 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/message. - */ - level: LoggingLevel; -} -/** - * A request from the client to the server, to enable or adjust logging. - * - * @category `logging/setLevel` - */ -export interface SetLevelRequest extends JSONRPCRequest { - method: "logging/setLevel"; - params: SetLevelRequestParams; -} -/** - * Parameters for a `notifications/message` notification. - * - * @category `notifications/message` - */ -export interface LoggingMessageNotificationParams extends NotificationParams { - /** - * The severity of this log message. - */ - level: LoggingLevel; - /** - * An optional name of the logger issuing this message. - */ - logger?: string; - /** - * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. - */ - data: unknown; -} -/** - * JSONRPCNotification 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. - * - * @category `notifications/message` - */ -export interface LoggingMessageNotification extends JSONRPCNotification { - method: "notifications/message"; - params: LoggingMessageNotificationParams; -} -/** - * The severity of a log message. - * - * These map to syslog message severities, as specified in RFC-5424: - * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 - * - * @category Common Types - */ -export type LoggingLevel = "debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency"; -/** - * Parameters for a `sampling/createMessage` request. - * - * @category `sampling/createMessage` - */ -export interface CreateMessageRequestParams extends RequestParams { - messages: SamplingMessage[]; - /** - * The server's preferences for which model to select. The client MAY ignore these preferences. - */ - modelPreferences?: ModelPreferences; - /** - * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. - */ - systemPrompt?: string; - /** - * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. - * The client MAY ignore this request. - * - * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client - * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. - */ - includeContext?: "none" | "thisServer" | "allServers"; - /** - * @TJS-type number - */ - temperature?: number; - /** - * The requested maximum number of tokens to sample (to prevent runaway completions). - * - * The client MAY choose to sample fewer tokens than the requested maximum. - */ - maxTokens: number; - stopSequences?: string[]; - /** - * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. - */ - metadata?: object; - /** - * Tools that the model may use during generation. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. - */ - tools?: Tool[]; - /** - * Controls how the model uses tools. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. - * Default is `{ mode: "auto" }`. - */ - toolChoice?: ToolChoice; -} -/** - * Controls tool selection behavior for sampling requests. - * - * @category `sampling/createMessage` - */ -export interface ToolChoice { - /** - * Controls the tool use ability of the model: - * - "auto": Model decides whether to use tools (default) - * - "required": Model MUST use at least one tool before completing - * - "none": Model MUST NOT use any tools - */ - mode?: "auto" | "required" | "none"; -} -/** - * 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. - * - * @category `sampling/createMessage` - */ -export interface CreateMessageRequest extends JSONRPCRequest { - method: "sampling/createMessage"; - params: CreateMessageRequestParams; -} -/** - * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. - * - * @category `sampling/createMessage` - */ -export interface CreateMessageResult extends Result, SamplingMessage { - /** - * The name of the model that generated the message. - */ - model: string; - /** - * The reason why sampling stopped, if known. - * - * Standard values: - * - "endTurn": Natural end of the assistant's turn - * - "stopSequence": A stop sequence was encountered - * - "maxTokens": Maximum token limit was reached - * - "toolUse": The model wants to use one or more tools - * - * This field is an open string to allow for provider-specific stop reasons. - */ - stopReason?: "endTurn" | "stopSequence" | "maxTokens" | "toolUse" | string; -} -/** - * Describes a message issued to or received from an LLM API. - * - * @category `sampling/createMessage` - */ -export interface SamplingMessage { - role: Role; - content: SamplingMessageContentBlock | SamplingMessageContentBlock[]; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -export type SamplingMessageContentBlock = TextContent | ImageContent | AudioContent | ToolUseContent | ToolResultContent; -/** - * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed - * - * @category Common Types - */ -export interface Annotations { - /** - * Describes who the intended customer of this object or data is. - * - * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). - */ - audience?: Role[]; - /** - * Describes how important this data is for operating the server. - * - * A value of 1 means "most important," and indicates that the data is - * effectively required, while 0 means "least important," and indicates that - * the data is entirely optional. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - priority?: number; - /** - * The moment the resource was last modified, as an ISO 8601 formatted string. - * - * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"). - * - * Examples: last activity timestamp in an open file, timestamp when the resource - * was attached, etc. - */ - lastModified?: string; -} -/** - * @category Content - */ -export type ContentBlock = TextContent | ImageContent | AudioContent | ResourceLink | EmbeddedResource; -/** - * Text provided to or from an LLM. - * - * @category Content - */ -export interface TextContent { - type: "text"; - /** - * The text content of the message. - */ - text: string; - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * An image provided to or from an LLM. - * - * @category Content - */ -export interface ImageContent { - type: "image"; - /** - * The base64-encoded image data. - * - * @format byte - */ - data: string; - /** - * The MIME type of the image. Different providers may support different image types. - */ - mimeType: string; - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * Audio provided to or from an LLM. - * - * @category Content - */ -export interface AudioContent { - type: "audio"; - /** - * The base64-encoded audio data. - * - * @format byte - */ - data: string; - /** - * The MIME type of the audio. Different providers may support different audio types. - */ - mimeType: string; - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * A request from the assistant to call a tool. - * - * @category `sampling/createMessage` - */ -export interface ToolUseContent { - type: "tool_use"; - /** - * A unique identifier for this tool use. - * - * This ID is used to match tool results to their corresponding tool uses. - */ - id: string; - /** - * The name of the tool to call. - */ - name: string; - /** - * The arguments to pass to the tool, conforming to the tool's input schema. - */ - input: { - [key: string]: unknown; - }; - /** - * Optional metadata about the tool use. Clients SHOULD preserve this field when - * including tool uses in subsequent sampling requests to enable caching optimizations. - * - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * The result of a tool use, provided by the user back to the assistant. - * - * @category `sampling/createMessage` - */ -export interface ToolResultContent { - type: "tool_result"; - /** - * The ID of the tool use this result corresponds to. - * - * This MUST match the ID from a previous ToolUseContent. - */ - toolUseId: string; - /** - * The unstructured result content of the tool use. - * - * This has the same format as CallToolResult.content and can include text, images, - * audio, resource links, and embedded resources. - */ - content: ContentBlock[]; - /** - * An optional structured result object. - * - * If the tool defined an outputSchema, this SHOULD conform to that schema. - */ - structuredContent?: { - [key: string]: unknown; - }; - /** - * Whether the tool use resulted in an error. - * - * If true, the content typically describes the error that occurred. - * Default: false - */ - isError?: boolean; - /** - * Optional metadata about the tool result. Clients SHOULD preserve this field when - * including tool results in subsequent sampling requests to enable caching optimizations. - * - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * The server's preferences for model selection, requested of the client during sampling. - * - * Because LLMs can vary along multiple dimensions, choosing the "best" model is - * rarely straightforward. Different models excel in different areas—some are - * faster but less capable, others are more capable but more expensive, and so - * on. This interface allows servers to express their priorities across multiple - * dimensions to help clients make an appropriate selection for their use case. - * - * These preferences are always advisory. The client MAY ignore them. It is also - * up to the client to decide how to interpret these preferences and how to - * balance them against other considerations. - * - * @category `sampling/createMessage` - */ -export interface ModelPreferences { - /** - * Optional hints to use for model selection. - * - * If multiple hints are specified, the client MUST evaluate them in order - * (such that the first match is taken). - * - * The client SHOULD prioritize these hints over the numeric priorities, but - * MAY still use the priorities to select from ambiguous matches. - */ - hints?: ModelHint[]; - /** - * How much to prioritize cost when selecting a model. A value of 0 means cost - * is not important, while a value of 1 means cost is the most important - * factor. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - costPriority?: number; - /** - * How much to prioritize sampling speed (latency) when selecting a model. A - * value of 0 means speed is not important, while a value of 1 means speed is - * the most important factor. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - speedPriority?: number; - /** - * How much to prioritize intelligence and capabilities when selecting a - * model. A value of 0 means intelligence is not important, while a value of 1 - * means intelligence is the most important factor. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - intelligencePriority?: number; -} -/** - * Hints to use for model selection. - * - * Keys not declared here are currently left unspecified by the spec and are up - * to the client to interpret. - * - * @category `sampling/createMessage` - */ -export interface ModelHint { - /** - * A hint for a model name. - * - * The client SHOULD treat this as a substring of a model name; for example: - * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` - * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. - * - `claude` should match any Claude model - * - * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: - * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` - */ - name?: string; -} -/** - * Parameters for a `completion/complete` request. - * - * @category `completion/complete` - */ -export interface CompleteRequestParams extends RequestParams { - ref: PromptReference | ResourceTemplateReference; - /** - * The argument's information - */ - argument: { - /** - * The name of the argument - */ - name: string; - /** - * The value of the argument to use for completion matching. - */ - value: string; - }; - /** - * Additional, optional context for completions - */ - context?: { - /** - * Previously-resolved variables in a URI template or prompt. - */ - arguments?: { - [key: string]: string; - }; - }; -} -/** - * A request from the client to the server, to ask for completion options. - * - * @category `completion/complete` - */ -export interface CompleteRequest extends JSONRPCRequest { - method: "completion/complete"; - params: CompleteRequestParams; -} -/** - * The server's response to a completion/complete request - * - * @category `completion/complete` - */ -export interface CompleteResult extends Result { - completion: { - /** - * An array of completion values. Must not exceed 100 items. - */ - values: string[]; - /** - * The total number of completion options available. This can exceed the number of values actually sent in the response. - */ - total?: number; - /** - * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. - */ - hasMore?: boolean; - }; -} -/** - * A reference to a resource or resource template definition. - * - * @category `completion/complete` - */ -export interface ResourceTemplateReference { - type: "ref/resource"; - /** - * The URI or URI template of the resource. - * - * @format uri-template - */ - uri: string; -} -/** - * Identifies a prompt. - * - * @category `completion/complete` - */ -export interface PromptReference extends BaseMetadata { - type: "ref/prompt"; -} -/** - * Sent from the server to request a list of root URIs from the client. Roots allow - * servers to ask for specific directories or files to operate on. A common example - * for roots is providing a set of repositories or directories a server should operate - * on. - * - * This request is typically used when the server needs to understand the file system - * structure or access specific locations that the client has permission to read from. - * - * @category `roots/list` - */ -export interface ListRootsRequest extends JSONRPCRequest { - method: "roots/list"; - params?: RequestParams; -} -/** - * The client's response to a roots/list request from the server. - * This result contains an array of Root objects, each representing a root directory - * or file that the server can operate on. - * - * @category `roots/list` - */ -export interface ListRootsResult extends Result { - roots: Root[]; -} -/** - * Represents a root directory or file that the server can operate on. - * - * @category `roots/list` - */ -export interface Root { - /** - * The URI identifying the root. This *must* start with file:// for now. - * This restriction may be relaxed in future versions of the protocol to allow - * other URI schemes. - * - * @format uri - */ - uri: string; - /** - * An optional name for the root. This can be used to provide a human-readable - * identifier for the root, which may be useful for display purposes or for - * referencing the root in other parts of the application. - */ - name?: string; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * A notification from the client to the server, informing it that the list of roots has changed. - * This notification should be sent whenever the client adds, removes, or modifies any root. - * The server should then request an updated list of roots using the ListRootsRequest. - * - * @category `notifications/roots/list_changed` - */ -export interface RootsListChangedNotification extends JSONRPCNotification { - method: "notifications/roots/list_changed"; - params?: NotificationParams; -} -/** - * The parameters for a request to elicit non-sensitive information from the user via a form in the client. - * - * @category `elicitation/create` - */ -export interface ElicitRequestFormParams extends RequestParams { - /** - * The elicitation mode. - */ - mode: "form"; - /** - * The message to present to the user describing what information is being requested. - */ - message: string; - /** - * A restricted subset of JSON Schema. - * Only top-level properties are allowed, without nesting. - */ - requestedSchema: { - type: "object"; - properties: { - [key: string]: PrimitiveSchemaDefinition; - }; - required?: string[]; - }; -} -/** - * The parameters for a request to elicit information from the user via a URL in the client. - * - * @category `elicitation/create` - */ -export interface ElicitRequestURLParams extends RequestParams { - /** - * The elicitation mode. - */ - mode: "url"; - /** - * The message to present to the user explaining why the interaction is needed. - */ - message: string; - /** - * The ID of the elicitation, which must be unique within the context of the server. - * The client MUST treat this ID as an opaque value. - */ - elicitationId: string; - /** - * The URL that the user should navigate to. - * - * @format uri - */ - url: string; -} -/** - * The parameters for a request to elicit additional information from the user via the client. - * - * @category `elicitation/create` - */ -export type ElicitRequestParams = ElicitRequestFormParams | ElicitRequestURLParams; -/** - * A request from the server to elicit additional information from the user via the client. - * - * @category `elicitation/create` - */ -export interface ElicitRequest extends JSONRPCRequest { - method: "elicitation/create"; - params: ElicitRequestParams; -} -/** - * Restricted schema definitions that only allow primitive types - * without nested objects or arrays. - * - * @category `elicitation/create` - */ -export type PrimitiveSchemaDefinition = StringSchema | NumberSchema | BooleanSchema | EnumSchema; -/** - * @category `elicitation/create` - */ -export interface StringSchema { - type: "string"; - title?: string; - description?: string; - minLength?: number; - maxLength?: number; - format?: "email" | "uri" | "date" | "date-time"; - default?: string; -} -/** - * @category `elicitation/create` - */ -export interface NumberSchema { - type: "number" | "integer"; - title?: string; - description?: string; - minimum?: number; - maximum?: number; - default?: number; -} -/** - * @category `elicitation/create` - */ -export interface BooleanSchema { - type: "boolean"; - title?: string; - description?: string; - default?: boolean; -} -/** - * Schema for single-selection enumeration without display titles for options. - * - * @category `elicitation/create` - */ -export interface UntitledSingleSelectEnumSchema { - type: "string"; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Array of enum values to choose from. - */ - enum: string[]; - /** - * Optional default value. - */ - default?: string; -} -/** - * Schema for single-selection enumeration with display titles for each option. - * - * @category `elicitation/create` - */ -export interface TitledSingleSelectEnumSchema { - type: "string"; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Array of enum options with values and display labels. - */ - oneOf: Array<{ - /** - * The enum value. - */ - const: string; - /** - * Display label for this option. - */ - title: string; - }>; - /** - * Optional default value. - */ - default?: string; -} -/** - * @category `elicitation/create` - */ -export type SingleSelectEnumSchema = UntitledSingleSelectEnumSchema | TitledSingleSelectEnumSchema; -/** - * Schema for multiple-selection enumeration without display titles for options. - * - * @category `elicitation/create` - */ -export interface UntitledMultiSelectEnumSchema { - type: "array"; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Minimum number of items to select. - */ - minItems?: number; - /** - * Maximum number of items to select. - */ - maxItems?: number; - /** - * Schema for the array items. - */ - items: { - type: "string"; - /** - * Array of enum values to choose from. - */ - enum: string[]; - }; - /** - * Optional default value. - */ - default?: string[]; -} -/** - * Schema for multiple-selection enumeration with display titles for each option. - * - * @category `elicitation/create` - */ -export interface TitledMultiSelectEnumSchema { - type: "array"; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Minimum number of items to select. - */ - minItems?: number; - /** - * Maximum number of items to select. - */ - maxItems?: number; - /** - * Schema for array items with enum options and display labels. - */ - items: { - /** - * Array of enum options with values and display labels. - */ - anyOf: Array<{ - /** - * The constant enum value. - */ - const: string; - /** - * Display title for this option. - */ - title: string; - }>; - }; - /** - * Optional default value. - */ - default?: string[]; -} -/** - * @category `elicitation/create` - */ -export type MultiSelectEnumSchema = UntitledMultiSelectEnumSchema | TitledMultiSelectEnumSchema; -/** - * Use TitledSingleSelectEnumSchema instead. - * This interface will be removed in a future version. - * - * @category `elicitation/create` - */ -export interface LegacyTitledEnumSchema { - type: "string"; - title?: string; - description?: string; - enum: string[]; - /** - * (Legacy) Display names for enum values. - * Non-standard according to JSON schema 2020-12. - */ - enumNames?: string[]; - default?: string; -} -/** - * @category `elicitation/create` - */ -export type EnumSchema = SingleSelectEnumSchema | MultiSelectEnumSchema | LegacyTitledEnumSchema; -/** - * The client's response to an elicitation request. - * - * @category `elicitation/create` - */ -export interface ElicitResult extends Result { - /** - * The user action in response to the elicitation. - * - "accept": User submitted the form/confirmed the action - * - "decline": User explicitly decline the action - * - "cancel": User dismissed without making an explicit choice - */ - action: "accept" | "decline" | "cancel"; - /** - * The submitted form data, only present when action is "accept" and mode was "form". - * Contains values matching the requested schema. - * Omitted for out-of-band mode responses. - */ - content?: { - [key: string]: string | number | boolean | string[]; - }; -} -/** - * An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request. - * - * @category `notifications/elicitation/complete` - */ -export interface ElicitationCompleteNotification extends JSONRPCNotification { - method: "notifications/elicitation/complete"; - params: { - /** - * The ID of the elicitation that completed. - */ - elicitationId: string; - }; -} -/** @internal */ -export type ClientRequest = PingRequest | InitializeRequest | CompleteRequest | SetLevelRequest | GetPromptRequest | ListPromptsRequest | ListResourcesRequest | ListResourceTemplatesRequest | ReadResourceRequest | SubscribeRequest | UnsubscribeRequest | CallToolRequest | ListToolsRequest; -/** @internal */ -export type ClientNotification = CancelledNotification | ProgressNotification | InitializedNotification | RootsListChangedNotification; -/** @internal */ -export type ClientResult = EmptyResult | CreateMessageResult | ListRootsResult | ElicitResult; -/** @internal */ -export type ServerRequest = PingRequest | CreateMessageRequest | ListRootsRequest | ElicitRequest; -/** @internal */ -export type ServerNotification = CancelledNotification | ProgressNotification | LoggingMessageNotification | ResourceUpdatedNotification | ResourceListChangedNotification | ToolListChangedNotification | PromptListChangedNotification | ElicitationCompleteNotification; -/** @internal */ -export type ServerResult = EmptyResult | InitializeResult | CompleteResult | GetPromptResult | ListPromptsResult | ListResourceTemplatesResult | ListResourcesResult | ReadResourceResult | CallToolResult | ListToolsResult; -//# sourceMappingURL=spec.types.d.ts.map \ No newline at end of file diff --git a/dist/cjs/spec.types.d.ts.map b/dist/cjs/spec.types.d.ts.map deleted file mode 100644 index 3e44f68e82..0000000000 --- a/dist/cjs/spec.types.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"spec.types.d.ts","sourceRoot":"","sources":["../../src/spec.types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH;;;;GAIG;AACH,MA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,GAC1B,2BAA2B,GAC3B,+BAA+B,GAC/B,2BAA2B,GAC3B,6BAA6B,GAC7B,+BAA+B,CAAC;AAEpC,gBAAgB;AAChB,MAAM,MAAM,YAAY,GACpB,WAAW,GACX,gBAAgB,GAChB,cAAc,GACd,eAAe,GACf,iBAAiB,GACjB,2BAA2B,GAC3B,mBAAmB,GACnB,kBAAkB,GAClB,cAAc,GACd,eAAe,CAAC"} \ No newline at end of file diff --git a/dist/cjs/spec.types.js b/dist/cjs/spec.types.js deleted file mode 100644 index 77bf7d35e4..0000000000 --- a/dist/cjs/spec.types.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -/** - * This file is automatically generated from the Model Context Protocol specification. - * - * Source: https://github.com/modelcontextprotocol/modelcontextprotocol - * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts - * Last updated from commit: 4528444698f76e6d0337e58d2941d5d3485d779d - * - * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. - * To update this file, run: npm run fetch:spec-types - */ /* JSON-RPC types */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.URL_ELICITATION_REQUIRED = exports.INTERNAL_ERROR = exports.INVALID_PARAMS = exports.METHOD_NOT_FOUND = exports.INVALID_REQUEST = exports.PARSE_ERROR = exports.JSONRPC_VERSION = exports.LATEST_PROTOCOL_VERSION = void 0; -/** @internal */ -exports.LATEST_PROTOCOL_VERSION = "DRAFT-2025-v3"; -/** @internal */ -exports.JSONRPC_VERSION = "2.0"; -// Standard JSON-RPC error codes -exports.PARSE_ERROR = -32700; -exports.INVALID_REQUEST = -32600; -exports.METHOD_NOT_FOUND = -32601; -exports.INVALID_PARAMS = -32602; -exports.INTERNAL_ERROR = -32603; -// Implementation-specific JSON-RPC error codes [-32000, -32099] -/** @internal */ -exports.URL_ELICITATION_REQUIRED = -32042; -//# sourceMappingURL=spec.types.js.map \ No newline at end of file diff --git a/dist/cjs/spec.types.js.map b/dist/cjs/spec.types.js.map deleted file mode 100644 index 0a09728c5a..0000000000 --- a/dist/cjs/spec.types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"spec.types.js","sourceRoot":"","sources":["../../src/spec.types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;GASG,CAAA,oBAAoB;;;AAavB,gBAAgB;AACH,QAAA,uBAAuB,GAAG,eAAe,CAAC;AACvD,gBAAgB;AACH,QAAA,eAAe,GAAG,KAAK,CAAC;AA4HrC,gCAAgC;AACnB,QAAA,WAAW,GAAG,CAAC,KAAK,CAAC;AACrB,QAAA,eAAe,GAAG,CAAC,KAAK,CAAC;AACzB,QAAA,gBAAgB,GAAG,CAAC,KAAK,CAAC;AAC1B,QAAA,cAAc,GAAG,CAAC,KAAK,CAAC;AACxB,QAAA,cAAc,GAAG,CAAC,KAAK,CAAC;AAErC,gEAAgE;AAChE,gBAAgB;AACH,QAAA,wBAAwB,GAAG,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/dist/cjs/types.d.ts b/dist/cjs/types.d.ts deleted file mode 100644 index 392b544dd5..0000000000 --- a/dist/cjs/types.d.ts +++ /dev/null @@ -1,4390 +0,0 @@ -import * as z from 'zod/v4'; -import { AuthInfo } from './server/auth/types.js'; -export declare const LATEST_PROTOCOL_VERSION = "2025-06-18"; -export declare const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; -export declare const SUPPORTED_PROTOCOL_VERSIONS: string[]; -export declare const JSONRPC_VERSION = "2.0"; -/** - * Utility types - */ -type ExpandRecursively = T extends object ? (T extends infer O ? { - [K in keyof O]: ExpandRecursively; -} : never) : T; -/** - * A progress token, used to associate progress notifications with the original request. - */ -export declare const ProgressTokenSchema: z.ZodUnion; -/** - * An opaque token used to represent a cursor for pagination. - */ -export declare const CursorSchema: z.ZodString; -declare const RequestMetaSchema: z.ZodObject<{ - /** - * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. - */ - progressToken: z.ZodOptional>; -}, z.core.$loose>; -/** - * Common params for any request. - */ -declare const BaseRequestParamsSchema: z.ZodObject<{ - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta: z.ZodOptional>; - }, z.core.$loose>>; -}, z.core.$loose>; -export declare const RequestSchema: z.ZodObject<{ - method: z.ZodString; - params: z.ZodOptional>; - }, z.core.$loose>>; - }, z.core.$loose>>; -}, z.core.$strip>; -declare const NotificationsParamsSchema: z.ZodObject<{ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.ZodOptional>; -}, z.core.$loose>; -export declare const NotificationSchema: z.ZodObject<{ - method: z.ZodString; - params: z.ZodOptional>; - }, z.core.$loose>>; -}, z.core.$strip>; -export declare const ResultSchema: z.ZodObject<{ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.ZodOptional>; -}, z.core.$loose>; -/** - * A uniquely identifying ID for a request in JSON-RPC. - */ -export declare const RequestIdSchema: z.ZodUnion; -/** - * A request that expects a response. - */ -export declare const JSONRPCRequestSchema: z.ZodObject<{ - method: z.ZodString; - params: z.ZodOptional>; - }, z.core.$loose>>; - }, z.core.$loose>>; - jsonrpc: z.ZodLiteral<"2.0">; - id: z.ZodUnion; -}, z.core.$strict>; -export declare const isJSONRPCRequest: (value: unknown) => value is JSONRPCRequest; -/** - * A notification which does not expect a response. - */ -export declare const JSONRPCNotificationSchema: z.ZodObject<{ - method: z.ZodString; - params: z.ZodOptional>; - }, z.core.$loose>>; - jsonrpc: z.ZodLiteral<"2.0">; -}, z.core.$strict>; -export declare const isJSONRPCNotification: (value: unknown) => value is JSONRPCNotification; -/** - * A successful (non-error) response to a request. - */ -export declare const JSONRPCResponseSchema: z.ZodObject<{ - jsonrpc: z.ZodLiteral<"2.0">; - id: z.ZodUnion; - result: z.ZodObject<{ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.ZodOptional>; - }, z.core.$loose>; -}, z.core.$strict>; -export declare const isJSONRPCResponse: (value: unknown) => value is JSONRPCResponse; -/** - * Error codes defined by the JSON-RPC specification. - */ -export declare enum ErrorCode { - ConnectionClosed = -32000, - RequestTimeout = -32001, - ParseError = -32700, - InvalidRequest = -32600, - MethodNotFound = -32601, - InvalidParams = -32602, - InternalError = -32603, - UrlElicitationRequired = -32042 -} -/** - * A response to a request that indicates an error occurred. - */ -export declare const JSONRPCErrorSchema: z.ZodObject<{ - jsonrpc: z.ZodLiteral<"2.0">; - id: z.ZodUnion; - error: z.ZodObject<{ - code: z.ZodNumber; - message: z.ZodString; - data: z.ZodOptional; - }, z.core.$strip>; -}, z.core.$strict>; -export declare const isJSONRPCError: (value: unknown) => value is JSONRPCError; -export declare const JSONRPCMessageSchema: z.ZodUnion>; - }, z.core.$loose>>; - }, z.core.$loose>>; - jsonrpc: z.ZodLiteral<"2.0">; - id: z.ZodUnion; -}, z.core.$strict>, z.ZodObject<{ - method: z.ZodString; - params: z.ZodOptional>; - }, z.core.$loose>>; - jsonrpc: z.ZodLiteral<"2.0">; -}, z.core.$strict>, z.ZodObject<{ - jsonrpc: z.ZodLiteral<"2.0">; - id: z.ZodUnion; - result: z.ZodObject<{ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.ZodOptional>; - }, z.core.$loose>; -}, z.core.$strict>, z.ZodObject<{ - jsonrpc: z.ZodLiteral<"2.0">; - id: z.ZodUnion; - error: z.ZodObject<{ - code: z.ZodNumber; - message: z.ZodString; - data: z.ZodOptional; - }, z.core.$strip>; -}, z.core.$strict>]>; -/** - * A response that indicates success but carries no data. - */ -export declare const EmptyResultSchema: z.ZodObject<{ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.ZodOptional>; -}, z.core.$strict>; -export declare const CancelledNotificationParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - requestId: z.ZodUnion; - reason: z.ZodOptional; -}, z.core.$loose>; -/** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its `initialize` request. - */ -export declare const CancelledNotificationSchema: z.ZodObject<{ - method: z.ZodLiteral<"notifications/cancelled">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - requestId: z.ZodUnion; - reason: z.ZodOptional; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * Icon schema for use in tools, prompts, resources, and implementations. - */ -export declare const IconSchema: z.ZodObject<{ - src: z.ZodString; - mimeType: z.ZodOptional; - sizes: z.ZodOptional>; -}, z.core.$strip>; -/** - * Base schema to add `icons` property. - * - */ -export declare const IconsSchema: z.ZodObject<{ - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; -}, z.core.$strip>; -/** - * Base metadata interface for common properties across resources, tools, prompts, and implementations. - */ -export declare const BaseMetadataSchema: z.ZodObject<{ - name: z.ZodString; - title: z.ZodOptional; -}, z.core.$strip>; -/** - * Describes the name and version of an MCP implementation. - */ -export declare const ImplementationSchema: z.ZodObject<{ - version: z.ZodString; - websiteUrl: z.ZodOptional; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; -}, z.core.$strip>; -/** - * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. - */ -export declare const ClientCapabilitiesSchema: z.ZodObject<{ - experimental: z.ZodOptional>>; - sampling: z.ZodOptional>; - tools: z.ZodOptional>; - }, z.core.$strip>>; - elicitation: z.ZodOptional, z.ZodIntersection; - }, z.core.$strip>, z.ZodRecord>>; - url: z.ZodOptional>; - }, z.core.$strip>, z.ZodOptional>>>>; - roots: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$strip>; -export declare const InitializeRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - protocolVersion: z.ZodString; - capabilities: z.ZodObject<{ - experimental: z.ZodOptional>>; - sampling: z.ZodOptional>; - tools: z.ZodOptional>; - }, z.core.$strip>>; - elicitation: z.ZodOptional, z.ZodIntersection; - }, z.core.$strip>, z.ZodRecord>>; - url: z.ZodOptional>; - }, z.core.$strip>, z.ZodOptional>>>>; - roots: z.ZodOptional; - }, z.core.$strip>>; - }, z.core.$strip>; - clientInfo: z.ZodObject<{ - version: z.ZodString; - websiteUrl: z.ZodOptional; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>; -}, z.core.$loose>; -/** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - */ -export declare const InitializeRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"initialize">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - protocolVersion: z.ZodString; - capabilities: z.ZodObject<{ - experimental: z.ZodOptional>>; - sampling: z.ZodOptional>; - tools: z.ZodOptional>; - }, z.core.$strip>>; - elicitation: z.ZodOptional, z.ZodIntersection; - }, z.core.$strip>, z.ZodRecord>>; - url: z.ZodOptional>; - }, z.core.$strip>, z.ZodOptional>>>>; - roots: z.ZodOptional; - }, z.core.$strip>>; - }, z.core.$strip>; - clientInfo: z.ZodObject<{ - version: z.ZodString; - websiteUrl: z.ZodOptional; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>; - }, z.core.$loose>; -}, z.core.$strip>; -export declare const isInitializeRequest: (value: unknown) => value is InitializeRequest; -/** - * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. - */ -export declare const ServerCapabilitiesSchema: z.ZodObject<{ - experimental: z.ZodOptional>>; - logging: z.ZodOptional>; - completions: z.ZodOptional>; - prompts: z.ZodOptional; - }, z.core.$strip>>; - resources: z.ZodOptional; - listChanged: z.ZodOptional; - }, z.core.$strip>>; - tools: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$strip>; -/** - * After receiving an initialize request from the client, the server sends this response. - */ -export declare const InitializeResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - protocolVersion: z.ZodString; - capabilities: z.ZodObject<{ - experimental: z.ZodOptional>>; - logging: z.ZodOptional>; - completions: z.ZodOptional>; - prompts: z.ZodOptional; - }, z.core.$strip>>; - resources: z.ZodOptional; - listChanged: z.ZodOptional; - }, z.core.$strip>>; - tools: z.ZodOptional; - }, z.core.$strip>>; - }, z.core.$strip>; - serverInfo: z.ZodObject<{ - version: z.ZodString; - websiteUrl: z.ZodOptional; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>; - instructions: z.ZodOptional; -}, z.core.$loose>; -/** - * This notification is sent from the client to the server after initialization has finished. - */ -export declare const InitializedNotificationSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/initialized">; -}, z.core.$strip>; -export declare const isInitializedNotification: (value: unknown) => value is InitializedNotification; -/** - * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. - */ -export declare const PingRequestSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - }, z.core.$loose>>; - method: z.ZodLiteral<"ping">; -}, z.core.$strip>; -export declare const ProgressSchema: z.ZodObject<{ - progress: z.ZodNumber; - total: z.ZodOptional; - message: z.ZodOptional; -}, z.core.$strip>; -export declare const ProgressNotificationParamsSchema: z.ZodObject<{ - progressToken: z.ZodUnion; - progress: z.ZodNumber; - total: z.ZodOptional; - message: z.ZodOptional; - _meta: z.ZodOptional>; -}, z.core.$strip>; -/** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - * - * @category notifications/progress - */ -export declare const ProgressNotificationSchema: z.ZodObject<{ - method: z.ZodLiteral<"notifications/progress">; - params: z.ZodObject<{ - progressToken: z.ZodUnion; - progress: z.ZodNumber; - total: z.ZodOptional; - message: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$strip>; -}, z.core.$strip>; -export declare const PaginatedRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; -}, z.core.$loose>; -export declare const PaginatedRequestSchema: z.ZodObject<{ - method: z.ZodString; - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; -}, z.core.$strip>; -export declare const PaginatedResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; -}, z.core.$loose>; -/** - * The contents of a specific resource or sub-resource. - */ -export declare const ResourceContentsSchema: z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; -}, z.core.$strip>; -export declare const TextResourceContentsSchema: z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - text: z.ZodString; -}, z.core.$strip>; -export declare const BlobResourceContentsSchema: z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; -}, z.core.$strip>; -/** - * A known resource that the server is capable of reading. - */ -export declare const ResourceSchema: z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; -}, z.core.$strip>; -/** - * A template description for resources available on the server. - */ -export declare const ResourceTemplateSchema: z.ZodObject<{ - uriTemplate: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; -}, z.core.$strip>; -/** - * Sent from the client to request a list of resources the server has. - */ -export declare const ListResourcesRequestSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"resources/list">; -}, z.core.$strip>; -/** - * The server's response to a resources/list request from the client. - */ -export declare const ListResourcesResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - resources: z.ZodArray; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>; -/** - * Sent from the client to request a list of resource templates the server has. - */ -export declare const ListResourceTemplatesRequestSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"resources/templates/list">; -}, z.core.$strip>; -/** - * The server's response to a resources/templates/list request from the client. - */ -export declare const ListResourceTemplatesResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - resourceTemplates: z.ZodArray; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>; -export declare const ResourceRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; -}, z.core.$loose>; -/** - * Parameters for a `resources/read` request. - */ -export declare const ReadResourceRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; -}, z.core.$loose>; -/** - * Sent from the client to the server, to read a specific resource URI. - */ -export declare const ReadResourceRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"resources/read">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * The server's response to a resources/read request from the client. - */ -export declare const ReadResourceResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - contents: z.ZodArray; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>>; -}, z.core.$loose>; -/** - * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. - */ -export declare const ResourceListChangedNotificationSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/resources/list_changed">; -}, z.core.$strip>; -export declare const SubscribeRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; -}, z.core.$loose>; -/** - * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. - */ -export declare const SubscribeRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"resources/subscribe">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>; -export declare const UnsubscribeRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; -}, z.core.$loose>; -/** - * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. - */ -export declare const UnsubscribeRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"resources/unsubscribe">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * Parameters for a `notifications/resources/updated` notification. - */ -export declare const ResourceUpdatedNotificationParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - uri: z.ZodString; -}, z.core.$loose>; -/** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. - */ -export declare const ResourceUpdatedNotificationSchema: z.ZodObject<{ - method: z.ZodLiteral<"notifications/resources/updated">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * Describes an argument that a prompt can accept. - */ -export declare const PromptArgumentSchema: z.ZodObject<{ - name: z.ZodString; - description: z.ZodOptional; - required: z.ZodOptional; -}, z.core.$strip>; -/** - * A prompt or prompt template that the server offers. - */ -export declare const PromptSchema: z.ZodObject<{ - description: z.ZodOptional; - arguments: z.ZodOptional; - required: z.ZodOptional; - }, z.core.$strip>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; -}, z.core.$strip>; -/** - * Sent from the client to request a list of prompts and prompt templates the server has. - */ -export declare const ListPromptsRequestSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"prompts/list">; -}, z.core.$strip>; -/** - * The server's response to a prompts/list request from the client. - */ -export declare const ListPromptsResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - prompts: z.ZodArray; - arguments: z.ZodOptional; - required: z.ZodOptional; - }, z.core.$strip>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>; -/** - * Parameters for a `prompts/get` request. - */ -export declare const GetPromptRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - name: z.ZodString; - arguments: z.ZodOptional>; -}, z.core.$loose>; -/** - * Used by the client to get a prompt provided by the server. - */ -export declare const GetPromptRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"prompts/get">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - name: z.ZodString; - arguments: z.ZodOptional>; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * Text provided to or from an LLM. - */ -export declare const TextContentSchema: z.ZodObject<{ - type: z.ZodLiteral<"text">; - text: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>; -/** - * An image provided to or from an LLM. - */ -export declare const ImageContentSchema: z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>; -/** - * An Audio provided to or from an LLM. - */ -export declare const AudioContentSchema: z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>; -/** - * A tool call request from an assistant (LLM). - * Represents the assistant's request to use a tool. - */ -export declare const ToolUseContentSchema: z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; -}, z.core.$loose>; -/** - * The contents of a resource, embedded into a prompt or tool call result. - */ -export declare const EmbeddedResourceSchema: z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; -}, z.core.$strip>; -/** - * A resource that the server is capable of reading, included in a prompt or tool call result. - * - * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. - */ -export declare const ResourceLinkSchema: z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; -}, z.core.$strip>; -/** - * A content block that can be used in prompts and tool results. - */ -export declare const ContentBlockSchema: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; -}, z.core.$strip>]>; -/** - * Describes a message returned as part of a prompt. - */ -export declare const PromptMessageSchema: z.ZodObject<{ - role: z.ZodEnum<{ - user: "user"; - assistant: "assistant"; - }>; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>; -}, z.core.$strip>; -/** - * The server's response to a prompts/get request from the client. - */ -export declare const GetPromptResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - description: z.ZodOptional; - messages: z.ZodArray; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>; - }, z.core.$strip>>; -}, z.core.$loose>; -/** - * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. - */ -export declare const PromptListChangedNotificationSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/prompts/list_changed">; -}, z.core.$strip>; -/** - * Security scheme indicating no authentication is required. - */ -export declare const NoAuthSecuritySchemeSchema: z.ZodObject<{ - type: z.ZodLiteral<"noauth">; -}, z.core.$strip>; -/** - * Security scheme indicating OAuth 2.0 authentication is required. - */ -export declare const OAuth2SecuritySchemeSchema: z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; -}, z.core.$strip>; -/** - * A security scheme that can be used to authenticate tool calls. - */ -export declare const SecuritySchemeSchema: z.ZodUnion; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; -}, z.core.$strip>]>; -/** - * Additional properties describing a Tool to clients. - * - * NOTE: all properties in ToolAnnotations are **hints**. - * They are not guaranteed to provide a faithful description of - * tool behavior (including descriptive properties like `title`). - * - * Clients should never make tool use decisions based on ToolAnnotations - * received from untrusted servers. - */ -export declare const ToolAnnotationsSchema: z.ZodObject<{ - title: z.ZodOptional; - readOnlyHint: z.ZodOptional; - destructiveHint: z.ZodOptional; - idempotentHint: z.ZodOptional; - openWorldHint: z.ZodOptional; -}, z.core.$strip>; -/** - * Definition for a tool the client can call. - */ -export declare const ToolSchema: z.ZodObject<{ - description: z.ZodOptional; - inputSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>; - outputSchema: z.ZodOptional; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>>; - annotations: z.ZodOptional; - readOnlyHint: z.ZodOptional; - destructiveHint: z.ZodOptional; - idempotentHint: z.ZodOptional; - openWorldHint: z.ZodOptional; - }, z.core.$strip>>; - securitySchemes: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; - }, z.core.$strip>]>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; -}, z.core.$strip>; -/** - * Sent from the client to request a list of tools the server has. - */ -export declare const ListToolsRequestSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"tools/list">; -}, z.core.$strip>; -/** - * The server's response to a tools/list request from the client. - */ -export declare const ListToolsResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - tools: z.ZodArray; - inputSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>; - outputSchema: z.ZodOptional; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>>; - annotations: z.ZodOptional; - readOnlyHint: z.ZodOptional; - destructiveHint: z.ZodOptional; - idempotentHint: z.ZodOptional; - openWorldHint: z.ZodOptional; - }, z.core.$strip>>; - securitySchemes: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; - }, z.core.$strip>]>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>; -/** - * The server's response to a tool call. - */ -export declare const CallToolResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; -}, z.core.$loose>; -/** - * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. - */ -export declare const CompatibilityCallToolResultSchema: z.ZodUnion<[z.ZodObject<{ - _meta: z.ZodOptional>; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - toolResult: z.ZodUnknown; -}, z.core.$loose>]>; -/** - * Parameters for a `tools/call` request. - */ -export declare const CallToolRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - name: z.ZodString; - arguments: z.ZodOptional>; -}, z.core.$loose>; -/** - * Used by the client to invoke a tool provided by the server. - */ -export declare const CallToolRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"tools/call">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - name: z.ZodString; - arguments: z.ZodOptional>; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. - */ -export declare const ToolListChangedNotificationSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/tools/list_changed">; -}, z.core.$strip>; -/** - * The severity of a log message. - */ -export declare const LoggingLevelSchema: z.ZodEnum<{ - error: "error"; - debug: "debug"; - info: "info"; - notice: "notice"; - warning: "warning"; - critical: "critical"; - alert: "alert"; - emergency: "emergency"; -}>; -/** - * Parameters for a `logging/setLevel` request. - */ -export declare const SetLevelRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - level: z.ZodEnum<{ - error: "error"; - debug: "debug"; - info: "info"; - notice: "notice"; - warning: "warning"; - critical: "critical"; - alert: "alert"; - emergency: "emergency"; - }>; -}, z.core.$loose>; -/** - * A request from the client to the server, to enable or adjust logging. - */ -export declare const SetLevelRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"logging/setLevel">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - level: z.ZodEnum<{ - error: "error"; - debug: "debug"; - info: "info"; - notice: "notice"; - warning: "warning"; - critical: "critical"; - alert: "alert"; - emergency: "emergency"; - }>; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * Parameters for a `notifications/message` notification. - */ -export declare const LoggingMessageNotificationParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - level: z.ZodEnum<{ - error: "error"; - debug: "debug"; - info: "info"; - notice: "notice"; - warning: "warning"; - critical: "critical"; - alert: "alert"; - emergency: "emergency"; - }>; - logger: z.ZodOptional; - data: z.ZodUnknown; -}, z.core.$loose>; -/** - * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. - */ -export declare const LoggingMessageNotificationSchema: z.ZodObject<{ - method: z.ZodLiteral<"notifications/message">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - level: z.ZodEnum<{ - error: "error"; - debug: "debug"; - info: "info"; - notice: "notice"; - warning: "warning"; - critical: "critical"; - alert: "alert"; - emergency: "emergency"; - }>; - logger: z.ZodOptional; - data: z.ZodUnknown; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * Hints to use for model selection. - */ -export declare const ModelHintSchema: z.ZodObject<{ - name: z.ZodOptional; -}, z.core.$strip>; -/** - * The server's preferences for model selection, requested of the client during sampling. - */ -export declare const ModelPreferencesSchema: z.ZodObject<{ - hints: z.ZodOptional; - }, z.core.$strip>>>; - costPriority: z.ZodOptional; - speedPriority: z.ZodOptional; - intelligencePriority: z.ZodOptional; -}, z.core.$strip>; -/** - * Controls tool usage behavior in sampling requests. - */ -export declare const ToolChoiceSchema: z.ZodObject<{ - mode: z.ZodOptional>; -}, z.core.$strip>; -/** - * The result of a tool execution, provided by the user (server). - * Represents the outcome of invoking a tool requested via ToolUseContent. - */ -export declare const ToolResultContentSchema: z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; -}, z.core.$loose>; -/** - * Content block types allowed in sampling messages. - * This includes text, image, audio, tool use requests, and tool results. - */ -export declare const SamplingMessageContentBlockSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ - type: z.ZodLiteral<"text">; - text: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; -}, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; -}, z.core.$loose>]>; -/** - * Describes a message issued to or received from an LLM API. - */ -export declare const SamplingMessageSchema: z.ZodObject<{ - role: z.ZodEnum<{ - user: "user"; - assistant: "assistant"; - }>; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>, z.ZodArray; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>>]>; - _meta: z.ZodOptional>; -}, z.core.$loose>; -/** - * Parameters for a `sampling/createMessage` request. - */ -export declare const CreateMessageRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - messages: z.ZodArray; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>, z.ZodArray; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>>]>; - _meta: z.ZodOptional>; - }, z.core.$loose>>; - modelPreferences: z.ZodOptional; - }, z.core.$strip>>>; - costPriority: z.ZodOptional; - speedPriority: z.ZodOptional; - intelligencePriority: z.ZodOptional; - }, z.core.$strip>>; - systemPrompt: z.ZodOptional; - includeContext: z.ZodOptional>; - temperature: z.ZodOptional; - maxTokens: z.ZodNumber; - stopSequences: z.ZodOptional>; - metadata: z.ZodOptional>; - tools: z.ZodOptional; - inputSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>; - outputSchema: z.ZodOptional; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>>; - annotations: z.ZodOptional; - readOnlyHint: z.ZodOptional; - destructiveHint: z.ZodOptional; - idempotentHint: z.ZodOptional; - openWorldHint: z.ZodOptional; - }, z.core.$strip>>; - securitySchemes: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; - }, z.core.$strip>]>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>>; - toolChoice: z.ZodOptional>; - }, z.core.$strip>>; -}, z.core.$loose>; -/** - * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. - */ -export declare const CreateMessageRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"sampling/createMessage">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - messages: z.ZodArray; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>, z.ZodArray; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>>]>; - _meta: z.ZodOptional>; - }, z.core.$loose>>; - modelPreferences: z.ZodOptional; - }, z.core.$strip>>>; - costPriority: z.ZodOptional; - speedPriority: z.ZodOptional; - intelligencePriority: z.ZodOptional; - }, z.core.$strip>>; - systemPrompt: z.ZodOptional; - includeContext: z.ZodOptional>; - temperature: z.ZodOptional; - maxTokens: z.ZodNumber; - stopSequences: z.ZodOptional>; - metadata: z.ZodOptional>; - tools: z.ZodOptional; - inputSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>; - outputSchema: z.ZodOptional; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>>; - annotations: z.ZodOptional; - readOnlyHint: z.ZodOptional; - destructiveHint: z.ZodOptional; - idempotentHint: z.ZodOptional; - openWorldHint: z.ZodOptional; - }, z.core.$strip>>; - securitySchemes: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; - }, z.core.$strip>]>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>>; - toolChoice: z.ZodOptional>; - }, z.core.$strip>>; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. - */ -export declare const CreateMessageResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - model: z.ZodString; - stopReason: z.ZodOptional, z.ZodString]>>; - role: z.ZodEnum<{ - user: "user"; - assistant: "assistant"; - }>; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>, z.ZodArray; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>>]>; -}, z.core.$loose>; -/** - * Primitive schema definition for boolean fields. - */ -export declare const BooleanSchemaSchema: z.ZodObject<{ - type: z.ZodLiteral<"boolean">; - title: z.ZodOptional; - description: z.ZodOptional; - default: z.ZodOptional; -}, z.core.$strip>; -/** - * Primitive schema definition for string fields. - */ -export declare const StringSchemaSchema: z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - minLength: z.ZodOptional; - maxLength: z.ZodOptional; - format: z.ZodOptional>; - default: z.ZodOptional; -}, z.core.$strip>; -/** - * Primitive schema definition for number fields. - */ -export declare const NumberSchemaSchema: z.ZodObject<{ - type: z.ZodEnum<{ - number: "number"; - integer: "integer"; - }>; - title: z.ZodOptional; - description: z.ZodOptional; - minimum: z.ZodOptional; - maximum: z.ZodOptional; - default: z.ZodOptional; -}, z.core.$strip>; -/** - * Schema for single-selection enumeration without display titles for options. - */ -export declare const UntitledSingleSelectEnumSchemaSchema: z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; -}, z.core.$strip>; -/** - * Schema for single-selection enumeration with display titles for each option. - */ -export declare const TitledSingleSelectEnumSchemaSchema: z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; -}, z.core.$strip>; -/** - * Use TitledSingleSelectEnumSchema instead. - * This interface will be removed in a future version. - */ -export declare const LegacyTitledEnumSchemaSchema: z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - enumNames: z.ZodOptional>; - default: z.ZodOptional; -}, z.core.$strip>; -export declare const SingleSelectEnumSchemaSchema: z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; -}, z.core.$strip>]>; -/** - * Schema for multiple-selection enumeration without display titles for options. - */ -export declare const UntitledMultiSelectEnumSchemaSchema: z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>; -/** - * Schema for multiple-selection enumeration with display titles for each option. - */ -export declare const TitledMultiSelectEnumSchemaSchema: z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>; -/** - * Combined schema for multiple-selection enumeration - */ -export declare const MultiSelectEnumSchemaSchema: z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>]>; -/** - * Primitive schema definition for enum fields. - */ -export declare const EnumSchemaSchema: z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - enumNames: z.ZodOptional>; - default: z.ZodOptional; -}, z.core.$strip>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; -}, z.core.$strip>]>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>]>]>; -/** - * Union of all primitive schema definitions. - */ -export declare const PrimitiveSchemaDefinitionSchema: z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - enumNames: z.ZodOptional>; - default: z.ZodOptional; -}, z.core.$strip>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; -}, z.core.$strip>]>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>]>]>, z.ZodObject<{ - type: z.ZodLiteral<"boolean">; - title: z.ZodOptional; - description: z.ZodOptional; - default: z.ZodOptional; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - minLength: z.ZodOptional; - maxLength: z.ZodOptional; - format: z.ZodOptional>; - default: z.ZodOptional; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodEnum<{ - number: "number"; - integer: "integer"; - }>; - title: z.ZodOptional; - description: z.ZodOptional; - minimum: z.ZodOptional; - maximum: z.ZodOptional; - default: z.ZodOptional; -}, z.core.$strip>]>; -/** - * Parameters for an `elicitation/create` request for form-based elicitation. - */ -export declare const ElicitRequestFormParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"form">; - message: z.ZodString; - requestedSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodRecord; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - enumNames: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; - }, z.core.$strip>]>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>]>]>, z.ZodObject<{ - type: z.ZodLiteral<"boolean">; - title: z.ZodOptional; - description: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - minLength: z.ZodOptional; - maxLength: z.ZodOptional; - format: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodEnum<{ - number: "number"; - integer: "integer"; - }>; - title: z.ZodOptional; - description: z.ZodOptional; - minimum: z.ZodOptional; - maximum: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>]>>; - required: z.ZodOptional>; - }, z.core.$strip>; -}, z.core.$loose>; -/** - * Parameters for an `elicitation/create` request for URL-based elicitation. - */ -export declare const ElicitRequestURLParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"url">; - message: z.ZodString; - elicitationId: z.ZodString; - url: z.ZodString; -}, z.core.$loose>; -/** - * The parameters for a request to elicit additional information from the user via the client. - */ -export declare const ElicitRequestParamsSchema: z.ZodUnion>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"form">; - message: z.ZodString; - requestedSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodRecord; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - enumNames: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; - }, z.core.$strip>]>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>]>]>, z.ZodObject<{ - type: z.ZodLiteral<"boolean">; - title: z.ZodOptional; - description: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - minLength: z.ZodOptional; - maxLength: z.ZodOptional; - format: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodEnum<{ - number: "number"; - integer: "integer"; - }>; - title: z.ZodOptional; - description: z.ZodOptional; - minimum: z.ZodOptional; - maximum: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>]>>; - required: z.ZodOptional>; - }, z.core.$strip>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"url">; - message: z.ZodString; - elicitationId: z.ZodString; - url: z.ZodString; -}, z.core.$loose>]>; -/** - * A request from the server to elicit user input via the client. - * The client should present the message and form fields to the user (form mode) - * or navigate to a URL (URL mode). - */ -export declare const ElicitRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"elicitation/create">; - params: z.ZodUnion>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"form">; - message: z.ZodString; - requestedSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodRecord; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - enumNames: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; - }, z.core.$strip>]>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>]>]>, z.ZodObject<{ - type: z.ZodLiteral<"boolean">; - title: z.ZodOptional; - description: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - minLength: z.ZodOptional; - maxLength: z.ZodOptional; - format: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodEnum<{ - number: "number"; - integer: "integer"; - }>; - title: z.ZodOptional; - description: z.ZodOptional; - minimum: z.ZodOptional; - maximum: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>]>>; - required: z.ZodOptional>; - }, z.core.$strip>; - }, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"url">; - message: z.ZodString; - elicitationId: z.ZodString; - url: z.ZodString; - }, z.core.$loose>]>; -}, z.core.$strip>; -/** - * Parameters for a `notifications/elicitation/complete` notification. - * - * @category notifications/elicitation/complete - */ -export declare const ElicitationCompleteNotificationParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - elicitationId: z.ZodString; -}, z.core.$loose>; -/** - * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. - * - * @category notifications/elicitation/complete - */ -export declare const ElicitationCompleteNotificationSchema: z.ZodObject<{ - method: z.ZodLiteral<"notifications/elicitation/complete">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - elicitationId: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * The client's response to an elicitation/create request from the server. - */ -export declare const ElicitResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - action: z.ZodEnum<{ - accept: "accept"; - decline: "decline"; - cancel: "cancel"; - }>; - content: z.ZodOptional]>>>; -}, z.core.$loose>; -/** - * A reference to a resource or resource template definition. - */ -export declare const ResourceTemplateReferenceSchema: z.ZodObject<{ - type: z.ZodLiteral<"ref/resource">; - uri: z.ZodString; -}, z.core.$strip>; -/** - * @deprecated Use ResourceTemplateReferenceSchema instead - */ -export declare const ResourceReferenceSchema: z.ZodObject<{ - type: z.ZodLiteral<"ref/resource">; - uri: z.ZodString; -}, z.core.$strip>; -/** - * Identifies a prompt. - */ -export declare const PromptReferenceSchema: z.ZodObject<{ - type: z.ZodLiteral<"ref/prompt">; - name: z.ZodString; -}, z.core.$strip>; -/** - * Parameters for a `completion/complete` request. - */ -export declare const CompleteRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - ref: z.ZodUnion; - name: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"ref/resource">; - uri: z.ZodString; - }, z.core.$strip>]>; - argument: z.ZodObject<{ - name: z.ZodString; - value: z.ZodString; - }, z.core.$strip>; - context: z.ZodOptional>; - }, z.core.$strip>>; -}, z.core.$loose>; -/** - * A request from the client to the server, to ask for completion options. - */ -export declare const CompleteRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"completion/complete">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - ref: z.ZodUnion; - name: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"ref/resource">; - uri: z.ZodString; - }, z.core.$strip>]>; - argument: z.ZodObject<{ - name: z.ZodString; - value: z.ZodString; - }, z.core.$strip>; - context: z.ZodOptional>; - }, z.core.$strip>>; - }, z.core.$loose>; -}, z.core.$strip>; -export declare function assertCompleteRequestPrompt(request: CompleteRequest): asserts request is CompleteRequestPrompt; -export declare function assertCompleteRequestResourceTemplate(request: CompleteRequest): asserts request is CompleteRequestResourceTemplate; -/** - * The server's response to a completion/complete request - */ -export declare const CompleteResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - completion: z.ZodObject<{ - /** - * An array of completion values. Must not exceed 100 items. - */ - values: z.ZodArray; - /** - * The total number of completion options available. This can exceed the number of values actually sent in the response. - */ - total: z.ZodOptional; - /** - * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. - */ - hasMore: z.ZodOptional; - }, z.core.$loose>; -}, z.core.$loose>; -/** - * Represents a root directory or file that the server can operate on. - */ -export declare const RootSchema: z.ZodObject<{ - uri: z.ZodString; - name: z.ZodOptional; - _meta: z.ZodOptional>; -}, z.core.$strip>; -/** - * Sent from the server to request a list of root URIs from the client. - */ -export declare const ListRootsRequestSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - }, z.core.$loose>>; - method: z.ZodLiteral<"roots/list">; -}, z.core.$strip>; -/** - * The client's response to a roots/list request from the server. - */ -export declare const ListRootsResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - roots: z.ZodArray; - _meta: z.ZodOptional>; - }, z.core.$strip>>; -}, z.core.$loose>; -/** - * A notification from the client to the server, informing it that the list of roots has changed. - */ -export declare const RootsListChangedNotificationSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/roots/list_changed">; -}, z.core.$strip>; -export declare const ClientRequestSchema: z.ZodUnion>; - }, z.core.$loose>>; - }, z.core.$loose>>; - method: z.ZodLiteral<"ping">; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"initialize">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - protocolVersion: z.ZodString; - capabilities: z.ZodObject<{ - experimental: z.ZodOptional>>; - sampling: z.ZodOptional>; - tools: z.ZodOptional>; - }, z.core.$strip>>; - elicitation: z.ZodOptional, z.ZodIntersection; - }, z.core.$strip>, z.ZodRecord>>; - url: z.ZodOptional>; - }, z.core.$strip>, z.ZodOptional>>>>; - roots: z.ZodOptional; - }, z.core.$strip>>; - }, z.core.$strip>; - clientInfo: z.ZodObject<{ - version: z.ZodString; - websiteUrl: z.ZodOptional; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"completion/complete">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - ref: z.ZodUnion; - name: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"ref/resource">; - uri: z.ZodString; - }, z.core.$strip>]>; - argument: z.ZodObject<{ - name: z.ZodString; - value: z.ZodString; - }, z.core.$strip>; - context: z.ZodOptional>; - }, z.core.$strip>>; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"logging/setLevel">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - level: z.ZodEnum<{ - error: "error"; - debug: "debug"; - info: "info"; - notice: "notice"; - warning: "warning"; - critical: "critical"; - alert: "alert"; - emergency: "emergency"; - }>; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"prompts/get">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - name: z.ZodString; - arguments: z.ZodOptional>; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"prompts/list">; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"resources/list">; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"resources/templates/list">; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"resources/read">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"resources/subscribe">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"resources/unsubscribe">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"tools/call">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - name: z.ZodString; - arguments: z.ZodOptional>; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"tools/list">; -}, z.core.$strip>]>; -export declare const ClientNotificationSchema: z.ZodUnion; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - requestId: z.ZodUnion; - reason: z.ZodOptional; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"notifications/progress">; - params: z.ZodObject<{ - progressToken: z.ZodUnion; - progress: z.ZodNumber; - total: z.ZodOptional; - message: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$strip>; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/initialized">; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/roots/list_changed">; -}, z.core.$strip>]>; -export declare const ClientResultSchema: z.ZodUnion>; -}, z.core.$strict>, z.ZodObject<{ - _meta: z.ZodOptional>; - model: z.ZodString; - stopReason: z.ZodOptional, z.ZodString]>>; - role: z.ZodEnum<{ - user: "user"; - assistant: "assistant"; - }>; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>, z.ZodArray; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>>]>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - action: z.ZodEnum<{ - accept: "accept"; - decline: "decline"; - cancel: "cancel"; - }>; - content: z.ZodOptional]>>>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - roots: z.ZodArray; - _meta: z.ZodOptional>; - }, z.core.$strip>>; -}, z.core.$loose>]>; -export declare const ServerRequestSchema: z.ZodUnion>; - }, z.core.$loose>>; - }, z.core.$loose>>; - method: z.ZodLiteral<"ping">; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"sampling/createMessage">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - messages: z.ZodArray; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>, z.ZodArray; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>>]>; - _meta: z.ZodOptional>; - }, z.core.$loose>>; - modelPreferences: z.ZodOptional; - }, z.core.$strip>>>; - costPriority: z.ZodOptional; - speedPriority: z.ZodOptional; - intelligencePriority: z.ZodOptional; - }, z.core.$strip>>; - systemPrompt: z.ZodOptional; - includeContext: z.ZodOptional>; - temperature: z.ZodOptional; - maxTokens: z.ZodNumber; - stopSequences: z.ZodOptional>; - metadata: z.ZodOptional>; - tools: z.ZodOptional; - inputSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>; - outputSchema: z.ZodOptional; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>>; - annotations: z.ZodOptional; - readOnlyHint: z.ZodOptional; - destructiveHint: z.ZodOptional; - idempotentHint: z.ZodOptional; - openWorldHint: z.ZodOptional; - }, z.core.$strip>>; - securitySchemes: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; - }, z.core.$strip>]>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>>; - toolChoice: z.ZodOptional>; - }, z.core.$strip>>; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"elicitation/create">; - params: z.ZodUnion>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"form">; - message: z.ZodString; - requestedSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodRecord; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - enumNames: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; - }, z.core.$strip>]>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>]>]>, z.ZodObject<{ - type: z.ZodLiteral<"boolean">; - title: z.ZodOptional; - description: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - minLength: z.ZodOptional; - maxLength: z.ZodOptional; - format: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodEnum<{ - number: "number"; - integer: "integer"; - }>; - title: z.ZodOptional; - description: z.ZodOptional; - minimum: z.ZodOptional; - maximum: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>]>>; - required: z.ZodOptional>; - }, z.core.$strip>; - }, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"url">; - message: z.ZodString; - elicitationId: z.ZodString; - url: z.ZodString; - }, z.core.$loose>]>; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - }, z.core.$loose>>; - method: z.ZodLiteral<"roots/list">; -}, z.core.$strip>]>; -export declare const ServerNotificationSchema: z.ZodUnion; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - requestId: z.ZodUnion; - reason: z.ZodOptional; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"notifications/progress">; - params: z.ZodObject<{ - progressToken: z.ZodUnion; - progress: z.ZodNumber; - total: z.ZodOptional; - message: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$strip>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"notifications/message">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - level: z.ZodEnum<{ - error: "error"; - debug: "debug"; - info: "info"; - notice: "notice"; - warning: "warning"; - critical: "critical"; - alert: "alert"; - emergency: "emergency"; - }>; - logger: z.ZodOptional; - data: z.ZodUnknown; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"notifications/resources/updated">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/resources/list_changed">; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/tools/list_changed">; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/prompts/list_changed">; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"notifications/elicitation/complete">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - elicitationId: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>]>; -export declare const ServerResultSchema: z.ZodUnion>; -}, z.core.$strict>, z.ZodObject<{ - _meta: z.ZodOptional>; - protocolVersion: z.ZodString; - capabilities: z.ZodObject<{ - experimental: z.ZodOptional>>; - logging: z.ZodOptional>; - completions: z.ZodOptional>; - prompts: z.ZodOptional; - }, z.core.$strip>>; - resources: z.ZodOptional; - listChanged: z.ZodOptional; - }, z.core.$strip>>; - tools: z.ZodOptional; - }, z.core.$strip>>; - }, z.core.$strip>; - serverInfo: z.ZodObject<{ - version: z.ZodString; - websiteUrl: z.ZodOptional; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>; - instructions: z.ZodOptional; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - completion: z.ZodObject<{ - /** - * An array of completion values. Must not exceed 100 items. - */ - values: z.ZodArray; - /** - * The total number of completion options available. This can exceed the number of values actually sent in the response. - */ - total: z.ZodOptional; - /** - * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. - */ - hasMore: z.ZodOptional; - }, z.core.$loose>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - description: z.ZodOptional; - messages: z.ZodArray; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>; - }, z.core.$strip>>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - prompts: z.ZodArray; - arguments: z.ZodOptional; - required: z.ZodOptional; - }, z.core.$strip>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - resources: z.ZodArray; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - resourceTemplates: z.ZodArray; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - contents: z.ZodArray; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - tools: z.ZodArray; - inputSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>; - outputSchema: z.ZodOptional; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>>; - annotations: z.ZodOptional; - readOnlyHint: z.ZodOptional; - destructiveHint: z.ZodOptional; - idempotentHint: z.ZodOptional; - openWorldHint: z.ZodOptional; - }, z.core.$strip>>; - securitySchemes: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; - }, z.core.$strip>]>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>]>; -export declare class McpError extends Error { - readonly code: number; - readonly data?: unknown; - constructor(code: number, message: string, data?: unknown); - /** - * Factory method to create the appropriate error type based on the error code and data - */ - static fromError(code: number, message: string, data?: unknown): McpError; -} -/** - * Specialized error type when a tool requires a URL mode elicitation. - * 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. - */ -export declare class UrlElicitationRequiredError extends McpError { - constructor(elicitations: ElicitRequestURLParams[], message?: string); - get elicitations(): ElicitRequestURLParams[]; -} -type Primitive = string | number | boolean | bigint | null | undefined; -type Flatten = T extends Primitive ? T : T extends Array ? Array> : T extends Set ? Set> : T extends Map ? Map, Flatten> : T extends object ? { - [K in keyof T]: Flatten; -} : T; -type Infer = Flatten>; -/** - * Headers that are compatible with both Node.js and the browser. - */ -export type IsomorphicHeaders = Record; -/** - * Information about the incoming request. - */ -export interface RequestInfo { - /** - * The headers of the request. - */ - headers: IsomorphicHeaders; -} -/** - * Extra information about a message. - */ -export interface MessageExtraInfo { - /** - * The request information. - */ - requestInfo?: RequestInfo; - /** - * The authentication information. - */ - authInfo?: AuthInfo; -} -export type ProgressToken = Infer; -export type Cursor = Infer; -export type Request = Infer; -export type RequestMeta = Infer; -export type Notification = Infer; -export type Result = Infer; -export type RequestId = Infer; -export type JSONRPCRequest = Infer; -export type JSONRPCNotification = Infer; -export type JSONRPCResponse = Infer; -export type JSONRPCError = Infer; -export type JSONRPCMessage = Infer; -export type RequestParams = Infer; -export type NotificationParams = Infer; -export type EmptyResult = Infer; -export type CancelledNotificationParams = Infer; -export type CancelledNotification = Infer; -export type Icon = Infer; -export type Icons = Infer; -export type BaseMetadata = Infer; -export type Implementation = Infer; -export type ClientCapabilities = Infer; -export type InitializeRequestParams = Infer; -export type InitializeRequest = Infer; -export type ServerCapabilities = Infer; -export type InitializeResult = Infer; -export type InitializedNotification = Infer; -export type PingRequest = Infer; -export type Progress = Infer; -export type ProgressNotificationParams = Infer; -export type ProgressNotification = Infer; -export type PaginatedRequestParams = Infer; -export type PaginatedRequest = Infer; -export type PaginatedResult = Infer; -export type ResourceContents = Infer; -export type TextResourceContents = Infer; -export type BlobResourceContents = Infer; -export type Resource = Infer; -export type ResourceTemplate = Infer; -export type ListResourcesRequest = Infer; -export type ListResourcesResult = Infer; -export type ListResourceTemplatesRequest = Infer; -export type ListResourceTemplatesResult = Infer; -export type ResourceRequestParams = Infer; -export type ReadResourceRequestParams = Infer; -export type ReadResourceRequest = Infer; -export type ReadResourceResult = Infer; -export type ResourceListChangedNotification = Infer; -export type SubscribeRequestParams = Infer; -export type SubscribeRequest = Infer; -export type UnsubscribeRequestParams = Infer; -export type UnsubscribeRequest = Infer; -export type ResourceUpdatedNotificationParams = Infer; -export type ResourceUpdatedNotification = Infer; -export type PromptArgument = Infer; -export type Prompt = Infer; -export type ListPromptsRequest = Infer; -export type ListPromptsResult = Infer; -export type GetPromptRequestParams = Infer; -export type GetPromptRequest = Infer; -export type TextContent = Infer; -export type ImageContent = Infer; -export type AudioContent = Infer; -export type ToolUseContent = Infer; -export type ToolResultContent = Infer; -export type EmbeddedResource = Infer; -export type ResourceLink = Infer; -export type ContentBlock = Infer; -export type PromptMessage = Infer; -export type GetPromptResult = Infer; -export type PromptListChangedNotification = Infer; -export type NoAuthSecurityScheme = Infer; -export type OAuth2SecurityScheme = Infer; -export type SecurityScheme = Infer; -export type ToolAnnotations = Infer; -export type Tool = Infer; -export type ListToolsRequest = Infer; -export type ListToolsResult = Infer; -export type CallToolRequestParams = Infer; -export type CallToolResult = Infer; -export type CompatibilityCallToolResult = Infer; -export type CallToolRequest = Infer; -export type ToolListChangedNotification = Infer; -export type LoggingLevel = Infer; -export type SetLevelRequestParams = Infer; -export type SetLevelRequest = Infer; -export type LoggingMessageNotificationParams = Infer; -export type LoggingMessageNotification = Infer; -export type ToolChoice = Infer; -export type ModelHint = Infer; -export type ModelPreferences = Infer; -export type SamplingMessageContentBlock = Infer; -export type SamplingMessage = Infer; -export type CreateMessageRequestParams = Infer; -export type CreateMessageRequest = Infer; -export type CreateMessageResult = Infer; -export type BooleanSchema = Infer; -export type StringSchema = Infer; -export type NumberSchema = Infer; -export type EnumSchema = Infer; -export type UntitledSingleSelectEnumSchema = Infer; -export type TitledSingleSelectEnumSchema = Infer; -export type LegacyTitledEnumSchema = Infer; -export type UntitledMultiSelectEnumSchema = Infer; -export type TitledMultiSelectEnumSchema = Infer; -export type SingleSelectEnumSchema = Infer; -export type MultiSelectEnumSchema = Infer; -export type PrimitiveSchemaDefinition = Infer; -export type ElicitRequestParams = Infer; -export type ElicitRequestFormParams = Infer; -export type ElicitRequestURLParams = Infer; -export type ElicitRequest = Infer; -export type ElicitationCompleteNotificationParams = Infer; -export type ElicitationCompleteNotification = Infer; -export type ElicitResult = Infer; -export type ResourceTemplateReference = Infer; -/** - * @deprecated Use ResourceTemplateReference instead - */ -export type ResourceReference = ResourceTemplateReference; -export type PromptReference = Infer; -export type CompleteRequestParams = Infer; -export type CompleteRequest = Infer; -export type CompleteRequestResourceTemplate = ExpandRecursively; -export type CompleteRequestPrompt = ExpandRecursively; -export type CompleteResult = Infer; -export type Root = Infer; -export type ListRootsRequest = Infer; -export type ListRootsResult = Infer; -export type RootsListChangedNotification = Infer; -export type ClientRequest = Infer; -export type ClientNotification = Infer; -export type ClientResult = Infer; -export type ServerRequest = Infer; -export type ServerNotification = Infer; -export type ServerResult = Infer; -export {}; -//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/cjs/types.d.ts.map b/dist/cjs/types.d.ts.map deleted file mode 100644 index 39761f83d0..0000000000 --- a/dist/cjs/types.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAElD,eAAO,MAAM,uBAAuB,eAAe,CAAC;AACpD,eAAO,MAAM,mCAAmC,eAAe,CAAC;AAChE,eAAO,MAAM,2BAA2B,UAAsE,CAAC;AAG/G,eAAO,MAAM,eAAe,QAAQ,CAAC;AAErC;;GAEG;AACH,KAAK,iBAAiB,CAAC,CAAC,IAAI,CAAC,SAAS,MAAM,GAAG,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,iBAAiB,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AAe,GAAG,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAClE,MAAM,MAAM,4BAA4B,GAAG,KAAK,CAAC,OAAO,kCAAkC,CAAC,CAAC;AAG5F,MAAM,MAAM,aAAa,GAAG,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAC9D,MAAM,MAAM,kBAAkB,GAAG,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;AACxE,MAAM,MAAM,YAAY,GAAG,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAG5D,MAAM,MAAM,aAAa,GAAG,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAC9D,MAAM,MAAM,kBAAkB,GAAG,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;AACxE,MAAM,MAAM,YAAY,GAAG,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/cjs/types.js b/dist/cjs/types.js deleted file mode 100644 index b269cc3a84..0000000000 --- a/dist/cjs/types.js +++ /dev/null @@ -1,1697 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ListResourceTemplatesRequestSchema = exports.ListResourcesResultSchema = exports.ListResourcesRequestSchema = exports.ResourceTemplateSchema = exports.ResourceSchema = exports.BlobResourceContentsSchema = exports.TextResourceContentsSchema = exports.ResourceContentsSchema = exports.PaginatedResultSchema = exports.PaginatedRequestSchema = exports.PaginatedRequestParamsSchema = exports.ProgressNotificationSchema = exports.ProgressNotificationParamsSchema = exports.ProgressSchema = exports.PingRequestSchema = exports.isInitializedNotification = exports.InitializedNotificationSchema = exports.InitializeResultSchema = exports.ServerCapabilitiesSchema = exports.isInitializeRequest = exports.InitializeRequestSchema = exports.InitializeRequestParamsSchema = exports.ClientCapabilitiesSchema = exports.ImplementationSchema = exports.BaseMetadataSchema = exports.IconsSchema = exports.IconSchema = exports.CancelledNotificationSchema = exports.CancelledNotificationParamsSchema = exports.EmptyResultSchema = exports.JSONRPCMessageSchema = exports.isJSONRPCError = exports.JSONRPCErrorSchema = exports.ErrorCode = exports.isJSONRPCResponse = exports.JSONRPCResponseSchema = exports.isJSONRPCNotification = exports.JSONRPCNotificationSchema = exports.isJSONRPCRequest = exports.JSONRPCRequestSchema = exports.RequestIdSchema = exports.ResultSchema = exports.NotificationSchema = exports.RequestSchema = exports.CursorSchema = exports.ProgressTokenSchema = exports.JSONRPC_VERSION = exports.SUPPORTED_PROTOCOL_VERSIONS = exports.DEFAULT_NEGOTIATED_PROTOCOL_VERSION = exports.LATEST_PROTOCOL_VERSION = void 0; -exports.SamplingMessageContentBlockSchema = exports.ToolResultContentSchema = exports.ToolChoiceSchema = exports.ModelPreferencesSchema = exports.ModelHintSchema = exports.LoggingMessageNotificationSchema = exports.LoggingMessageNotificationParamsSchema = exports.SetLevelRequestSchema = exports.SetLevelRequestParamsSchema = exports.LoggingLevelSchema = exports.ToolListChangedNotificationSchema = exports.CallToolRequestSchema = exports.CallToolRequestParamsSchema = exports.CompatibilityCallToolResultSchema = exports.CallToolResultSchema = exports.ListToolsResultSchema = exports.ListToolsRequestSchema = exports.ToolSchema = exports.ToolAnnotationsSchema = exports.SecuritySchemeSchema = exports.OAuth2SecuritySchemeSchema = exports.NoAuthSecuritySchemeSchema = exports.PromptListChangedNotificationSchema = exports.GetPromptResultSchema = exports.PromptMessageSchema = exports.ContentBlockSchema = exports.ResourceLinkSchema = exports.EmbeddedResourceSchema = exports.ToolUseContentSchema = exports.AudioContentSchema = exports.ImageContentSchema = exports.TextContentSchema = exports.GetPromptRequestSchema = exports.GetPromptRequestParamsSchema = exports.ListPromptsResultSchema = exports.ListPromptsRequestSchema = exports.PromptSchema = exports.PromptArgumentSchema = exports.ResourceUpdatedNotificationSchema = exports.ResourceUpdatedNotificationParamsSchema = exports.UnsubscribeRequestSchema = exports.UnsubscribeRequestParamsSchema = exports.SubscribeRequestSchema = exports.SubscribeRequestParamsSchema = exports.ResourceListChangedNotificationSchema = exports.ReadResourceResultSchema = exports.ReadResourceRequestSchema = exports.ReadResourceRequestParamsSchema = exports.ResourceRequestParamsSchema = exports.ListResourceTemplatesResultSchema = void 0; -exports.UrlElicitationRequiredError = exports.McpError = exports.ServerResultSchema = exports.ServerNotificationSchema = exports.ServerRequestSchema = exports.ClientResultSchema = exports.ClientNotificationSchema = exports.ClientRequestSchema = exports.RootsListChangedNotificationSchema = exports.ListRootsResultSchema = exports.ListRootsRequestSchema = exports.RootSchema = exports.CompleteResultSchema = exports.CompleteRequestSchema = exports.CompleteRequestParamsSchema = exports.PromptReferenceSchema = exports.ResourceReferenceSchema = exports.ResourceTemplateReferenceSchema = exports.ElicitResultSchema = exports.ElicitationCompleteNotificationSchema = exports.ElicitationCompleteNotificationParamsSchema = exports.ElicitRequestSchema = exports.ElicitRequestParamsSchema = exports.ElicitRequestURLParamsSchema = exports.ElicitRequestFormParamsSchema = exports.PrimitiveSchemaDefinitionSchema = exports.EnumSchemaSchema = exports.MultiSelectEnumSchemaSchema = exports.TitledMultiSelectEnumSchemaSchema = exports.UntitledMultiSelectEnumSchemaSchema = exports.SingleSelectEnumSchemaSchema = exports.LegacyTitledEnumSchemaSchema = exports.TitledSingleSelectEnumSchemaSchema = exports.UntitledSingleSelectEnumSchemaSchema = exports.NumberSchemaSchema = exports.StringSchemaSchema = exports.BooleanSchemaSchema = exports.CreateMessageResultSchema = exports.CreateMessageRequestSchema = exports.CreateMessageRequestParamsSchema = exports.SamplingMessageSchema = void 0; -exports.assertCompleteRequestPrompt = assertCompleteRequestPrompt; -exports.assertCompleteRequestResourceTemplate = assertCompleteRequestResourceTemplate; -const z = __importStar(require("zod/v4")); -exports.LATEST_PROTOCOL_VERSION = '2025-06-18'; -exports.DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26'; -exports.SUPPORTED_PROTOCOL_VERSIONS = [exports.LATEST_PROTOCOL_VERSION, '2025-03-26', '2024-11-05', '2024-10-07']; -/* JSON-RPC types */ -exports.JSONRPC_VERSION = '2.0'; -/** - * Assert 'object' type schema. - * - * @internal - */ -const AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function')); -/** - * A progress token, used to associate progress notifications with the original request. - */ -exports.ProgressTokenSchema = z.union([z.string(), z.number().int()]); -/** - * An opaque token used to represent a cursor for pagination. - */ -exports.CursorSchema = z.string(); -const RequestMetaSchema = z.looseObject({ - /** - * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. - */ - progressToken: exports.ProgressTokenSchema.optional() -}); -/** - * Common params for any request. - */ -const BaseRequestParamsSchema = z.looseObject({ - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta: RequestMetaSchema.optional() -}); -exports.RequestSchema = z.object({ - method: z.string(), - params: BaseRequestParamsSchema.optional() -}); -const NotificationsParamsSchema = z.looseObject({ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -exports.NotificationSchema = z.object({ - method: z.string(), - params: NotificationsParamsSchema.optional() -}); -exports.ResultSchema = z.looseObject({ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * A uniquely identifying ID for a request in JSON-RPC. - */ -exports.RequestIdSchema = z.union([z.string(), z.number().int()]); -/** - * A request that expects a response. - */ -exports.JSONRPCRequestSchema = z - .object({ - jsonrpc: z.literal(exports.JSONRPC_VERSION), - id: exports.RequestIdSchema, - ...exports.RequestSchema.shape -}) - .strict(); -const isJSONRPCRequest = (value) => exports.JSONRPCRequestSchema.safeParse(value).success; -exports.isJSONRPCRequest = isJSONRPCRequest; -/** - * A notification which does not expect a response. - */ -exports.JSONRPCNotificationSchema = z - .object({ - jsonrpc: z.literal(exports.JSONRPC_VERSION), - ...exports.NotificationSchema.shape -}) - .strict(); -const isJSONRPCNotification = (value) => exports.JSONRPCNotificationSchema.safeParse(value).success; -exports.isJSONRPCNotification = isJSONRPCNotification; -/** - * A successful (non-error) response to a request. - */ -exports.JSONRPCResponseSchema = z - .object({ - jsonrpc: z.literal(exports.JSONRPC_VERSION), - id: exports.RequestIdSchema, - result: exports.ResultSchema -}) - .strict(); -const isJSONRPCResponse = (value) => exports.JSONRPCResponseSchema.safeParse(value).success; -exports.isJSONRPCResponse = isJSONRPCResponse; -/** - * Error codes defined by the JSON-RPC specification. - */ -var ErrorCode; -(function (ErrorCode) { - // SDK error codes - ErrorCode[ErrorCode["ConnectionClosed"] = -32000] = "ConnectionClosed"; - ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout"; - // Standard JSON-RPC error codes - ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError"; - ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest"; - ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound"; - ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams"; - ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError"; - // MCP-specific error codes - ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; -})(ErrorCode || (exports.ErrorCode = ErrorCode = {})); -/** - * A response to a request that indicates an error occurred. - */ -exports.JSONRPCErrorSchema = z - .object({ - jsonrpc: z.literal(exports.JSONRPC_VERSION), - id: exports.RequestIdSchema, - error: z.object({ - /** - * The error type that occurred. - */ - code: z.number().int(), - /** - * A short description of the error. The message SHOULD be limited to a concise single sentence. - */ - message: z.string(), - /** - * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). - */ - data: z.optional(z.unknown()) - }) -}) - .strict(); -const isJSONRPCError = (value) => exports.JSONRPCErrorSchema.safeParse(value).success; -exports.isJSONRPCError = isJSONRPCError; -exports.JSONRPCMessageSchema = z.union([exports.JSONRPCRequestSchema, exports.JSONRPCNotificationSchema, exports.JSONRPCResponseSchema, exports.JSONRPCErrorSchema]); -/* Empty result */ -/** - * A response that indicates success but carries no data. - */ -exports.EmptyResultSchema = exports.ResultSchema.strict(); -exports.CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The ID of the request to cancel. - * - * This MUST correspond to the ID of a request previously issued in the same direction. - */ - requestId: exports.RequestIdSchema, - /** - * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. - */ - reason: z.string().optional() -}); -/* Cancellation */ -/** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its `initialize` request. - */ -exports.CancelledNotificationSchema = exports.NotificationSchema.extend({ - method: z.literal('notifications/cancelled'), - params: exports.CancelledNotificationParamsSchema -}); -/* Base Metadata */ -/** - * Icon schema for use in tools, prompts, resources, and implementations. - */ -exports.IconSchema = z.object({ - /** - * URL or data URI for the icon. - */ - src: z.string(), - /** - * Optional MIME type for the icon. - */ - mimeType: z.string().optional(), - /** - * Optional array of strings that specify sizes at which the icon can be used. - * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. - * - * If not provided, the client should assume that the icon can be used at any size. - */ - sizes: z.array(z.string()).optional() -}); -/** - * Base schema to add `icons` property. - * - */ -exports.IconsSchema = z.object({ - /** - * Optional set of sized icons that the client can display in a user interface. - * - * Clients that support rendering icons MUST support at least the following MIME types: - * - `image/png` - PNG images (safe, universal compatibility) - * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) - * - * Clients that support rendering icons SHOULD also support: - * - `image/svg+xml` - SVG images (scalable but requires security precautions) - * - `image/webp` - WebP images (modern, efficient format) - */ - icons: z.array(exports.IconSchema).optional() -}); -/** - * Base metadata interface for common properties across resources, tools, prompts, and implementations. - */ -exports.BaseMetadataSchema = z.object({ - /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ - name: z.string(), - /** - * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, - * even by those unfamiliar with domain-specific terminology. - * - * If not provided, the name should be used for display (except for Tool, - * where `annotations.title` should be given precedence over using `name`, - * if present). - */ - title: z.string().optional() -}); -/* Initialization */ -/** - * Describes the name and version of an MCP implementation. - */ -exports.ImplementationSchema = exports.BaseMetadataSchema.extend({ - ...exports.BaseMetadataSchema.shape, - ...exports.IconsSchema.shape, - version: z.string(), - /** - * An optional URL of the website for this implementation. - */ - websiteUrl: z.string().optional() -}); -const FormElicitationCapabilitySchema = z.intersection(z.object({ - applyDefaults: z.boolean().optional() -}), z.record(z.string(), z.unknown())); -const ElicitationCapabilitySchema = z.preprocess(value => { - if (value && typeof value === 'object' && !Array.isArray(value)) { - if (Object.keys(value).length === 0) { - return { form: {} }; - } - } - return value; -}, z.intersection(z.object({ - form: FormElicitationCapabilitySchema.optional(), - url: AssertObjectSchema.optional() -}), z.record(z.string(), z.unknown()).optional())); -/** - * 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. - */ -exports.ClientCapabilitiesSchema = z.object({ - /** - * Experimental, non-standard capabilities that the client supports. - */ - experimental: z.record(z.string(), AssertObjectSchema).optional(), - /** - * Present if the client supports sampling from an LLM. - */ - sampling: z - .object({ - /** - * Present if the client supports context inclusion via includeContext parameter. - * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). - */ - context: AssertObjectSchema.optional(), - /** - * Present if the client supports tool use via tools and toolChoice parameters. - */ - tools: AssertObjectSchema.optional() - }) - .optional(), - /** - * Present if the client supports eliciting user input. - */ - elicitation: ElicitationCapabilitySchema.optional(), - /** - * Present if the client supports listing roots. - */ - roots: z - .object({ - /** - * Whether the client supports issuing notifications for changes to the roots list. - */ - listChanged: z.boolean().optional() - }) - .optional() -}); -exports.InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. - */ - protocolVersion: z.string(), - capabilities: exports.ClientCapabilitiesSchema, - clientInfo: exports.ImplementationSchema -}); -/** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - */ -exports.InitializeRequestSchema = exports.RequestSchema.extend({ - method: z.literal('initialize'), - params: exports.InitializeRequestParamsSchema -}); -const isInitializeRequest = (value) => exports.InitializeRequestSchema.safeParse(value).success; -exports.isInitializeRequest = isInitializeRequest; -/** - * 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. - */ -exports.ServerCapabilitiesSchema = z.object({ - /** - * Experimental, non-standard capabilities that the server supports. - */ - experimental: z.record(z.string(), AssertObjectSchema).optional(), - /** - * Present if the server supports sending log messages to the client. - */ - logging: AssertObjectSchema.optional(), - /** - * Present if the server supports sending completions to the client. - */ - completions: AssertObjectSchema.optional(), - /** - * Present if the server offers any prompt templates. - */ - prompts: z.optional(z.object({ - /** - * Whether this server supports issuing notifications for changes to the prompt list. - */ - listChanged: z.optional(z.boolean()) - })), - /** - * Present if the server offers any resources to read. - */ - resources: z - .object({ - /** - * Whether this server supports clients subscribing to resource updates. - */ - subscribe: z.boolean().optional(), - /** - * Whether this server supports issuing notifications for changes to the resource list. - */ - listChanged: z.boolean().optional() - }) - .optional(), - /** - * Present if the server offers any tools to call. - */ - tools: z - .object({ - /** - * Whether this server supports issuing notifications for changes to the tool list. - */ - listChanged: z.boolean().optional() - }) - .optional() -}); -/** - * After receiving an initialize request from the client, the server sends this response. - */ -exports.InitializeResultSchema = exports.ResultSchema.extend({ - /** - * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. - */ - protocolVersion: z.string(), - capabilities: exports.ServerCapabilitiesSchema, - serverInfo: exports.ImplementationSchema, - /** - * Instructions describing how to use the server and its features. - * - * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. - */ - instructions: z.string().optional() -}); -/** - * This notification is sent from the client to the server after initialization has finished. - */ -exports.InitializedNotificationSchema = exports.NotificationSchema.extend({ - method: z.literal('notifications/initialized') -}); -const isInitializedNotification = (value) => exports.InitializedNotificationSchema.safeParse(value).success; -exports.isInitializedNotification = isInitializedNotification; -/* Ping */ -/** - * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. - */ -exports.PingRequestSchema = exports.RequestSchema.extend({ - method: z.literal('ping') -}); -/* Progress notifications */ -exports.ProgressSchema = z.object({ - /** - * The progress thus far. This should increase every time progress is made, even if the total is unknown. - */ - progress: z.number(), - /** - * Total number of items to process (or total progress required), if known. - */ - total: z.optional(z.number()), - /** - * An optional message describing the current progress. - */ - message: z.optional(z.string()) -}); -exports.ProgressNotificationParamsSchema = z.object({ - ...NotificationsParamsSchema.shape, - ...exports.ProgressSchema.shape, - /** - * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. - */ - progressToken: exports.ProgressTokenSchema -}); -/** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - * - * @category notifications/progress - */ -exports.ProgressNotificationSchema = exports.NotificationSchema.extend({ - method: z.literal('notifications/progress'), - params: exports.ProgressNotificationParamsSchema -}); -exports.PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * An opaque token representing the current pagination position. - * If provided, the server should return results starting after this cursor. - */ - cursor: exports.CursorSchema.optional() -}); -/* Pagination */ -exports.PaginatedRequestSchema = exports.RequestSchema.extend({ - params: exports.PaginatedRequestParamsSchema.optional() -}); -exports.PaginatedResultSchema = exports.ResultSchema.extend({ - /** - * An opaque token representing the pagination position after the last returned result. - * If present, there may be more results available. - */ - nextCursor: z.optional(exports.CursorSchema) -}); -/* Resources */ -/** - * The contents of a specific resource or sub-resource. - */ -exports.ResourceContentsSchema = z.object({ - /** - * The URI of this resource. - */ - uri: z.string(), - /** - * The MIME type of this resource, if known. - */ - mimeType: z.optional(z.string()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -exports.TextResourceContentsSchema = exports.ResourceContentsSchema.extend({ - /** - * The text of the item. This must only be set if the item can actually be represented as text (not binary data). - */ - text: z.string() -}); -/** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ -const Base64Schema = z.string().refine(val => { - try { - // atob throws a DOMException if the string contains characters - // that are not part of the Base64 character set. - atob(val); - return true; - } - catch (_a) { - return false; - } -}, { message: 'Invalid Base64 string' }); -exports.BlobResourceContentsSchema = exports.ResourceContentsSchema.extend({ - /** - * A base64-encoded string representing the binary data of the item. - */ - blob: Base64Schema -}); -/** - * A known resource that the server is capable of reading. - */ -exports.ResourceSchema = z.object({ - ...exports.BaseMetadataSchema.shape, - ...exports.IconsSchema.shape, - /** - * The URI of this resource. - */ - uri: z.string(), - /** - * A description of what this resource represents. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description: z.optional(z.string()), - /** - * The MIME type of this resource, if known. - */ - mimeType: z.optional(z.string()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.looseObject({})) -}); -/** - * A template description for resources available on the server. - */ -exports.ResourceTemplateSchema = z.object({ - ...exports.BaseMetadataSchema.shape, - ...exports.IconsSchema.shape, - /** - * A URI template (according to RFC 6570) that can be used to construct resource URIs. - */ - uriTemplate: z.string(), - /** - * A description of what this template is for. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description: z.optional(z.string()), - /** - * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. - */ - mimeType: z.optional(z.string()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.looseObject({})) -}); -/** - * Sent from the client to request a list of resources the server has. - */ -exports.ListResourcesRequestSchema = exports.PaginatedRequestSchema.extend({ - method: z.literal('resources/list') -}); -/** - * The server's response to a resources/list request from the client. - */ -exports.ListResourcesResultSchema = exports.PaginatedResultSchema.extend({ - resources: z.array(exports.ResourceSchema) -}); -/** - * Sent from the client to request a list of resource templates the server has. - */ -exports.ListResourceTemplatesRequestSchema = exports.PaginatedRequestSchema.extend({ - method: z.literal('resources/templates/list') -}); -/** - * The server's response to a resources/templates/list request from the client. - */ -exports.ListResourceTemplatesResultSchema = exports.PaginatedResultSchema.extend({ - resourceTemplates: z.array(exports.ResourceTemplateSchema) -}); -exports.ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. - * - * @format uri - */ - uri: z.string() -}); -/** - * Parameters for a `resources/read` request. - */ -exports.ReadResourceRequestParamsSchema = exports.ResourceRequestParamsSchema; -/** - * Sent from the client to the server, to read a specific resource URI. - */ -exports.ReadResourceRequestSchema = exports.RequestSchema.extend({ - method: z.literal('resources/read'), - params: exports.ReadResourceRequestParamsSchema -}); -/** - * The server's response to a resources/read request from the client. - */ -exports.ReadResourceResultSchema = exports.ResultSchema.extend({ - contents: z.array(z.union([exports.TextResourceContentsSchema, exports.BlobResourceContentsSchema])) -}); -/** - * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. - */ -exports.ResourceListChangedNotificationSchema = exports.NotificationSchema.extend({ - method: z.literal('notifications/resources/list_changed') -}); -exports.SubscribeRequestParamsSchema = exports.ResourceRequestParamsSchema; -/** - * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. - */ -exports.SubscribeRequestSchema = exports.RequestSchema.extend({ - method: z.literal('resources/subscribe'), - params: exports.SubscribeRequestParamsSchema -}); -exports.UnsubscribeRequestParamsSchema = exports.ResourceRequestParamsSchema; -/** - * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. - */ -exports.UnsubscribeRequestSchema = exports.RequestSchema.extend({ - method: z.literal('resources/unsubscribe'), - params: exports.UnsubscribeRequestParamsSchema -}); -/** - * Parameters for a `notifications/resources/updated` notification. - */ -exports.ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. - */ - uri: z.string() -}); -/** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. - */ -exports.ResourceUpdatedNotificationSchema = exports.NotificationSchema.extend({ - method: z.literal('notifications/resources/updated'), - params: exports.ResourceUpdatedNotificationParamsSchema -}); -/* Prompts */ -/** - * Describes an argument that a prompt can accept. - */ -exports.PromptArgumentSchema = z.object({ - /** - * The name of the argument. - */ - name: z.string(), - /** - * A human-readable description of the argument. - */ - description: z.optional(z.string()), - /** - * Whether this argument must be provided. - */ - required: z.optional(z.boolean()) -}); -/** - * A prompt or prompt template that the server offers. - */ -exports.PromptSchema = z.object({ - ...exports.BaseMetadataSchema.shape, - ...exports.IconsSchema.shape, - /** - * An optional description of what this prompt provides - */ - description: z.optional(z.string()), - /** - * A list of arguments to use for templating the prompt. - */ - arguments: z.optional(z.array(exports.PromptArgumentSchema)), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.looseObject({})) -}); -/** - * Sent from the client to request a list of prompts and prompt templates the server has. - */ -exports.ListPromptsRequestSchema = exports.PaginatedRequestSchema.extend({ - method: z.literal('prompts/list') -}); -/** - * The server's response to a prompts/list request from the client. - */ -exports.ListPromptsResultSchema = exports.PaginatedResultSchema.extend({ - prompts: z.array(exports.PromptSchema) -}); -/** - * Parameters for a `prompts/get` request. - */ -exports.GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The name of the prompt or prompt template. - */ - name: z.string(), - /** - * Arguments to use for templating the prompt. - */ - arguments: z.record(z.string(), z.string()).optional() -}); -/** - * Used by the client to get a prompt provided by the server. - */ -exports.GetPromptRequestSchema = exports.RequestSchema.extend({ - method: z.literal('prompts/get'), - params: exports.GetPromptRequestParamsSchema -}); -/** - * Text provided to or from an LLM. - */ -exports.TextContentSchema = z.object({ - type: z.literal('text'), - /** - * The text content of the message. - */ - text: z.string(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * An image provided to or from an LLM. - */ -exports.ImageContentSchema = z.object({ - type: z.literal('image'), - /** - * The base64-encoded image data. - */ - data: Base64Schema, - /** - * The MIME type of the image. Different providers may support different image types. - */ - mimeType: z.string(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * An Audio provided to or from an LLM. - */ -exports.AudioContentSchema = z.object({ - type: z.literal('audio'), - /** - * The base64-encoded audio data. - */ - data: Base64Schema, - /** - * The MIME type of the audio. Different providers may support different audio types. - */ - mimeType: z.string(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * A tool call request from an assistant (LLM). - * Represents the assistant's request to use a tool. - */ -exports.ToolUseContentSchema = z - .object({ - type: z.literal('tool_use'), - /** - * The name of the tool to invoke. - * Must match a tool name from the request's tools array. - */ - name: z.string(), - /** - * Unique identifier for this tool call. - * Used to correlate with ToolResultContent in subsequent messages. - */ - id: z.string(), - /** - * Arguments to pass to the tool. - * Must conform to the tool's inputSchema. - */ - input: z.object({}).passthrough(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) -}) - .passthrough(); -/** - * The contents of a resource, embedded into a prompt or tool call result. - */ -exports.EmbeddedResourceSchema = z.object({ - type: z.literal('resource'), - resource: z.union([exports.TextResourceContentsSchema, exports.BlobResourceContentsSchema]), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * A resource that the server is capable of reading, included in a prompt or tool call result. - * - * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. - */ -exports.ResourceLinkSchema = exports.ResourceSchema.extend({ - type: z.literal('resource_link') -}); -/** - * A content block that can be used in prompts and tool results. - */ -exports.ContentBlockSchema = z.union([ - exports.TextContentSchema, - exports.ImageContentSchema, - exports.AudioContentSchema, - exports.ResourceLinkSchema, - exports.EmbeddedResourceSchema -]); -/** - * Describes a message returned as part of a prompt. - */ -exports.PromptMessageSchema = z.object({ - role: z.enum(['user', 'assistant']), - content: exports.ContentBlockSchema -}); -/** - * The server's response to a prompts/get request from the client. - */ -exports.GetPromptResultSchema = exports.ResultSchema.extend({ - /** - * An optional description for the prompt. - */ - description: z.optional(z.string()), - messages: z.array(exports.PromptMessageSchema) -}); -/** - * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. - */ -exports.PromptListChangedNotificationSchema = exports.NotificationSchema.extend({ - method: z.literal('notifications/prompts/list_changed') -}); -/* Tools */ -/** - * Security scheme indicating no authentication is required. - */ -exports.NoAuthSecuritySchemeSchema = z.object({ - type: z.literal('noauth') -}); -/** - * Security scheme indicating OAuth 2.0 authentication is required. - */ -exports.OAuth2SecuritySchemeSchema = z.object({ - type: z.literal('oauth2'), - /** - * Optional list of OAuth 2.0 scopes required for this tool. - */ - scopes: z - .array(z.string().min(1)) - .refine((arr) => new Set(arr).size === arr.length, { - message: 'Scopes must be unique' - }) - .optional() -}); -/** - * A security scheme that can be used to authenticate tool calls. - */ -exports.SecuritySchemeSchema = z.union([exports.NoAuthSecuritySchemeSchema, exports.OAuth2SecuritySchemeSchema]); -/** - * Additional properties describing a Tool to clients. - * - * NOTE: all properties in ToolAnnotations are **hints**. - * They are not guaranteed to provide a faithful description of - * tool behavior (including descriptive properties like `title`). - * - * Clients should never make tool use decisions based on ToolAnnotations - * received from untrusted servers. - */ -exports.ToolAnnotationsSchema = z.object({ - /** - * A human-readable title for the tool. - */ - title: z.string().optional(), - /** - * If true, the tool does not modify its environment. - * - * Default: false - */ - readOnlyHint: z.boolean().optional(), - /** - * If true, the tool may perform destructive updates to its environment. - * If false, the tool performs only additive updates. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: true - */ - destructiveHint: z.boolean().optional(), - /** - * If true, calling the tool repeatedly with the same arguments - * will have no additional effect on the its environment. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: false - */ - idempotentHint: z.boolean().optional(), - /** - * If true, this tool may interact with an "open world" of external - * entities. If false, the tool's domain of interaction is closed. - * For example, the world of a web search tool is open, whereas that - * of a memory tool is not. - * - * Default: true - */ - openWorldHint: z.boolean().optional() -}); -/** - * Definition for a tool the client can call. - */ -exports.ToolSchema = z.object({ - ...exports.BaseMetadataSchema.shape, - ...exports.IconsSchema.shape, - /** - * A human-readable description of the tool. - */ - description: z.string().optional(), - /** - * A JSON Schema 2020-12 object defining the expected parameters for the tool. - * Must have type: 'object' at the root level per MCP spec. - */ - inputSchema: z - .object({ - type: z.literal('object'), - properties: z.record(z.string(), AssertObjectSchema).optional(), - required: z.array(z.string()).optional() - }) - .catchall(z.unknown()), - /** - * An optional JSON Schema 2020-12 object defining the structure of the tool's output - * returned in the structuredContent field of a CallToolResult. - * Must have type: 'object' at the root level per MCP spec. - */ - outputSchema: z - .object({ - type: z.literal('object'), - properties: z.record(z.string(), AssertObjectSchema).optional(), - required: z.array(z.string()).optional() - }) - .catchall(z.unknown()) - .optional(), - /** - * Optional additional tool information. - */ - annotations: z.optional(exports.ToolAnnotationsSchema), - /** - * Optional list of security schemes supported by this tool. - * If missing, the tool follows the server's default authentication policy. - * If present, lists the supported authentication schemes (e.g., "noauth", "oauth2"). - */ - securitySchemes: z.array(exports.SecuritySchemeSchema).optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * Sent from the client to request a list of tools the server has. - */ -exports.ListToolsRequestSchema = exports.PaginatedRequestSchema.extend({ - method: z.literal('tools/list') -}); -/** - * The server's response to a tools/list request from the client. - */ -exports.ListToolsResultSchema = exports.PaginatedResultSchema.extend({ - tools: z.array(exports.ToolSchema) -}); -/** - * The server's response to a tool call. - */ -exports.CallToolResultSchema = exports.ResultSchema.extend({ - /** - * A list of content objects that represent the result of the tool call. - * - * If the Tool does not define an outputSchema, this field MUST be present in the result. - * For backwards compatibility, this field is always present, but it may be empty. - */ - content: z.array(exports.ContentBlockSchema).default([]), - /** - * An object containing structured tool output. - * - * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. - */ - structuredContent: z.record(z.string(), z.unknown()).optional(), - /** - * Whether the tool call ended in an error. - * - * If not set, this is assumed to be false (the call was successful). - * - * Any errors that originate from the tool SHOULD be reported inside the result - * object, with `isError` set to true, _not_ as an MCP protocol-level error - * response. Otherwise, the LLM would not be able to see that an error occurred - * and self-correct. - * - * However, any errors in _finding_ the tool, an error indicating that the - * server does not support tool calls, or any other exceptional conditions, - * should be reported as an MCP error response. - */ - isError: z.optional(z.boolean()) -}); -/** - * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. - */ -exports.CompatibilityCallToolResultSchema = exports.CallToolResultSchema.or(exports.ResultSchema.extend({ - toolResult: z.unknown() -})); -/** - * Parameters for a `tools/call` request. - */ -exports.CallToolRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The name of the tool to call. - */ - name: z.string(), - /** - * Arguments to pass to the tool. - */ - arguments: z.optional(z.record(z.string(), z.unknown())) -}); -/** - * Used by the client to invoke a tool provided by the server. - */ -exports.CallToolRequestSchema = exports.RequestSchema.extend({ - method: z.literal('tools/call'), - params: exports.CallToolRequestParamsSchema -}); -/** - * 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. - */ -exports.ToolListChangedNotificationSchema = exports.NotificationSchema.extend({ - method: z.literal('notifications/tools/list_changed') -}); -/* Logging */ -/** - * The severity of a log message. - */ -exports.LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); -/** - * Parameters for a `logging/setLevel` request. - */ -exports.SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. - */ - level: exports.LoggingLevelSchema -}); -/** - * A request from the client to the server, to enable or adjust logging. - */ -exports.SetLevelRequestSchema = exports.RequestSchema.extend({ - method: z.literal('logging/setLevel'), - params: exports.SetLevelRequestParamsSchema -}); -/** - * Parameters for a `notifications/message` notification. - */ -exports.LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The severity of this log message. - */ - level: exports.LoggingLevelSchema, - /** - * An optional name of the logger issuing this message. - */ - logger: z.string().optional(), - /** - * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. - */ - data: z.unknown() -}); -/** - * 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. - */ -exports.LoggingMessageNotificationSchema = exports.NotificationSchema.extend({ - method: z.literal('notifications/message'), - params: exports.LoggingMessageNotificationParamsSchema -}); -/* Sampling */ -/** - * Hints to use for model selection. - */ -exports.ModelHintSchema = z.object({ - /** - * A hint for a model name. - */ - name: z.string().optional() -}); -/** - * The server's preferences for model selection, requested of the client during sampling. - */ -exports.ModelPreferencesSchema = z.object({ - /** - * Optional hints to use for model selection. - */ - hints: z.optional(z.array(exports.ModelHintSchema)), - /** - * How much to prioritize cost when selecting a model. - */ - costPriority: z.optional(z.number().min(0).max(1)), - /** - * How much to prioritize sampling speed (latency) when selecting a model. - */ - speedPriority: z.optional(z.number().min(0).max(1)), - /** - * How much to prioritize intelligence and capabilities when selecting a model. - */ - intelligencePriority: z.optional(z.number().min(0).max(1)) -}); -/** - * Controls tool usage behavior in sampling requests. - */ -exports.ToolChoiceSchema = z.object({ - /** - * Controls when tools are used: - * - "auto": Model decides whether to use tools (default) - * - "required": Model MUST use at least one tool before completing - * - "none": Model MUST NOT use any tools - */ - mode: z.optional(z.enum(['auto', 'required', 'none'])) -}); -/** - * The result of a tool execution, provided by the user (server). - * Represents the outcome of invoking a tool requested via ToolUseContent. - */ -exports.ToolResultContentSchema = z - .object({ - type: z.literal('tool_result'), - toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'), - content: z.array(exports.ContentBlockSchema).default([]), - structuredContent: z.object({}).passthrough().optional(), - isError: z.optional(z.boolean()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) -}) - .passthrough(); -/** - * Content block types allowed in sampling messages. - * This includes text, image, audio, tool use requests, and tool results. - */ -exports.SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ - exports.TextContentSchema, - exports.ImageContentSchema, - exports.AudioContentSchema, - exports.ToolUseContentSchema, - exports.ToolResultContentSchema -]); -/** - * Describes a message issued to or received from an LLM API. - */ -exports.SamplingMessageSchema = z - .object({ - role: z.enum(['user', 'assistant']), - content: z.union([exports.SamplingMessageContentBlockSchema, z.array(exports.SamplingMessageContentBlockSchema)]), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) -}) - .passthrough(); -/** - * Parameters for a `sampling/createMessage` request. - */ -exports.CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({ - messages: z.array(exports.SamplingMessageSchema), - /** - * The server's preferences for which model to select. The client MAY modify or omit this request. - */ - modelPreferences: exports.ModelPreferencesSchema.optional(), - /** - * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. - */ - systemPrompt: z.string().optional(), - /** - * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. - * The client MAY ignore this request. - * - * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client - * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. - */ - includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(), - temperature: z.number().optional(), - /** - * The requested maximum number of tokens to sample (to prevent runaway completions). - * - * The client MAY choose to sample fewer tokens than the requested maximum. - */ - maxTokens: z.number().int(), - stopSequences: z.array(z.string()).optional(), - /** - * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. - */ - metadata: AssertObjectSchema.optional(), - /** - * Tools that the model may use during generation. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. - */ - tools: z.optional(z.array(exports.ToolSchema)), - /** - * Controls how the model uses tools. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. - * Default is `{ mode: "auto" }`. - */ - toolChoice: z.optional(exports.ToolChoiceSchema) -}); -/** - * 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. - */ -exports.CreateMessageRequestSchema = exports.RequestSchema.extend({ - method: z.literal('sampling/createMessage'), - params: exports.CreateMessageRequestParamsSchema -}); -/** - * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. - */ -exports.CreateMessageResultSchema = exports.ResultSchema.extend({ - /** - * The name of the model that generated the message. - */ - model: z.string(), - /** - * The reason why sampling stopped, if known. - * - * Standard values: - * - "endTurn": Natural end of the assistant's turn - * - "stopSequence": A stop sequence was encountered - * - "maxTokens": Maximum token limit was reached - * - "toolUse": The model wants to use one or more tools - * - * This field is an open string to allow for provider-specific stop reasons. - */ - stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())), - role: z.enum(['user', 'assistant']), - /** - * Response content. May be ToolUseContent if stopReason is "toolUse". - */ - content: z.union([exports.SamplingMessageContentBlockSchema, z.array(exports.SamplingMessageContentBlockSchema)]) -}); -/* Elicitation */ -/** - * Primitive schema definition for boolean fields. - */ -exports.BooleanSchemaSchema = z.object({ - type: z.literal('boolean'), - title: z.string().optional(), - description: z.string().optional(), - default: z.boolean().optional() -}); -/** - * Primitive schema definition for string fields. - */ -exports.StringSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - minLength: z.number().optional(), - maxLength: z.number().optional(), - format: z.enum(['email', 'uri', 'date', 'date-time']).optional(), - default: z.string().optional() -}); -/** - * Primitive schema definition for number fields. - */ -exports.NumberSchemaSchema = z.object({ - type: z.enum(['number', 'integer']), - title: z.string().optional(), - description: z.string().optional(), - minimum: z.number().optional(), - maximum: z.number().optional(), - default: z.number().optional() -}); -/** - * Schema for single-selection enumeration without display titles for options. - */ -exports.UntitledSingleSelectEnumSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - enum: z.array(z.string()), - default: z.string().optional() -}); -/** - * Schema for single-selection enumeration with display titles for each option. - */ -exports.TitledSingleSelectEnumSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - oneOf: z.array(z.object({ - const: z.string(), - title: z.string() - })), - default: z.string().optional() -}); -/** - * Use TitledSingleSelectEnumSchema instead. - * This interface will be removed in a future version. - */ -exports.LegacyTitledEnumSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - enum: z.array(z.string()), - enumNames: z.array(z.string()).optional(), - default: z.string().optional() -}); -// Combined single selection enumeration -exports.SingleSelectEnumSchemaSchema = z.union([exports.UntitledSingleSelectEnumSchemaSchema, exports.TitledSingleSelectEnumSchemaSchema]); -/** - * Schema for multiple-selection enumeration without display titles for options. - */ -exports.UntitledMultiSelectEnumSchemaSchema = z.object({ - type: z.literal('array'), - title: z.string().optional(), - description: z.string().optional(), - minItems: z.number().optional(), - maxItems: z.number().optional(), - items: z.object({ - type: z.literal('string'), - enum: z.array(z.string()) - }), - default: z.array(z.string()).optional() -}); -/** - * Schema for multiple-selection enumeration with display titles for each option. - */ -exports.TitledMultiSelectEnumSchemaSchema = z.object({ - type: z.literal('array'), - title: z.string().optional(), - description: z.string().optional(), - minItems: z.number().optional(), - maxItems: z.number().optional(), - items: z.object({ - anyOf: z.array(z.object({ - const: z.string(), - title: z.string() - })) - }), - default: z.array(z.string()).optional() -}); -/** - * Combined schema for multiple-selection enumeration - */ -exports.MultiSelectEnumSchemaSchema = z.union([exports.UntitledMultiSelectEnumSchemaSchema, exports.TitledMultiSelectEnumSchemaSchema]); -/** - * Primitive schema definition for enum fields. - */ -exports.EnumSchemaSchema = z.union([exports.LegacyTitledEnumSchemaSchema, exports.SingleSelectEnumSchemaSchema, exports.MultiSelectEnumSchemaSchema]); -/** - * Union of all primitive schema definitions. - */ -exports.PrimitiveSchemaDefinitionSchema = z.union([exports.EnumSchemaSchema, exports.BooleanSchemaSchema, exports.StringSchemaSchema, exports.NumberSchemaSchema]); -/** - * Parameters for an `elicitation/create` request for form-based elicitation. - */ -exports.ElicitRequestFormParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The elicitation mode. - */ - mode: z.literal('form'), - /** - * The message to present to the user describing what information is being requested. - */ - message: z.string(), - /** - * A restricted subset of JSON Schema. - * Only top-level properties are allowed, without nesting. - */ - requestedSchema: z.object({ - type: z.literal('object'), - properties: z.record(z.string(), exports.PrimitiveSchemaDefinitionSchema), - required: z.array(z.string()).optional() - }) -}); -/** - * Parameters for an `elicitation/create` request for URL-based elicitation. - */ -exports.ElicitRequestURLParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The elicitation mode. - */ - mode: z.literal('url'), - /** - * The message to present to the user explaining why the interaction is needed. - */ - message: z.string(), - /** - * The ID of the elicitation, which must be unique within the context of the server. - * The client MUST treat this ID as an opaque value. - */ - elicitationId: z.string(), - /** - * The URL that the user should navigate to. - */ - url: z.string().url() -}); -/** - * The parameters for a request to elicit additional information from the user via the client. - */ -exports.ElicitRequestParamsSchema = z.union([exports.ElicitRequestFormParamsSchema, exports.ElicitRequestURLParamsSchema]); -/** - * A request from the server to elicit user input via the client. - * The client should present the message and form fields to the user (form mode) - * or navigate to a URL (URL mode). - */ -exports.ElicitRequestSchema = exports.RequestSchema.extend({ - method: z.literal('elicitation/create'), - params: exports.ElicitRequestParamsSchema -}); -/** - * Parameters for a `notifications/elicitation/complete` notification. - * - * @category notifications/elicitation/complete - */ -exports.ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The ID of the elicitation that completed. - */ - elicitationId: z.string() -}); -/** - * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. - * - * @category notifications/elicitation/complete - */ -exports.ElicitationCompleteNotificationSchema = exports.NotificationSchema.extend({ - method: z.literal('notifications/elicitation/complete'), - params: exports.ElicitationCompleteNotificationParamsSchema -}); -/** - * The client's response to an elicitation/create request from the server. - */ -exports.ElicitResultSchema = exports.ResultSchema.extend({ - /** - * The user action in response to the elicitation. - * - "accept": User submitted the form/confirmed the action - * - "decline": User explicitly decline the action - * - "cancel": User dismissed without making an explicit choice - */ - action: z.enum(['accept', 'decline', 'cancel']), - /** - * The submitted form data, only present when action is "accept". - * Contains values matching the requested schema. - */ - content: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional() -}); -/* Autocomplete */ -/** - * A reference to a resource or resource template definition. - */ -exports.ResourceTemplateReferenceSchema = z.object({ - type: z.literal('ref/resource'), - /** - * The URI or URI template of the resource. - */ - uri: z.string() -}); -/** - * @deprecated Use ResourceTemplateReferenceSchema instead - */ -exports.ResourceReferenceSchema = exports.ResourceTemplateReferenceSchema; -/** - * Identifies a prompt. - */ -exports.PromptReferenceSchema = z.object({ - type: z.literal('ref/prompt'), - /** - * The name of the prompt or prompt template - */ - name: z.string() -}); -/** - * Parameters for a `completion/complete` request. - */ -exports.CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ - ref: z.union([exports.PromptReferenceSchema, exports.ResourceTemplateReferenceSchema]), - /** - * The argument's information - */ - argument: z.object({ - /** - * The name of the argument - */ - name: z.string(), - /** - * The value of the argument to use for completion matching. - */ - value: z.string() - }), - context: z - .object({ - /** - * Previously-resolved variables in a URI template or prompt. - */ - arguments: z.record(z.string(), z.string()).optional() - }) - .optional() -}); -/** - * A request from the client to the server, to ask for completion options. - */ -exports.CompleteRequestSchema = exports.RequestSchema.extend({ - method: z.literal('completion/complete'), - params: exports.CompleteRequestParamsSchema -}); -function assertCompleteRequestPrompt(request) { - if (request.params.ref.type !== 'ref/prompt') { - throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); - } - void request; -} -function assertCompleteRequestResourceTemplate(request) { - if (request.params.ref.type !== 'ref/resource') { - throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); - } - void request; -} -/** - * The server's response to a completion/complete request - */ -exports.CompleteResultSchema = exports.ResultSchema.extend({ - completion: z.looseObject({ - /** - * An array of completion values. Must not exceed 100 items. - */ - values: z.array(z.string()).max(100), - /** - * The total number of completion options available. This can exceed the number of values actually sent in the response. - */ - total: z.optional(z.number().int()), - /** - * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. - */ - hasMore: z.optional(z.boolean()) - }) -}); -/* Roots */ -/** - * Represents a root directory or file that the server can operate on. - */ -exports.RootSchema = z.object({ - /** - * The URI identifying the root. This *must* start with file:// for now. - */ - uri: z.string().startsWith('file://'), - /** - * An optional name for the root. - */ - name: z.string().optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * Sent from the server to request a list of root URIs from the client. - */ -exports.ListRootsRequestSchema = exports.RequestSchema.extend({ - method: z.literal('roots/list') -}); -/** - * The client's response to a roots/list request from the server. - */ -exports.ListRootsResultSchema = exports.ResultSchema.extend({ - roots: z.array(exports.RootSchema) -}); -/** - * A notification from the client to the server, informing it that the list of roots has changed. - */ -exports.RootsListChangedNotificationSchema = exports.NotificationSchema.extend({ - method: z.literal('notifications/roots/list_changed') -}); -/* Client messages */ -exports.ClientRequestSchema = z.union([ - exports.PingRequestSchema, - exports.InitializeRequestSchema, - exports.CompleteRequestSchema, - exports.SetLevelRequestSchema, - exports.GetPromptRequestSchema, - exports.ListPromptsRequestSchema, - exports.ListResourcesRequestSchema, - exports.ListResourceTemplatesRequestSchema, - exports.ReadResourceRequestSchema, - exports.SubscribeRequestSchema, - exports.UnsubscribeRequestSchema, - exports.CallToolRequestSchema, - exports.ListToolsRequestSchema -]); -exports.ClientNotificationSchema = z.union([ - exports.CancelledNotificationSchema, - exports.ProgressNotificationSchema, - exports.InitializedNotificationSchema, - exports.RootsListChangedNotificationSchema -]); -exports.ClientResultSchema = z.union([exports.EmptyResultSchema, exports.CreateMessageResultSchema, exports.ElicitResultSchema, exports.ListRootsResultSchema]); -/* Server messages */ -exports.ServerRequestSchema = z.union([exports.PingRequestSchema, exports.CreateMessageRequestSchema, exports.ElicitRequestSchema, exports.ListRootsRequestSchema]); -exports.ServerNotificationSchema = z.union([ - exports.CancelledNotificationSchema, - exports.ProgressNotificationSchema, - exports.LoggingMessageNotificationSchema, - exports.ResourceUpdatedNotificationSchema, - exports.ResourceListChangedNotificationSchema, - exports.ToolListChangedNotificationSchema, - exports.PromptListChangedNotificationSchema, - exports.ElicitationCompleteNotificationSchema -]); -exports.ServerResultSchema = z.union([ - exports.EmptyResultSchema, - exports.InitializeResultSchema, - exports.CompleteResultSchema, - exports.GetPromptResultSchema, - exports.ListPromptsResultSchema, - exports.ListResourcesResultSchema, - exports.ListResourceTemplatesResultSchema, - exports.ReadResourceResultSchema, - exports.CallToolResultSchema, - exports.ListToolsResultSchema -]); -class McpError extends Error { - constructor(code, message, data) { - super(`MCP error ${code}: ${message}`); - this.code = code; - this.data = data; - this.name = 'McpError'; - } - /** - * Factory method to create the appropriate error type based on the error code and data - */ - static fromError(code, message, data) { - // Check for specific error types - if (code === ErrorCode.UrlElicitationRequired && data) { - const errorData = data; - if (errorData.elicitations) { - return new UrlElicitationRequiredError(errorData.elicitations, message); - } - } - // Default to generic McpError - return new McpError(code, message, data); - } -} -exports.McpError = McpError; -/** - * Specialized error type when a tool requires a URL mode elicitation. - * 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. - */ -class UrlElicitationRequiredError extends McpError { - constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) { - super(ErrorCode.UrlElicitationRequired, message, { - elicitations: elicitations - }); - } - get elicitations() { - var _a, _b; - return (_b = (_a = this.data) === null || _a === void 0 ? void 0 : _a.elicitations) !== null && _b !== void 0 ? _b : []; - } -} -exports.UrlElicitationRequiredError = UrlElicitationRequiredError; -//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/cjs/types.js.map b/dist/cjs/types.js.map deleted file mode 100644 index 62b44a4f3c..0000000000 --- a/dist/cjs/types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0oDA,kEAKC;AAED,sFAKC;AAtpDD,0CAA4B;AAGf,QAAA,uBAAuB,GAAG,YAAY,CAAC;AACvC,QAAA,mCAAmC,GAAG,YAAY,CAAC;AACnD,QAAA,2BAA2B,GAAG,CAAC,+BAAuB,EAAE,YAAY,EAAE,YAAY,EAAE,YAAY,CAA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AAI,CAAQ;QAEZ,SAAI,GAAJ,IAAI,CAAU;QAG9B,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;IAC3B,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,SAAS,CAAC,IAAY,EAAE,OAAe,EAAE,IAAc;QAC1D,iCAAiC;QACjC,IAAI,IAAI,KAAK,SAAS,CAAC,sBAAsB,IAAI,IAAI,EAAE,CAAC;YACpD,MAAM,SAAS,GAAG,IAAoC,CAAC;YACvD,IAAI,SAAS,CAAC,YAAY,EAAE,CAAC;gBACzB,OAAO,IAAI,2BAA2B,CAAC,SAAS,CAAC,YAAwC,EAAE,OAAO,CAAC,CAAC;YACxG,CAAC;QACL,CAAC;QAED,8BAA8B;QAC9B,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC7C,CAAC;CACJ;AAzBD,4BAyBC;AAED;;;GAGG;AACH,MAAa,2BAA4B,SAAQ,QAAQ;IACrD,YAAY,YAAsC,EAAE,UAAkB,kBAAkB,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,WAAW;QACjI,KAAK,CAAC,SAAS,CAAC,sBAAsB,EAAE,OAAO,EAAE;YAC7C,YAAY,EAAE,YAAY;SAC7B,CAAC,CAAC;IACP,CAAC;IAED,IAAI,YAAY;;QACZ,OAAO,MAAA,MAAC,IAAI,CAAC,IAAmD,0CAAE,YAAY,mCAAI,EAAE,CAAC;IACzF,CAAC;CACJ;AAVD,kEAUC"} \ No newline at end of file diff --git a/dist/cjs/validation/ajv-provider.d.ts b/dist/cjs/validation/ajv-provider.d.ts deleted file mode 100644 index 43e24ffc93..0000000000 --- a/dist/cjs/validation/ajv-provider.d.ts +++ /dev/null @@ -1,53 +0,0 @@ -/** - * AJV-based JSON Schema validator provider - */ -import { Ajv } from 'ajv'; -import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from './types.js'; -/** - * @example - * ```typescript - * // Use with default AJV instance (recommended) - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // Use with custom AJV instance - * import { Ajv } from 'ajv'; - * const ajv = new Ajv({ strict: true, allErrors: true }); - * const validator = new AjvJsonSchemaValidator(ajv); - * ``` - */ -export declare class AjvJsonSchemaValidator implements jsonSchemaValidator { - private _ajv; - /** - * Create an AJV validator - * - * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. - * - * @example - * ```typescript - * // Use default configuration (recommended for most cases) - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // Or provide custom AJV instance for advanced configuration - * import { Ajv } from 'ajv'; - * import addFormats from 'ajv-formats'; - * - * const ajv = new Ajv({ validateFormats: true }); - * addFormats(ajv); - * const validator = new AjvJsonSchemaValidator(ajv); - * ``` - */ - constructor(ajv?: Ajv); - /** - * Create a validator for the given JSON Schema - * - * The validator is compiled once and can be reused multiple times. - * If the schema has an $id, it will be cached by AJV automatically. - * - * @param schema - Standard JSON Schema object - * @returns A validator function that validates input data - */ - getValidator(schema: JsonSchemaType): JsonSchemaValidator; -} -//# sourceMappingURL=ajv-provider.d.ts.map \ No newline at end of file diff --git a/dist/cjs/validation/ajv-provider.d.ts.map b/dist/cjs/validation/ajv-provider.d.ts.map deleted file mode 100644 index 4e955a3b32..0000000000 --- a/dist/cjs/validation/ajv-provider.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ajv-provider.d.ts","sourceRoot":"","sources":["../../../src/validation/ajv-provider.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAE1B,OAAO,KAAK,EAAE,cAAc,EAAE,mBAAmB,EAA6B,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAgBtH;;;;;;;;;;;;GAYG;AACH,qBAAa,sBAAuB,YAAW,mBAAmB;IAC9D,OAAO,CAAC,IAAI,CAAM;IAElB;;;;;;;;;;;;;;;;;;;OAmBG;gBACS,GAAG,CAAC,EAAE,GAAG;IAIrB;;;;;;;;OAQG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC;CAyBlE"} \ No newline at end of file diff --git a/dist/cjs/validation/ajv-provider.js b/dist/cjs/validation/ajv-provider.js deleted file mode 100644 index 7356bfa303..0000000000 --- a/dist/cjs/validation/ajv-provider.js +++ /dev/null @@ -1,95 +0,0 @@ -"use strict"; -/** - * AJV-based JSON Schema validator provider - */ -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AjvJsonSchemaValidator = void 0; -const ajv_1 = require("ajv"); -const ajv_formats_1 = __importDefault(require("ajv-formats")); -function createDefaultAjvInstance() { - const ajv = new ajv_1.Ajv({ - strict: false, - validateFormats: true, - validateSchema: false, - allErrors: true - }); - const addFormats = ajv_formats_1.default; - addFormats(ajv); - return ajv; -} -/** - * @example - * ```typescript - * // Use with default AJV instance (recommended) - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // Use with custom AJV instance - * import { Ajv } from 'ajv'; - * const ajv = new Ajv({ strict: true, allErrors: true }); - * const validator = new AjvJsonSchemaValidator(ajv); - * ``` - */ -class AjvJsonSchemaValidator { - /** - * Create an AJV validator - * - * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. - * - * @example - * ```typescript - * // Use default configuration (recommended for most cases) - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // Or provide custom AJV instance for advanced configuration - * import { Ajv } from 'ajv'; - * import addFormats from 'ajv-formats'; - * - * const ajv = new Ajv({ validateFormats: true }); - * addFormats(ajv); - * const validator = new AjvJsonSchemaValidator(ajv); - * ``` - */ - constructor(ajv) { - this._ajv = ajv !== null && ajv !== void 0 ? ajv : createDefaultAjvInstance(); - } - /** - * Create a validator for the given JSON Schema - * - * The validator is compiled once and can be reused multiple times. - * If the schema has an $id, it will be cached by AJV automatically. - * - * @param schema - Standard JSON Schema object - * @returns A validator function that validates input data - */ - getValidator(schema) { - var _a; - // Check if schema has $id and is already compiled/cached - const ajvValidator = '$id' in schema && typeof schema.$id === 'string' - ? ((_a = this._ajv.getSchema(schema.$id)) !== null && _a !== void 0 ? _a : this._ajv.compile(schema)) - : this._ajv.compile(schema); - return (input) => { - const valid = ajvValidator(input); - if (valid) { - return { - valid: true, - data: input, - errorMessage: undefined - }; - } - else { - return { - valid: false, - data: undefined, - errorMessage: this._ajv.errorsText(ajvValidator.errors) - }; - } - }; - } -} -exports.AjvJsonSchemaValidator = AjvJsonSchemaValidator; -//# sourceMappingURL=ajv-provider.js.map \ No newline at end of file diff --git a/dist/cjs/validation/ajv-provider.js.map b/dist/cjs/validation/ajv-provider.js.map deleted file mode 100644 index fcaa27e9f5..0000000000 --- a/dist/cjs/validation/ajv-provider.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ajv-provider.js","sourceRoot":"","sources":["../../../src/validation/ajv-provider.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;;AAEH,6BAA0B;AAC1B,8DAAsC;AAGtC,SAAS,wBAAwB;IAC7B,MAAM,GAAG,GAAG,IAAI,SAAG,CAAC;QAChB,MAAM,EAAE,KAAK;QACb,eAAe,EAAE,IAAI;QACrB,cAAc,EAAE,KAAK;QACrB,SAAS,EAAE,IAAI;KAClB,CAAC,CAAC;IAEH,MAAM,UAAU,GAAG,qBAAoD,CAAC;IACxE,UAAU,CAAC,GAAG,CAAC,CAAC;IAEhB,OAAO,GAAG,CAAC;AACf,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAa,sBAAsB;IAG/B;;;;;;;;;;;;;;;;;;;OAmBG;IACH,YAAY,GAAS;QACjB,IAAI,CAAC,IAAI,GAAG,GAAG,aAAH,GAAG,cAAH,GAAG,GAAI,wBAAwB,EAAE,CAAC;IAClD,CAAC;IAED;;;;;;;;OAQG;IACH,YAAY,CAAI,MAAsB;;QAClC,yDAAyD;QACzD,MAAM,YAAY,GACd,KAAK,IAAI,MAAM,IAAI,OAAO,MAAM,CAAC,GAAG,KAAK,QAAQ;YAC7C,CAAC,CAAC,CAAC,MAAA,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,mCAAI,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YAChE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAEpC,OAAO,CAAC,KAAc,EAAgC,EAAE;YACpD,MAAM,KAAK,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;YAElC,IAAI,KAAK,EAAE,CAAC;gBACR,OAAO;oBACH,KAAK,EAAE,IAAI;oBACX,IAAI,EAAE,KAAU;oBAChB,YAAY,EAAE,SAAS;iBAC1B,CAAC;YACN,CAAC;iBAAM,CAAC;gBACJ,OAAO;oBACH,KAAK,EAAE,KAAK;oBACZ,IAAI,EAAE,SAAS;oBACf,YAAY,EAAE,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,MAAM,CAAC;iBAC1D,CAAC;YACN,CAAC;QACL,CAAC,CAAC;IACN,CAAC;CACJ;AA7DD,wDA6DC"} \ No newline at end of file diff --git a/dist/cjs/validation/cfworker-provider.d.ts b/dist/cjs/validation/cfworker-provider.d.ts deleted file mode 100644 index 89c244a609..0000000000 --- a/dist/cjs/validation/cfworker-provider.d.ts +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Cloudflare Worker-compatible JSON Schema validator provider - * - * This provider uses @cfworker/json-schema for validation without code generation, - * making it compatible with edge runtimes like Cloudflare Workers that restrict - * eval and new Function. - */ -import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from './types.js'; -/** - * JSON Schema draft version supported by @cfworker/json-schema - */ -export type CfWorkerSchemaDraft = '4' | '7' | '2019-09' | '2020-12'; -/** - * - * @example - * ```typescript - * // Use with default configuration (2020-12, shortcircuit) - * const validator = new CfWorkerJsonSchemaValidator(); - * - * // Use with custom configuration - * const validator = new CfWorkerJsonSchemaValidator({ - * draft: '2020-12', - * shortcircuit: false // Report all errors - * }); - * ``` - */ -export declare class CfWorkerJsonSchemaValidator implements jsonSchemaValidator { - private shortcircuit; - private draft; - /** - * Create a validator - * - * @param options - Configuration options - * @param options.shortcircuit - If true, stop validation after first error (default: true) - * @param options.draft - JSON Schema draft version to use (default: '2020-12') - */ - constructor(options?: { - shortcircuit?: boolean; - draft?: CfWorkerSchemaDraft; - }); - /** - * Create a validator for the given JSON Schema - * - * Unlike AJV, this validator is not cached internally - * - * @param schema - Standard JSON Schema object - * @returns A validator function that validates input data - */ - getValidator(schema: JsonSchemaType): JsonSchemaValidator; -} -//# sourceMappingURL=cfworker-provider.d.ts.map \ No newline at end of file diff --git a/dist/cjs/validation/cfworker-provider.d.ts.map b/dist/cjs/validation/cfworker-provider.d.ts.map deleted file mode 100644 index ce404d92fc..0000000000 --- a/dist/cjs/validation/cfworker-provider.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"cfworker-provider.d.ts","sourceRoot":"","sources":["../../../src/validation/cfworker-provider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,mBAAmB,EAA6B,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtH;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG,GAAG,GAAG,GAAG,GAAG,SAAS,GAAG,SAAS,CAAC;AAEpE;;;;;;;;;;;;;GAaG;AACH,qBAAa,2BAA4B,YAAW,mBAAmB;IACnE,OAAO,CAAC,YAAY,CAAU;IAC9B,OAAO,CAAC,KAAK,CAAsB;IAEnC;;;;;;OAMG;gBACS,OAAO,CAAC,EAAE;QAAE,YAAY,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,mBAAmB,CAAA;KAAE;IAK7E;;;;;;;OAOG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC;CAsBlE"} \ No newline at end of file diff --git a/dist/cjs/validation/cfworker-provider.js b/dist/cjs/validation/cfworker-provider.js deleted file mode 100644 index a080a373bd..0000000000 --- a/dist/cjs/validation/cfworker-provider.js +++ /dev/null @@ -1,70 +0,0 @@ -"use strict"; -/** - * Cloudflare Worker-compatible JSON Schema validator provider - * - * This provider uses @cfworker/json-schema for validation without code generation, - * making it compatible with edge runtimes like Cloudflare Workers that restrict - * eval and new Function. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CfWorkerJsonSchemaValidator = void 0; -const json_schema_1 = require("@cfworker/json-schema"); -/** - * - * @example - * ```typescript - * // Use with default configuration (2020-12, shortcircuit) - * const validator = new CfWorkerJsonSchemaValidator(); - * - * // Use with custom configuration - * const validator = new CfWorkerJsonSchemaValidator({ - * draft: '2020-12', - * shortcircuit: false // Report all errors - * }); - * ``` - */ -class CfWorkerJsonSchemaValidator { - /** - * Create a validator - * - * @param options - Configuration options - * @param options.shortcircuit - If true, stop validation after first error (default: true) - * @param options.draft - JSON Schema draft version to use (default: '2020-12') - */ - constructor(options) { - var _a, _b; - this.shortcircuit = (_a = options === null || options === void 0 ? void 0 : options.shortcircuit) !== null && _a !== void 0 ? _a : true; - this.draft = (_b = options === null || options === void 0 ? void 0 : options.draft) !== null && _b !== void 0 ? _b : '2020-12'; - } - /** - * Create a validator for the given JSON Schema - * - * Unlike AJV, this validator is not cached internally - * - * @param schema - Standard JSON Schema object - * @returns A validator function that validates input data - */ - getValidator(schema) { - const cfSchema = schema; - const validator = new json_schema_1.Validator(cfSchema, this.draft, this.shortcircuit); - return (input) => { - const result = validator.validate(input); - if (result.valid) { - return { - valid: true, - data: input, - errorMessage: undefined - }; - } - else { - return { - valid: false, - data: undefined, - errorMessage: result.errors.map(err => `${err.instanceLocation}: ${err.error}`).join('; ') - }; - } - }; - } -} -exports.CfWorkerJsonSchemaValidator = CfWorkerJsonSchemaValidator; -//# sourceMappingURL=cfworker-provider.js.map \ No newline at end of file diff --git a/dist/cjs/validation/cfworker-provider.js.map b/dist/cjs/validation/cfworker-provider.js.map deleted file mode 100644 index b83afb3244..0000000000 --- a/dist/cjs/validation/cfworker-provider.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"cfworker-provider.js","sourceRoot":"","sources":["../../../src/validation/cfworker-provider.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEH,uDAA+D;AAQ/D;;;;;;;;;;;;;GAaG;AACH,MAAa,2BAA2B;IAIpC;;;;;;OAMG;IACH,YAAY,OAAiE;;QACzE,IAAI,CAAC,YAAY,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,mCAAI,IAAI,CAAC;QAClD,IAAI,CAAC,KAAK,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,KAAK,mCAAI,SAAS,CAAC;IAC7C,CAAC;IAED;;;;;;;OAOG;IACH,YAAY,CAAI,MAAsB;QAClC,MAAM,QAAQ,GAAG,MAA2B,CAAC;QAC7C,MAAM,SAAS,GAAG,IAAI,uBAAS,CAAC,QAAQ,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;QAEzE,OAAO,CAAC,KAAc,EAAgC,EAAE;YACpD,MAAM,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;YAEzC,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;gBACf,OAAO;oBACH,KAAK,EAAE,IAAI;oBACX,IAAI,EAAE,KAAU;oBAChB,YAAY,EAAE,SAAS;iBAC1B,CAAC;YACN,CAAC;iBAAM,CAAC;gBACJ,OAAO;oBACH,KAAK,EAAE,KAAK;oBACZ,IAAI,EAAE,SAAS;oBACf,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,gBAAgB,KAAK,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;iBAC7F,CAAC;YACN,CAAC;QACL,CAAC,CAAC;IACN,CAAC;CACJ;AA9CD,kEA8CC"} \ No newline at end of file diff --git a/dist/cjs/validation/index.d.ts b/dist/cjs/validation/index.d.ts deleted file mode 100644 index 99e993967f..0000000000 --- a/dist/cjs/validation/index.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** - * JSON Schema validation - * - * This module provides configurable JSON Schema validation for the MCP SDK. - * Choose a validator based on your runtime environment: - * - * - AjvJsonSchemaValidator: Best for Node.js (default, fastest) - * Import from: @modelcontextprotocol/sdk/validation/ajv - * Requires peer dependencies: ajv, ajv-formats - * - * - CfWorkerJsonSchemaValidator: Best for edge runtimes - * Import from: @modelcontextprotocol/sdk/validation/cfworker - * Requires peer dependency: @cfworker/json-schema - * - * @example - * ```typescript - * // For Node.js with AJV - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // For Cloudflare Workers - * import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker'; - * const validator = new CfWorkerJsonSchemaValidator(); - * ``` - * - * @module validation - */ -export type { JsonSchemaType, JsonSchemaValidator, JsonSchemaValidatorResult, jsonSchemaValidator } from './types.js'; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/cjs/validation/index.d.ts.map b/dist/cjs/validation/index.d.ts.map deleted file mode 100644 index a8845b96e7..0000000000 --- a/dist/cjs/validation/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/validation/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAGH,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC"} \ No newline at end of file diff --git a/dist/cjs/validation/index.js b/dist/cjs/validation/index.js deleted file mode 100644 index c8be9256d5..0000000000 --- a/dist/cjs/validation/index.js +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; -/** - * JSON Schema validation - * - * This module provides configurable JSON Schema validation for the MCP SDK. - * Choose a validator based on your runtime environment: - * - * - AjvJsonSchemaValidator: Best for Node.js (default, fastest) - * Import from: @modelcontextprotocol/sdk/validation/ajv - * Requires peer dependencies: ajv, ajv-formats - * - * - CfWorkerJsonSchemaValidator: Best for edge runtimes - * Import from: @modelcontextprotocol/sdk/validation/cfworker - * Requires peer dependency: @cfworker/json-schema - * - * @example - * ```typescript - * // For Node.js with AJV - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // For Cloudflare Workers - * import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker'; - * const validator = new CfWorkerJsonSchemaValidator(); - * ``` - * - * @module validation - */ -Object.defineProperty(exports, "__esModule", { value: true }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/cjs/validation/index.js.map b/dist/cjs/validation/index.js.map deleted file mode 100644 index 1d5874d998..0000000000 --- a/dist/cjs/validation/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/validation/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG"} \ No newline at end of file diff --git a/dist/cjs/validation/types.d.ts b/dist/cjs/validation/types.d.ts deleted file mode 100644 index 5872215c78..0000000000 --- a/dist/cjs/validation/types.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -import type { Schema } from '@cfworker/json-schema'; -/** - * Result of a JSON Schema validation operation - */ -export type JsonSchemaValidatorResult = { - valid: true; - data: T; - errorMessage: undefined; -} | { - valid: false; - data: undefined; - errorMessage: string; -}; -/** - * A validator function that validates data against a JSON Schema - */ -export type JsonSchemaValidator = (input: unknown) => JsonSchemaValidatorResult; -/** - * Provider interface for creating validators from JSON Schemas - * - * This is the main extension point for custom validator implementations. - * Implementations should: - * - Support JSON Schema Draft 2020-12 (or be compatible with it) - * - Return validator functions that can be called multiple times - * - Handle schema compilation/caching internally - * - Provide clear error messages on validation failure - * - * @example - * ```typescript - * class MyValidatorProvider implements jsonSchemaValidator { - * getValidator(schema: JsonSchemaType): JsonSchemaValidator { - * // Compile/cache validator from schema - * return (input: unknown) => { - * // Validate input against schema - * if (valid) { - * return { valid: true, data: input as T, errorMessage: undefined }; - * } else { - * return { valid: false, data: undefined, errorMessage: 'Error details' }; - * } - * }; - * } - * } - * ``` - */ -export interface jsonSchemaValidator { - /** - * Create a validator for the given JSON Schema - * - * @param schema - Standard JSON Schema object - * @returns A validator function that can be called multiple times - */ - getValidator(schema: JsonSchemaType): JsonSchemaValidator; -} -export type JsonSchemaType = Schema; -//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/cjs/validation/types.d.ts.map b/dist/cjs/validation/types.d.ts.map deleted file mode 100644 index 3bdf64e589..0000000000 --- a/dist/cjs/validation/types.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/validation/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAEpD;;GAEG;AACH,MAAM,MAAM,yBAAyB,CAAC,CAAC,IACjC;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,CAAC,CAAC;IAAC,YAAY,EAAE,SAAS,CAAA;CAAE,GACjD;IAAE,KAAK,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,SAAS,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC;AAE9D;;GAEG;AACH,MAAM,MAAM,mBAAmB,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,KAAK,yBAAyB,CAAC,CAAC,CAAC,CAAC;AAEtF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,WAAW,mBAAmB;IAChC;;;;;OAKG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAAC;CACnE;AAED,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/dist/cjs/validation/types.js b/dist/cjs/validation/types.js deleted file mode 100644 index 11e638d1ee..0000000000 --- a/dist/cjs/validation/types.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/cjs/validation/types.js.map b/dist/cjs/validation/types.js.map deleted file mode 100644 index 51361cf6a4..0000000000 --- a/dist/cjs/validation/types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/validation/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/client/auth.d.ts b/dist/esm/client/auth.d.ts deleted file mode 100644 index 0bf7a645e4..0000000000 --- a/dist/esm/client/auth.d.ts +++ /dev/null @@ -1,280 +0,0 @@ -import { OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens, OAuthMetadata, OAuthClientInformationFull, OAuthProtectedResourceMetadata, AuthorizationServerMetadata } from '../shared/auth.js'; -import { OAuthError } from '../server/auth/errors.js'; -import { FetchLike } from '../shared/transport.js'; -/** - * Implements an end-to-end OAuth client to be used with one MCP server. - * - * This client relies upon a concept of an authorized "session," the exact - * meaning of which is application-defined. Tokens, authorization codes, and - * code verifiers should not cross different sessions. - */ -export interface OAuthClientProvider { - /** - * The URL to redirect the user agent to after authorization. - */ - get redirectUrl(): string | URL; - /** - * External URL the server should use to fetch client metadata document - */ - clientMetadataUrl?: string; - /** - * Metadata about this OAuth client. - */ - get clientMetadata(): OAuthClientMetadata; - /** - * Returns a OAuth2 state parameter. - */ - state?(): string | Promise; - /** - * Loads information about this OAuth client, as registered already with the - * server, or returns `undefined` if the client is not registered with the - * server. - */ - clientInformation(): OAuthClientInformationMixed | undefined | Promise; - /** - * If implemented, this permits the OAuth client to dynamically register with - * the server. Client information saved this way should later be read via - * `clientInformation()`. - * - * This method is not required to be implemented if client information is - * statically known (e.g., pre-registered). - */ - saveClientInformation?(clientInformation: OAuthClientInformationMixed): void | Promise; - /** - * Loads any existing OAuth tokens for the current session, or returns - * `undefined` if there are no saved tokens. - */ - tokens(): OAuthTokens | undefined | Promise; - /** - * Stores new OAuth tokens for the current session, after a successful - * authorization. - */ - saveTokens(tokens: OAuthTokens): void | Promise; - /** - * Invoked to redirect the user agent to the given URL to begin the authorization flow. - */ - redirectToAuthorization(authorizationUrl: URL): void | Promise; - /** - * Saves a PKCE code verifier for the current session, before redirecting to - * the authorization flow. - */ - saveCodeVerifier(codeVerifier: string): void | Promise; - /** - * Loads the PKCE code verifier for the current session, necessary to validate - * the authorization result. - */ - codeVerifier(): string | Promise; - /** - * Adds custom client authentication to OAuth token requests. - * - * This optional method allows implementations to customize how client credentials - * are included in token exchange and refresh requests. When provided, this method - * is called instead of the default authentication logic, giving full control over - * the authentication mechanism. - * - * Common use cases include: - * - Supporting authentication methods beyond the standard OAuth 2.0 methods - * - Adding custom headers for proprietary authentication schemes - * - Implementing client assertion-based authentication (e.g., JWT bearer tokens) - * - * @param headers - The request headers (can be modified to add authentication) - * @param params - The request body parameters (can be modified to add credentials) - * @param url - The token endpoint URL being called - * @param metadata - Optional OAuth metadata for the server, which may include supported authentication methods - */ - addClientAuthentication?(headers: Headers, params: URLSearchParams, url: string | URL, metadata?: AuthorizationServerMetadata): void | Promise; - /** - * If defined, overrides the selection and validation of the - * RFC 8707 Resource Indicator. If left undefined, default - * validation behavior will be used. - * - * Implementations must verify the returned resource matches the MCP server. - */ - validateResourceURL?(serverUrl: string | URL, resource?: string): Promise; - /** - * If implemented, provides a way for the client to invalidate (e.g. delete) the specified - * credentials, in the case where the server has indicated that they are no longer valid. - * This avoids requiring the user to intervene manually. - */ - invalidateCredentials?(scope: 'all' | 'client' | 'tokens' | 'verifier'): void | Promise; -} -export type AuthResult = 'AUTHORIZED' | 'REDIRECT'; -export declare class UnauthorizedError extends Error { - constructor(message?: string); -} -type ClientAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'none'; -/** - * Determines the best client authentication method to use based on server support and client configuration. - * - * Priority order (highest to lowest): - * 1. client_secret_basic (if client secret is available) - * 2. client_secret_post (if client secret is available) - * 3. none (for public clients) - * - * @param clientInformation - OAuth client information containing credentials - * @param supportedMethods - Authentication methods supported by the authorization server - * @returns The selected authentication method - */ -export declare function selectClientAuthMethod(clientInformation: OAuthClientInformationMixed, supportedMethods: string[]): ClientAuthMethod; -/** - * Parses an OAuth error response from a string or Response object. - * - * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec - * and an instance of the appropriate OAuthError subclass will be returned. - * If parsing fails, it falls back to a generic ServerError that includes - * the response status (if available) and original content. - * - * @param input - A Response object or string containing the error response - * @returns A Promise that resolves to an OAuthError instance - */ -export declare function parseErrorResponse(input: Response | string): Promise; -/** - * Orchestrates the full auth flow with a server. - * - * This can be used as a single entry point for all authorization functionality, - * instead of linking together the other lower-level functions in this module. - */ -export declare function auth(provider: OAuthClientProvider, options: { - serverUrl: string | URL; - authorizationCode?: string; - scope?: string; - resourceMetadataUrl?: URL; - fetchFn?: FetchLike; -}): Promise; -/** - * SEP-991: URL-based Client IDs - * Validate that the client_id is a valid URL with https scheme - */ -export declare function isHttpsUrl(value?: string): boolean; -export declare function selectResourceURL(serverUrl: string | URL, provider: OAuthClientProvider, resourceMetadata?: OAuthProtectedResourceMetadata): Promise; -/** - * Extract resource_metadata, scope, and error from WWW-Authenticate header. - */ -export declare function extractWWWAuthenticateParams(res: Response): { - resourceMetadataUrl?: URL; - scope?: string; - error?: string; -}; -/** - * Extract resource_metadata from response header. - * @deprecated Use `extractWWWAuthenticateParams` instead. - */ -export declare function extractResourceMetadataUrl(res: Response): URL | undefined; -/** - * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata. - * - * If the server returns a 404 for the well-known endpoint, this function will - * return `undefined`. Any other errors will be thrown as exceptions. - */ -export declare function discoverOAuthProtectedResourceMetadata(serverUrl: string | URL, opts?: { - protocolVersion?: string; - resourceMetadataUrl?: string | URL; -}, fetchFn?: FetchLike): Promise; -/** - * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata. - * - * If the server returns a 404 for the well-known endpoint, this function will - * return `undefined`. Any other errors will be thrown as exceptions. - * - * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`. - */ -export declare function discoverOAuthMetadata(issuer: string | URL, { authorizationServerUrl, protocolVersion }?: { - authorizationServerUrl?: string | URL; - protocolVersion?: string; -}, fetchFn?: FetchLike): Promise; -/** - * Builds a list of discovery URLs to try for authorization server metadata. - * URLs are returned in priority order: - * 1. OAuth metadata at the given URL - * 2. OIDC metadata endpoints at the given URL - */ -export declare function buildDiscoveryUrls(authorizationServerUrl: string | URL): { - url: URL; - type: 'oauth' | 'oidc'; -}[]; -/** - * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata - * and OpenID Connect Discovery 1.0 specifications. - * - * This function implements a fallback strategy for authorization server discovery: - * 1. Attempts RFC 8414 OAuth metadata discovery first - * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery - * - * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's - * protected resource metadata, or the MCP server's URL if the - * metadata was not found. - * @param options - Configuration options - * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch - * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION - * @returns Promise resolving to authorization server metadata, or undefined if discovery fails - */ -export declare function discoverAuthorizationServerMetadata(authorizationServerUrl: string | URL, { fetchFn, protocolVersion }?: { - fetchFn?: FetchLike; - protocolVersion?: string; -}): Promise; -/** - * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL. - */ -export declare function startAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, redirectUrl, scope, state, resource }: { - metadata?: AuthorizationServerMetadata; - clientInformation: OAuthClientInformationMixed; - redirectUrl: string | URL; - scope?: string; - state?: string; - resource?: URL; -}): Promise<{ - authorizationUrl: URL; - codeVerifier: string; -}>; -/** - * Exchanges an authorization code for an access token with the given server. - * - * Supports multiple client authentication methods as specified in OAuth 2.1: - * - Automatically selects the best authentication method based on server support - * - Falls back to appropriate defaults when server metadata is unavailable - * - * @param authorizationServerUrl - The authorization server's base URL - * @param options - Configuration object containing client info, auth code, etc. - * @returns Promise resolving to OAuth tokens - * @throws {Error} When token exchange fails or authentication is invalid - */ -export declare function exchangeAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }: { - metadata?: AuthorizationServerMetadata; - clientInformation: OAuthClientInformationMixed; - authorizationCode: string; - codeVerifier: string; - redirectUri: string | URL; - resource?: URL; - addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; - fetchFn?: FetchLike; -}): Promise; -/** - * Exchange a refresh token for an updated access token. - * - * Supports multiple client authentication methods as specified in OAuth 2.1: - * - Automatically selects the best authentication method based on server support - * - Preserves the original refresh token if a new one is not returned - * - * @param authorizationServerUrl - The authorization server's base URL - * @param options - Configuration object containing client info, refresh token, etc. - * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced) - * @throws {Error} When token refresh fails or authentication is invalid - */ -export declare function refreshAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }: { - metadata?: AuthorizationServerMetadata; - clientInformation: OAuthClientInformationMixed; - refreshToken: string; - resource?: URL; - addClientAuthentication?: OAuthClientProvider['addClientAuthentication']; - fetchFn?: FetchLike; -}): Promise; -/** - * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. - */ -export declare function registerClient(authorizationServerUrl: string | URL, { metadata, clientMetadata, fetchFn }: { - metadata?: AuthorizationServerMetadata; - clientMetadata: OAuthClientMetadata; - fetchFn?: FetchLike; -}): Promise; -export {}; -//# sourceMappingURL=auth.d.ts.map \ No newline at end of file diff --git a/dist/esm/client/auth.d.ts.map b/dist/esm/client/auth.d.ts.map deleted file mode 100644 index ef03546f80..0000000000 --- a/dist/esm/client/auth.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/client/auth.ts"],"names":[],"mappings":"AAEA,OAAO,EACH,mBAAmB,EAEnB,2BAA2B,EAC3B,WAAW,EACX,aAAa,EACb,0BAA0B,EAC1B,8BAA8B,EAE9B,2BAA2B,EAE9B,MAAM,mBAAmB,CAAC;AAQ3B,OAAO,EAKH,UAAU,EAGb,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;;;;;GAMG;AACH,MAAM,WAAW,mBAAmB;IAChC;;OAEG;IACH,IAAI,WAAW,IAAI,MAAM,GAAG,GAAG,CAAC;IAEhC;;OAEG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;OAEG;IACH,IAAI,cAAc,IAAI,mBAAmB,CAAC;IAE1C;;OAEG;IACH,KAAK,CAAC,IAAI,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAEnC;;;;OAIG;IACH,iBAAiB,IAAI,2BAA2B,GAAG,SAAS,GAAG,OAAO,CAAC,2BAA2B,GAAG,SAAS,CAAC,CAAC;IAEhH;;;;;;;OAOG;IACH,qBAAqB,CAAC,CAAC,iBAAiB,EAAE,2BAA2B,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EACd,OAAO,EACV,EAAE;IACC,QAAQ,CAAC,EAAE,2BAA2B,CAAC;IACvC,cAAc,EAAE,mBAAmB,CAAC;IACpC,OAAO,CAAC,EAAE,SAAS,CAAC;CACvB,GACF,OAAO,CAAC,0BAA0B,CAAC,CA0BrC"} \ No newline at end of file diff --git a/dist/esm/client/auth.js b/dist/esm/client/auth.js deleted file mode 100644 index 9c1daedfdf..0000000000 --- a/dist/esm/client/auth.js +++ /dev/null @@ -1,777 +0,0 @@ -import pkceChallenge from 'pkce-challenge'; -import { LATEST_PROTOCOL_VERSION } from '../types.js'; -import { OAuthErrorResponseSchema, OpenIdProviderDiscoveryMetadataSchema } from '../shared/auth.js'; -import { OAuthClientInformationFullSchema, OAuthMetadataSchema, OAuthProtectedResourceMetadataSchema, OAuthTokensSchema } from '../shared/auth.js'; -import { checkResourceAllowed, resourceUrlFromServerUrl } from '../shared/auth-utils.js'; -import { InvalidClientError, InvalidClientMetadataError, InvalidGrantError, OAUTH_ERRORS, OAuthError, ServerError, UnauthorizedClientError } from '../server/auth/errors.js'; -export class UnauthorizedError extends Error { - constructor(message) { - super(message !== null && message !== void 0 ? message : 'Unauthorized'); - } -} -function isClientAuthMethod(method) { - return ['client_secret_basic', 'client_secret_post', 'none'].includes(method); -} -const AUTHORIZATION_CODE_RESPONSE_TYPE = 'code'; -const AUTHORIZATION_CODE_CHALLENGE_METHOD = 'S256'; -/** - * Determines the best client authentication method to use based on server support and client configuration. - * - * Priority order (highest to lowest): - * 1. client_secret_basic (if client secret is available) - * 2. client_secret_post (if client secret is available) - * 3. none (for public clients) - * - * @param clientInformation - OAuth client information containing credentials - * @param supportedMethods - Authentication methods supported by the authorization server - * @returns The selected authentication method - */ -export function selectClientAuthMethod(clientInformation, supportedMethods) { - const hasClientSecret = clientInformation.client_secret !== undefined; - // If server doesn't specify supported methods, use RFC 6749 defaults - if (supportedMethods.length === 0) { - return hasClientSecret ? 'client_secret_post' : 'none'; - } - // Prefer the method returned by the server during client registration if valid and supported - if ('token_endpoint_auth_method' in clientInformation && - clientInformation.token_endpoint_auth_method && - isClientAuthMethod(clientInformation.token_endpoint_auth_method) && - supportedMethods.includes(clientInformation.token_endpoint_auth_method)) { - return clientInformation.token_endpoint_auth_method; - } - // Try methods in priority order (most secure first) - if (hasClientSecret && supportedMethods.includes('client_secret_basic')) { - return 'client_secret_basic'; - } - if (hasClientSecret && supportedMethods.includes('client_secret_post')) { - return 'client_secret_post'; - } - if (supportedMethods.includes('none')) { - return 'none'; - } - // Fallback: use what we have - return hasClientSecret ? 'client_secret_post' : 'none'; -} -/** - * Applies client authentication to the request based on the specified method. - * - * Implements OAuth 2.1 client authentication methods: - * - client_secret_basic: HTTP Basic authentication (RFC 6749 Section 2.3.1) - * - client_secret_post: Credentials in request body (RFC 6749 Section 2.3.1) - * - none: Public client authentication (RFC 6749 Section 2.1) - * - * @param method - The authentication method to use - * @param clientInformation - OAuth client information containing credentials - * @param headers - HTTP headers object to modify - * @param params - URL search parameters to modify - * @throws {Error} When required credentials are missing - */ -function applyClientAuthentication(method, clientInformation, headers, params) { - const { client_id, client_secret } = clientInformation; - switch (method) { - case 'client_secret_basic': - applyBasicAuth(client_id, client_secret, headers); - return; - case 'client_secret_post': - applyPostAuth(client_id, client_secret, params); - return; - case 'none': - applyPublicAuth(client_id, params); - return; - default: - throw new Error(`Unsupported client authentication method: ${method}`); - } -} -/** - * Applies HTTP Basic authentication (RFC 6749 Section 2.3.1) - */ -function applyBasicAuth(clientId, clientSecret, headers) { - if (!clientSecret) { - throw new Error('client_secret_basic authentication requires a client_secret'); - } - const credentials = btoa(`${clientId}:${clientSecret}`); - headers.set('Authorization', `Basic ${credentials}`); -} -/** - * Applies POST body authentication (RFC 6749 Section 2.3.1) - */ -function applyPostAuth(clientId, clientSecret, params) { - params.set('client_id', clientId); - if (clientSecret) { - params.set('client_secret', clientSecret); - } -} -/** - * Applies public client authentication (RFC 6749 Section 2.1) - */ -function applyPublicAuth(clientId, params) { - params.set('client_id', clientId); -} -/** - * Parses an OAuth error response from a string or Response object. - * - * If the input is a standard OAuth2.0 error response, it will be parsed according to the spec - * and an instance of the appropriate OAuthError subclass will be returned. - * If parsing fails, it falls back to a generic ServerError that includes - * the response status (if available) and original content. - * - * @param input - A Response object or string containing the error response - * @returns A Promise that resolves to an OAuthError instance - */ -export async function parseErrorResponse(input) { - const statusCode = input instanceof Response ? input.status : undefined; - const body = input instanceof Response ? await input.text() : input; - try { - const result = OAuthErrorResponseSchema.parse(JSON.parse(body)); - const { error, error_description, error_uri } = result; - const errorClass = OAUTH_ERRORS[error] || ServerError; - return new errorClass(error_description || '', error_uri); - } - catch (error) { - // Not a valid OAuth error response, but try to inform the user of the raw data anyway - const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ''}Invalid OAuth error response: ${error}. Raw body: ${body}`; - return new ServerError(errorMessage); - } -} -/** - * Orchestrates the full auth flow with a server. - * - * This can be used as a single entry point for all authorization functionality, - * instead of linking together the other lower-level functions in this module. - */ -export async function auth(provider, options) { - var _a, _b; - try { - return await authInternal(provider, options); - } - catch (error) { - // Handle recoverable error types by invalidating credentials and retrying - if (error instanceof InvalidClientError || error instanceof UnauthorizedClientError) { - await ((_a = provider.invalidateCredentials) === null || _a === void 0 ? void 0 : _a.call(provider, 'all')); - return await authInternal(provider, options); - } - else if (error instanceof InvalidGrantError) { - await ((_b = provider.invalidateCredentials) === null || _b === void 0 ? void 0 : _b.call(provider, 'tokens')); - return await authInternal(provider, options); - } - // Throw otherwise - throw error; - } -} -async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) { - var _a, _b; - let resourceMetadata; - let authorizationServerUrl; - try { - resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl }, fetchFn); - if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) { - authorizationServerUrl = resourceMetadata.authorization_servers[0]; - } - } - catch (_c) { - // Ignore errors and fall back to /.well-known/oauth-authorization-server - } - /** - * If we don't get a valid authorization server metadata from protected resource metadata, - * fallback to the legacy MCP spec's implementation (version 2025-03-26): MCP server base URL acts as the Authorization server. - */ - if (!authorizationServerUrl) { - authorizationServerUrl = new URL('/', serverUrl); - } - const resource = await selectResourceURL(serverUrl, provider, resourceMetadata); - const metadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { - fetchFn - }); - // Handle client registration if needed - let clientInformation = await Promise.resolve(provider.clientInformation()); - if (!clientInformation) { - if (authorizationCode !== undefined) { - throw new Error('Existing OAuth client information is required when exchanging an authorization code'); - } - const supportsUrlBasedClientId = (metadata === null || metadata === void 0 ? void 0 : metadata.client_id_metadata_document_supported) === true; - const clientMetadataUrl = provider.clientMetadataUrl; - if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) { - throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`); - } - const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl; - if (shouldUseUrlBasedClientId) { - // SEP-991: URL-based Client IDs - clientInformation = { - client_id: clientMetadataUrl - }; - await ((_a = provider.saveClientInformation) === null || _a === void 0 ? void 0 : _a.call(provider, clientInformation)); - } - else { - // Fallback to dynamic registration - if (!provider.saveClientInformation) { - throw new Error('OAuth client information must be saveable for dynamic registration'); - } - const fullInformation = await registerClient(authorizationServerUrl, { - metadata, - clientMetadata: provider.clientMetadata, - fetchFn - }); - await provider.saveClientInformation(fullInformation); - clientInformation = fullInformation; - } - } - // Exchange authorization code for tokens - if (authorizationCode !== undefined) { - const codeVerifier = await provider.codeVerifier(); - const tokens = await exchangeAuthorization(authorizationServerUrl, { - metadata, - clientInformation, - authorizationCode, - codeVerifier, - redirectUri: provider.redirectUrl, - resource, - addClientAuthentication: provider.addClientAuthentication, - fetchFn: fetchFn - }); - await provider.saveTokens(tokens); - return 'AUTHORIZED'; - } - const tokens = await provider.tokens(); - // Handle token refresh or new authorization - if (tokens === null || tokens === void 0 ? void 0 : tokens.refresh_token) { - try { - // Attempt to refresh the token - const newTokens = await refreshAuthorization(authorizationServerUrl, { - metadata, - clientInformation, - refreshToken: tokens.refresh_token, - resource, - addClientAuthentication: provider.addClientAuthentication, - fetchFn - }); - await provider.saveTokens(newTokens); - return 'AUTHORIZED'; - } - catch (error) { - // If this is a ServerError, or an unknown type, log it out and try to continue. Otherwise, escalate so we can fix things and retry. - if (!(error instanceof OAuthError) || error instanceof ServerError) { - // Could not refresh OAuth tokens - } - else { - // Refresh failed for another reason, re-throw - throw error; - } - } - } - const state = provider.state ? await provider.state() : undefined; - // Start new authorization flow - const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, { - metadata, - clientInformation, - state, - redirectUrl: provider.redirectUrl, - scope: scope || ((_b = resourceMetadata === null || resourceMetadata === void 0 ? void 0 : resourceMetadata.scopes_supported) === null || _b === void 0 ? void 0 : _b.join(' ')) || provider.clientMetadata.scope, - resource - }); - await provider.saveCodeVerifier(codeVerifier); - await provider.redirectToAuthorization(authorizationUrl); - return 'REDIRECT'; -} -/** - * SEP-991: URL-based Client IDs - * Validate that the client_id is a valid URL with https scheme - */ -export function isHttpsUrl(value) { - if (!value) - return false; - try { - const url = new URL(value); - return url.protocol === 'https:' && url.pathname !== '/'; - } - catch (_a) { - return false; - } -} -export async function selectResourceURL(serverUrl, provider, resourceMetadata) { - const defaultResource = resourceUrlFromServerUrl(serverUrl); - // If provider has custom validation, delegate to it - if (provider.validateResourceURL) { - return await provider.validateResourceURL(defaultResource, resourceMetadata === null || resourceMetadata === void 0 ? void 0 : resourceMetadata.resource); - } - // Only include resource parameter when Protected Resource Metadata is present - if (!resourceMetadata) { - return undefined; - } - // Validate that the metadata's resource is compatible with our request - if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) { - throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`); - } - // Prefer the resource from metadata since it's what the server is telling us to request - return new URL(resourceMetadata.resource); -} -/** - * Extract resource_metadata, scope, and error from WWW-Authenticate header. - */ -export function extractWWWAuthenticateParams(res) { - const authenticateHeader = res.headers.get('WWW-Authenticate'); - if (!authenticateHeader) { - return {}; - } - const [type, scheme] = authenticateHeader.split(' '); - if (type.toLowerCase() !== 'bearer' || !scheme) { - return {}; - } - const resourceMetadataMatch = extractFieldFromWwwAuth(res, 'resource_metadata') || undefined; - let resourceMetadataUrl; - if (resourceMetadataMatch) { - try { - resourceMetadataUrl = new URL(resourceMetadataMatch); - } - catch (_a) { - // Ignore invalid URL - } - } - const scope = extractFieldFromWwwAuth(res, 'scope') || undefined; - const error = extractFieldFromWwwAuth(res, 'error') || undefined; - return { - resourceMetadataUrl, - scope, - error - }; -} -/** - * Extracts a specific field's value from the WWW-Authenticate header string. - * - * @param response The HTTP response object containing the headers. - * @param fieldName The name of the field to extract (e.g., "realm", "nonce"). - * @returns The field value - */ -function extractFieldFromWwwAuth(response, fieldName) { - const wwwAuthHeader = response.headers.get('WWW-Authenticate'); - if (!wwwAuthHeader) { - return null; - } - const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`); - const match = wwwAuthHeader.match(pattern); - if (match) { - // Pattern matches: field_name="value" or field_name=value (unquoted) - return match[1] || match[2]; - } - return null; -} -/** - * Extract resource_metadata from response header. - * @deprecated Use `extractWWWAuthenticateParams` instead. - */ -export function extractResourceMetadataUrl(res) { - const authenticateHeader = res.headers.get('WWW-Authenticate'); - if (!authenticateHeader) { - return undefined; - } - const [type, scheme] = authenticateHeader.split(' '); - if (type.toLowerCase() !== 'bearer' || !scheme) { - return undefined; - } - const regex = /resource_metadata="([^"]*)"/; - const match = regex.exec(authenticateHeader); - if (!match) { - return undefined; - } - try { - return new URL(match[1]); - } - catch (_a) { - return undefined; - } -} -/** - * Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata. - * - * If the server returns a 404 for the well-known endpoint, this function will - * return `undefined`. Any other errors will be thrown as exceptions. - */ -export async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) { - const response = await discoverMetadataWithFallback(serverUrl, 'oauth-protected-resource', fetchFn, { - protocolVersion: opts === null || opts === void 0 ? void 0 : opts.protocolVersion, - metadataUrl: opts === null || opts === void 0 ? void 0 : opts.resourceMetadataUrl - }); - if (!response || response.status === 404) { - throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`); - } - if (!response.ok) { - throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`); - } - return OAuthProtectedResourceMetadataSchema.parse(await response.json()); -} -/** - * Helper function to handle fetch with CORS retry logic - */ -async function fetchWithCorsRetry(url, headers, fetchFn = fetch) { - try { - return await fetchFn(url, { headers }); - } - catch (error) { - if (error instanceof TypeError) { - if (headers) { - // CORS errors come back as TypeError, retry without headers - return fetchWithCorsRetry(url, undefined, fetchFn); - } - else { - // We're getting CORS errors on retry too, return undefined - return undefined; - } - } - throw error; - } -} -/** - * Constructs the well-known path for auth-related metadata discovery - */ -function buildWellKnownPath(wellKnownPrefix, pathname = '', options = {}) { - // Strip trailing slash from pathname to avoid double slashes - if (pathname.endsWith('/')) { - pathname = pathname.slice(0, -1); - } - return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`; -} -/** - * Tries to discover OAuth metadata at a specific URL - */ -async function tryMetadataDiscovery(url, protocolVersion, fetchFn = fetch) { - const headers = { - 'MCP-Protocol-Version': protocolVersion - }; - return await fetchWithCorsRetry(url, headers, fetchFn); -} -/** - * Determines if fallback to root discovery should be attempted - */ -function shouldAttemptFallback(response, pathname) { - return !response || (response.status >= 400 && response.status < 500 && pathname !== '/'); -} -/** - * Generic function for discovering OAuth metadata with fallback support - */ -async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) { - var _a, _b; - const issuer = new URL(serverUrl); - const protocolVersion = (_a = opts === null || opts === void 0 ? void 0 : opts.protocolVersion) !== null && _a !== void 0 ? _a : LATEST_PROTOCOL_VERSION; - let url; - if (opts === null || opts === void 0 ? void 0 : opts.metadataUrl) { - url = new URL(opts.metadataUrl); - } - else { - // Try path-aware discovery first - const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname); - url = new URL(wellKnownPath, (_b = opts === null || opts === void 0 ? void 0 : opts.metadataServerUrl) !== null && _b !== void 0 ? _b : issuer); - url.search = issuer.search; - } - let response = await tryMetadataDiscovery(url, protocolVersion, fetchFn); - // If path-aware discovery fails with 404 and we're not already at root, try fallback to root discovery - if (!(opts === null || opts === void 0 ? void 0 : opts.metadataUrl) && shouldAttemptFallback(response, issuer.pathname)) { - const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer); - response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn); - } - return response; -} -/** - * Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata. - * - * If the server returns a 404 for the well-known endpoint, this function will - * return `undefined`. Any other errors will be thrown as exceptions. - * - * @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`. - */ -export async function discoverOAuthMetadata(issuer, { authorizationServerUrl, protocolVersion } = {}, fetchFn = fetch) { - if (typeof issuer === 'string') { - issuer = new URL(issuer); - } - if (!authorizationServerUrl) { - authorizationServerUrl = issuer; - } - if (typeof authorizationServerUrl === 'string') { - authorizationServerUrl = new URL(authorizationServerUrl); - } - protocolVersion !== null && protocolVersion !== void 0 ? protocolVersion : (protocolVersion = LATEST_PROTOCOL_VERSION); - const response = await discoverMetadataWithFallback(authorizationServerUrl, 'oauth-authorization-server', fetchFn, { - protocolVersion, - metadataServerUrl: authorizationServerUrl - }); - if (!response || response.status === 404) { - return undefined; - } - if (!response.ok) { - throw new Error(`HTTP ${response.status} trying to load well-known OAuth metadata`); - } - return OAuthMetadataSchema.parse(await response.json()); -} -/** - * Builds a list of discovery URLs to try for authorization server metadata. - * URLs are returned in priority order: - * 1. OAuth metadata at the given URL - * 2. OIDC metadata endpoints at the given URL - */ -export function buildDiscoveryUrls(authorizationServerUrl) { - const url = typeof authorizationServerUrl === 'string' ? new URL(authorizationServerUrl) : authorizationServerUrl; - const hasPath = url.pathname !== '/'; - const urlsToTry = []; - if (!hasPath) { - // Root path: https://example.com/.well-known/oauth-authorization-server - urlsToTry.push({ - url: new URL('/.well-known/oauth-authorization-server', url.origin), - type: 'oauth' - }); - // OIDC: https://example.com/.well-known/openid-configuration - urlsToTry.push({ - url: new URL(`/.well-known/openid-configuration`, url.origin), - type: 'oidc' - }); - return urlsToTry; - } - // Strip trailing slash from pathname to avoid double slashes - let pathname = url.pathname; - if (pathname.endsWith('/')) { - pathname = pathname.slice(0, -1); - } - // 1. OAuth metadata at the given URL - // Insert well-known before the path: https://example.com/.well-known/oauth-authorization-server/tenant1 - urlsToTry.push({ - url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url.origin), - type: 'oauth' - }); - // 2. OIDC metadata endpoints - // RFC 8414 style: Insert /.well-known/openid-configuration before the path - urlsToTry.push({ - url: new URL(`/.well-known/openid-configuration${pathname}`, url.origin), - type: 'oidc' - }); - // OIDC Discovery 1.0 style: Append /.well-known/openid-configuration after the path - urlsToTry.push({ - url: new URL(`${pathname}/.well-known/openid-configuration`, url.origin), - type: 'oidc' - }); - return urlsToTry; -} -/** - * Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata - * and OpenID Connect Discovery 1.0 specifications. - * - * This function implements a fallback strategy for authorization server discovery: - * 1. Attempts RFC 8414 OAuth metadata discovery first - * 2. If OAuth discovery fails, falls back to OpenID Connect Discovery - * - * @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's - * protected resource metadata, or the MCP server's URL if the - * metadata was not found. - * @param options - Configuration options - * @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch - * @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION - * @returns Promise resolving to authorization server metadata, or undefined if discovery fails - */ -export async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) { - const headers = { - 'MCP-Protocol-Version': protocolVersion, - Accept: 'application/json' - }; - // Get the list of URLs to try - const urlsToTry = buildDiscoveryUrls(authorizationServerUrl); - // Try each URL in order - for (const { url: endpointUrl, type } of urlsToTry) { - const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn); - if (!response) { - /** - * CORS error occurred - don't throw as the endpoint may not allow CORS, - * continue trying other possible endpoints - */ - continue; - } - if (!response.ok) { - // Continue looking for any 4xx response code. - if (response.status >= 400 && response.status < 500) { - continue; // Try next URL - } - throw new Error(`HTTP ${response.status} trying to load ${type === 'oauth' ? 'OAuth' : 'OpenID provider'} metadata from ${endpointUrl}`); - } - // Parse and validate based on type - if (type === 'oauth') { - return OAuthMetadataSchema.parse(await response.json()); - } - else { - return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json()); - } - } - return undefined; -} -/** - * Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL. - */ -export async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) { - let authorizationUrl; - if (metadata) { - authorizationUrl = new URL(metadata.authorization_endpoint); - if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) { - throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`); - } - if (metadata.code_challenge_methods_supported && - !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) { - throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`); - } - } - else { - authorizationUrl = new URL('/authorize', authorizationServerUrl); - } - // Generate PKCE challenge - const challenge = await pkceChallenge(); - const codeVerifier = challenge.code_verifier; - const codeChallenge = challenge.code_challenge; - authorizationUrl.searchParams.set('response_type', AUTHORIZATION_CODE_RESPONSE_TYPE); - authorizationUrl.searchParams.set('client_id', clientInformation.client_id); - authorizationUrl.searchParams.set('code_challenge', codeChallenge); - authorizationUrl.searchParams.set('code_challenge_method', AUTHORIZATION_CODE_CHALLENGE_METHOD); - authorizationUrl.searchParams.set('redirect_uri', String(redirectUrl)); - if (state) { - authorizationUrl.searchParams.set('state', state); - } - if (scope) { - authorizationUrl.searchParams.set('scope', scope); - } - if (scope === null || scope === void 0 ? void 0 : scope.includes('offline_access')) { - // if the request includes the OIDC-only "offline_access" scope, - // we need to set the prompt to "consent" to ensure the user is prompted to grant offline access - // https://openid.net/specs/openid-connect-core-1_0.html#OfflineAccess - authorizationUrl.searchParams.append('prompt', 'consent'); - } - if (resource) { - authorizationUrl.searchParams.set('resource', resource.href); - } - return { authorizationUrl, codeVerifier }; -} -/** - * Exchanges an authorization code for an access token with the given server. - * - * Supports multiple client authentication methods as specified in OAuth 2.1: - * - Automatically selects the best authentication method based on server support - * - Falls back to appropriate defaults when server metadata is unavailable - * - * @param authorizationServerUrl - The authorization server's base URL - * @param options - Configuration object containing client info, auth code, etc. - * @returns Promise resolving to OAuth tokens - * @throws {Error} When token exchange fails or authentication is invalid - */ -export async function exchangeAuthorization(authorizationServerUrl, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }) { - var _a; - const grantType = 'authorization_code'; - const tokenUrl = (metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL('/token', authorizationServerUrl); - if ((metadata === null || metadata === void 0 ? void 0 : metadata.grant_types_supported) && !metadata.grant_types_supported.includes(grantType)) { - throw new Error(`Incompatible auth server: does not support grant type ${grantType}`); - } - // Exchange code for tokens - const headers = new Headers({ - 'Content-Type': 'application/x-www-form-urlencoded', - Accept: 'application/json' - }); - const params = new URLSearchParams({ - grant_type: grantType, - code: authorizationCode, - code_verifier: codeVerifier, - redirect_uri: String(redirectUri) - }); - if (addClientAuthentication) { - addClientAuthentication(headers, params, authorizationServerUrl, metadata); - } - else { - // Determine and apply client authentication method - const supportedMethods = (_a = metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint_auth_methods_supported) !== null && _a !== void 0 ? _a : []; - const authMethod = selectClientAuthMethod(clientInformation, supportedMethods); - applyClientAuthentication(authMethod, clientInformation, headers, params); - } - if (resource) { - params.set('resource', resource.href); - } - const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, { - method: 'POST', - headers, - body: params - }); - if (!response.ok) { - throw await parseErrorResponse(response); - } - return OAuthTokensSchema.parse(await response.json()); -} -/** - * Exchange a refresh token for an updated access token. - * - * Supports multiple client authentication methods as specified in OAuth 2.1: - * - Automatically selects the best authentication method based on server support - * - Preserves the original refresh token if a new one is not returned - * - * @param authorizationServerUrl - The authorization server's base URL - * @param options - Configuration object containing client info, refresh token, etc. - * @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced) - * @throws {Error} When token refresh fails or authentication is invalid - */ -export async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) { - var _a; - const grantType = 'refresh_token'; - let tokenUrl; - if (metadata) { - tokenUrl = new URL(metadata.token_endpoint); - if (metadata.grant_types_supported && !metadata.grant_types_supported.includes(grantType)) { - throw new Error(`Incompatible auth server: does not support grant type ${grantType}`); - } - } - else { - tokenUrl = new URL('/token', authorizationServerUrl); - } - // Exchange refresh token - const headers = new Headers({ - 'Content-Type': 'application/x-www-form-urlencoded' - }); - const params = new URLSearchParams({ - grant_type: grantType, - refresh_token: refreshToken - }); - if (addClientAuthentication) { - addClientAuthentication(headers, params, authorizationServerUrl, metadata); - } - else { - // Determine and apply client authentication method - const supportedMethods = (_a = metadata === null || metadata === void 0 ? void 0 : metadata.token_endpoint_auth_methods_supported) !== null && _a !== void 0 ? _a : []; - const authMethod = selectClientAuthMethod(clientInformation, supportedMethods); - applyClientAuthentication(authMethod, clientInformation, headers, params); - } - if (resource) { - params.set('resource', resource.href); - } - const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(tokenUrl, { - method: 'POST', - headers, - body: params - }); - if (!response.ok) { - throw await parseErrorResponse(response); - } - return OAuthTokensSchema.parse({ refresh_token: refreshToken, ...(await response.json()) }); -} -/** - * Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591. - */ -export async function registerClient(authorizationServerUrl, { metadata, clientMetadata, fetchFn }) { - let registrationUrl; - if (metadata) { - if (!metadata.registration_endpoint) { - throw new Error('Incompatible auth server: does not support dynamic client registration'); - } - registrationUrl = new URL(metadata.registration_endpoint); - } - else { - registrationUrl = new URL('/register', authorizationServerUrl); - } - const response = await (fetchFn !== null && fetchFn !== void 0 ? fetchFn : fetch)(registrationUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(clientMetadata) - }); - if (!response.ok) { - throw await parseErrorResponse(response); - } - return OAuthClientInformationFullSchema.parse(await response.json()); -} -//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/dist/esm/client/auth.js.map b/dist/esm/client/auth.js.map deleted file mode 100644 index a778750d04..0000000000 --- a/dist/esm/client/auth.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/client/auth.ts"],"names":[],"mappings":"AAAA,OAAO,aAAa,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AACtD,OAAO,EAQH,wBAAwB,EAExB,qCAAqC,EACxC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACH,gCAAgC,EAChC,mBAAmB,EACnB,oCAAoC,EACpC,iBAAiB,EACpB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AACzF,OAAO,EACH,kBAAkB,EAClB,0BAA0B,EAC1B,iBAAiB,EACjB,YAAY,EACZ,UAAU,EACV,WAAW,EACX,uBAAuB,EAC1B,MAAM,0BAA0B,CAAC;AAyHlC,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IACxC,YAAY,OAAgB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AAc,CAAC;KACvC,CAAC,CAAC;IAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACf,MAAM,MAAM,kBAAkB,CAAC,QAAQ,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,gCAAgC,CAAC,KAAK,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;AACzE,CAAC"} \ No newline at end of file diff --git a/dist/esm/client/index.d.ts b/dist/esm/client/index.d.ts deleted file mode 100644 index 03148dd89b..0000000000 --- a/dist/esm/client/index.d.ts +++ /dev/null @@ -1,379 +0,0 @@ -import { Protocol, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; -import type { Transport } from '../shared/transport.js'; -import { type CallToolRequest, CallToolResultSchema, type ClientCapabilities, type ClientNotification, type ClientRequest, type ClientResult, type CompatibilityCallToolResultSchema, type CompleteRequest, type GetPromptRequest, type Implementation, type ListPromptsRequest, type ListResourcesRequest, type ListResourceTemplatesRequest, type ListToolsRequest, type LoggingLevel, type Notification, type ReadResourceRequest, type Request, type Result, type ServerCapabilities, type SubscribeRequest, type UnsubscribeRequest } from '../types.js'; -import type { jsonSchemaValidator } from '../validation/types.js'; -import { AnyObjectSchema, SchemaOutput } from '../server/zod-compat.js'; -import type { RequestHandlerExtra } from '../shared/protocol.js'; -/** - * Determines which elicitation modes are supported based on declared client capabilities. - * - * According to the spec: - * - An empty elicitation capability object defaults to form mode support (backwards compatibility) - * - URL mode is only supported if explicitly declared - * - * @param capabilities - The client's elicitation capabilities - * @returns An object indicating which modes are supported - */ -export declare function getSupportedElicitationModes(capabilities: ClientCapabilities['elicitation']): { - supportsFormMode: boolean; - supportsUrlMode: boolean; -}; -export type ClientOptions = ProtocolOptions & { - /** - * Capabilities to advertise as being supported by this client. - */ - capabilities?: ClientCapabilities; - /** - * JSON Schema validator for tool output validation. - * - * The validator is used to validate structured content returned by tools - * against their declared output schemas. - * - * @default AjvJsonSchemaValidator - * - * @example - * ```typescript - * // ajv - * const client = new Client( - * { name: 'my-client', version: '1.0.0' }, - * { - * capabilities: {}, - * jsonSchemaValidator: new AjvJsonSchemaValidator() - * } - * ); - * - * // @cfworker/json-schema - * const client = new Client( - * { name: 'my-client', version: '1.0.0' }, - * { - * capabilities: {}, - * jsonSchemaValidator: new CfWorkerJsonSchemaValidator() - * } - * ); - * ``` - */ - jsonSchemaValidator?: jsonSchemaValidator; -}; -/** - * An MCP client on top of a pluggable transport. - * - * The client will automatically begin the initialization flow with the server when connect() is called. - * - * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: - * - * ```typescript - * // Custom schemas - * const CustomRequestSchema = RequestSchema.extend({...}) - * const CustomNotificationSchema = NotificationSchema.extend({...}) - * const CustomResultSchema = ResultSchema.extend({...}) - * - * // Type aliases - * type CustomRequest = z.infer - * type CustomNotification = z.infer - * type CustomResult = z.infer - * - * // Create typed client - * const client = new Client({ - * name: "CustomClient", - * version: "1.0.0" - * }) - * ``` - */ -export declare class Client extends Protocol { - private _clientInfo; - private _serverCapabilities?; - private _serverVersion?; - private _capabilities; - private _instructions?; - private _jsonSchemaValidator; - private _cachedToolOutputValidators; - /** - * Initializes this client with the given name and version information. - */ - constructor(_clientInfo: Implementation, options?: ClientOptions); - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - registerCapabilities(capabilities: ClientCapabilities): void; - /** - * Override request handler registration to enforce client-side validation for elicitation. - */ - setRequestHandler(requestSchema: T, handler: (request: SchemaOutput, extra: RequestHandlerExtra) => ClientResult | ResultT | Promise): void; - protected assertCapability(capability: keyof ServerCapabilities, method: string): void; - connect(transport: Transport, options?: RequestOptions): Promise; - /** - * After initialization has completed, this will be populated with the server's reported capabilities. - */ - getServerCapabilities(): ServerCapabilities | undefined; - /** - * After initialization has completed, this will be populated with information about the server's name and version. - */ - getServerVersion(): Implementation | undefined; - /** - * After initialization has completed, this may be populated with information about the server's instructions. - */ - getInstructions(): string | undefined; - protected assertCapabilityForMethod(method: RequestT['method']): void; - protected assertNotificationCapability(method: NotificationT['method']): void; - protected assertRequestHandlerCapability(method: string): void; - ping(options?: RequestOptions): Promise<{ - _meta?: Record | undefined; - }>; - complete(params: CompleteRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - completion: { - [x: string]: unknown; - values: string[]; - total?: number | undefined; - hasMore?: boolean | undefined; - }; - _meta?: Record | undefined; - }>; - setLoggingLevel(level: LoggingLevel, options?: RequestOptions): Promise<{ - _meta?: Record | undefined; - }>; - getPrompt(params: GetPromptRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - messages: { - role: "user" | "assistant"; - content: { - type: "text"; - text: string; - _meta?: Record | undefined; - } | { - type: "image"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "audio"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "resource"; - resource: { - uri: string; - text: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - } | { - uri: string; - blob: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - }; - _meta?: Record | undefined; - } | { - uri: string; - name: string; - type: "resource_link"; - description?: string | undefined; - mimeType?: string | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - }; - }[]; - _meta?: Record | undefined; - description?: string | undefined; - }>; - listPrompts(params?: ListPromptsRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - prompts: { - name: string; - description?: string | undefined; - arguments?: { - name: string; - description?: string | undefined; - required?: boolean | undefined; - }[] | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - }[]; - _meta?: Record | undefined; - nextCursor?: string | undefined; - }>; - listResources(params?: ListResourcesRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - resources: { - uri: string; - name: string; - description?: string | undefined; - mimeType?: string | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - }[]; - _meta?: Record | undefined; - nextCursor?: string | undefined; - }>; - listResourceTemplates(params?: ListResourceTemplatesRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - resourceTemplates: { - uriTemplate: string; - name: string; - description?: string | undefined; - mimeType?: string | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - }[]; - _meta?: Record | undefined; - nextCursor?: string | undefined; - }>; - readResource(params: ReadResourceRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - contents: ({ - uri: string; - text: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - } | { - uri: string; - blob: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - })[]; - _meta?: Record | undefined; - }>; - subscribeResource(params: SubscribeRequest['params'], options?: RequestOptions): Promise<{ - _meta?: Record | undefined; - }>; - unsubscribeResource(params: UnsubscribeRequest['params'], options?: RequestOptions): Promise<{ - _meta?: Record | undefined; - }>; - callTool(params: CallToolRequest['params'], resultSchema?: typeof CallToolResultSchema | typeof CompatibilityCallToolResultSchema, options?: RequestOptions): Promise<{ - [x: string]: unknown; - content: ({ - type: "text"; - text: string; - _meta?: Record | undefined; - } | { - type: "image"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "audio"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "resource"; - resource: { - uri: string; - text: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - } | { - uri: string; - blob: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - }; - _meta?: Record | undefined; - } | { - uri: string; - name: string; - type: "resource_link"; - description?: string | undefined; - mimeType?: string | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - })[]; - _meta?: Record | undefined; - structuredContent?: Record | undefined; - isError?: boolean | undefined; - } | { - [x: string]: unknown; - toolResult: unknown; - _meta?: Record | undefined; - }>; - /** - * Cache validators for tool output schemas. - * Called after listTools() to pre-compile validators for better performance. - */ - private cacheToolOutputSchemas; - /** - * Get cached validator for a tool - */ - private getToolOutputValidator; - listTools(params?: ListToolsRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - tools: { - inputSchema: { - [x: string]: unknown; - type: "object"; - properties?: Record | undefined; - required?: string[] | undefined; - }; - name: string; - description?: string | undefined; - outputSchema?: { - [x: string]: unknown; - type: "object"; - properties?: Record | undefined; - required?: string[] | undefined; - } | undefined; - annotations?: { - title?: string | undefined; - readOnlyHint?: boolean | undefined; - destructiveHint?: boolean | undefined; - idempotentHint?: boolean | undefined; - openWorldHint?: boolean | undefined; - } | undefined; - securitySchemes?: ({ - type: "noauth"; - } | { - type: "oauth2"; - scopes?: string[] | undefined; - })[] | undefined; - _meta?: Record | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - }[]; - _meta?: Record | undefined; - nextCursor?: string | undefined; - }>; - sendRootsListChanged(): Promise; -} -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/esm/client/index.d.ts.map b/dist/esm/client/index.d.ts.map deleted file mode 100644 index c19d4ef588..0000000000 --- a/dist/esm/client/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAAE,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC/G,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,EACH,KAAK,eAAe,EACpB,oBAAoB,EACpB,KAAK,kBAAkB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;;IA0C5B;;;OAGG;IACH,OAAO,CAAC,sBAAsB;IAY9B;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAIxB,SAAS,CAAC,MAAM,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IASvE,oBAAoB;CAG7B"} \ No newline at end of file diff --git a/dist/esm/client/index.js b/dist/esm/client/index.js deleted file mode 100644 index 73a55e6afe..0000000000 --- a/dist/esm/client/index.js +++ /dev/null @@ -1,418 +0,0 @@ -import { mergeCapabilities, Protocol } from '../shared/protocol.js'; -import { CallToolResultSchema, CompleteResultSchema, EmptyResultSchema, ErrorCode, GetPromptResultSchema, InitializeResultSchema, LATEST_PROTOCOL_VERSION, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ListToolsResultSchema, McpError, ReadResourceResultSchema, SUPPORTED_PROTOCOL_VERSIONS, ElicitResultSchema, ElicitRequestSchema } from '../types.js'; -import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; -import { getObjectShape, isZ4Schema, safeParse } from '../server/zod-compat.js'; -/** - * Elicitation default application helper. Applies defaults to the data based on the schema. - * - * @param schema - The schema to apply defaults to. - * @param data - The data to apply defaults to. - */ -function applyElicitationDefaults(schema, data) { - if (!schema || data === null || typeof data !== 'object') - return; - // Handle object properties - if (schema.type === 'object' && schema.properties && typeof schema.properties === 'object') { - const obj = data; - const props = schema.properties; - for (const key of Object.keys(props)) { - const propSchema = props[key]; - // If missing or explicitly undefined, apply default if present - if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) { - obj[key] = propSchema.default; - } - // Recurse into existing nested objects/arrays - if (obj[key] !== undefined) { - applyElicitationDefaults(propSchema, obj[key]); - } - } - } - if (Array.isArray(schema.anyOf)) { - for (const sub of schema.anyOf) { - applyElicitationDefaults(sub, data); - } - } - // Combine schemas - if (Array.isArray(schema.oneOf)) { - for (const sub of schema.oneOf) { - applyElicitationDefaults(sub, data); - } - } -} -/** - * Determines which elicitation modes are supported based on declared client capabilities. - * - * According to the spec: - * - An empty elicitation capability object defaults to form mode support (backwards compatibility) - * - URL mode is only supported if explicitly declared - * - * @param capabilities - The client's elicitation capabilities - * @returns An object indicating which modes are supported - */ -export function getSupportedElicitationModes(capabilities) { - if (!capabilities) { - return { supportsFormMode: false, supportsUrlMode: false }; - } - const hasFormCapability = capabilities.form !== undefined; - const hasUrlCapability = capabilities.url !== undefined; - // If neither form nor url are explicitly declared, form mode is supported (backwards compatibility) - const supportsFormMode = hasFormCapability || (!hasFormCapability && !hasUrlCapability); - const supportsUrlMode = hasUrlCapability; - return { supportsFormMode, supportsUrlMode }; -} -/** - * An MCP client on top of a pluggable transport. - * - * The client will automatically begin the initialization flow with the server when connect() is called. - * - * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: - * - * ```typescript - * // Custom schemas - * const CustomRequestSchema = RequestSchema.extend({...}) - * const CustomNotificationSchema = NotificationSchema.extend({...}) - * const CustomResultSchema = ResultSchema.extend({...}) - * - * // Type aliases - * type CustomRequest = z.infer - * type CustomNotification = z.infer - * type CustomResult = z.infer - * - * // Create typed client - * const client = new Client({ - * name: "CustomClient", - * version: "1.0.0" - * }) - * ``` - */ -export class Client extends Protocol { - /** - * Initializes this client with the given name and version information. - */ - constructor(_clientInfo, options) { - var _a, _b; - super(options); - this._clientInfo = _clientInfo; - this._cachedToolOutputValidators = new Map(); - this._capabilities = (_a = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a !== void 0 ? _a : {}; - this._jsonSchemaValidator = (_b = options === null || options === void 0 ? void 0 : options.jsonSchemaValidator) !== null && _b !== void 0 ? _b : new AjvJsonSchemaValidator(); - } - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - registerCapabilities(capabilities) { - if (this.transport) { - throw new Error('Cannot register capabilities after connecting to transport'); - } - this._capabilities = mergeCapabilities(this._capabilities, capabilities); - } - /** - * Override request handler registration to enforce client-side validation for elicitation. - */ - setRequestHandler(requestSchema, handler) { - var _a, _b, _c; - const shape = getObjectShape(requestSchema); - const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method; - if (!methodSchema) { - throw new Error('Schema is missing a method literal'); - } - // Extract literal value using type-safe property access - let methodValue; - if (isZ4Schema(methodSchema)) { - const v4Schema = methodSchema; - const v4Def = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def; - methodValue = (_b = v4Def === null || v4Def === void 0 ? void 0 : v4Def.value) !== null && _b !== void 0 ? _b : v4Schema.value; - } - else { - const v3Schema = methodSchema; - const legacyDef = v3Schema._def; - methodValue = (_c = legacyDef === null || legacyDef === void 0 ? void 0 : legacyDef.value) !== null && _c !== void 0 ? _c : v3Schema.value; - } - if (typeof methodValue !== 'string') { - throw new Error('Schema method literal must be a string'); - } - const method = methodValue; - if (method === 'elicitation/create') { - const wrappedHandler = async (request, extra) => { - var _a, _b; - const validatedRequest = safeParse(ElicitRequestSchema, request); - if (!validatedRequest.success) { - // Type guard: if success is false, error is guaranteed to exist - const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); - throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`); - } - const { params } = validatedRequest.data; - const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation); - if (params.mode === 'form' && !supportsFormMode) { - throw new McpError(ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests'); - } - if (params.mode === 'url' && !supportsUrlMode) { - throw new McpError(ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests'); - } - const result = await Promise.resolve(handler(request, extra)); - const validationResult = safeParse(ElicitResultSchema, result); - if (!validationResult.success) { - // Type guard: if success is false, error is guaranteed to exist - const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); - throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`); - } - const validatedResult = validationResult.data; - const requestedSchema = params.mode === 'form' ? params.requestedSchema : undefined; - if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) { - if ((_b = (_a = this._capabilities.elicitation) === null || _a === void 0 ? void 0 : _a.form) === null || _b === void 0 ? void 0 : _b.applyDefaults) { - try { - applyElicitationDefaults(requestedSchema, validatedResult.content); - } - catch (_c) { - // gracefully ignore errors in default application - } - } - } - return validatedResult; - }; - // Install the wrapped handler - return super.setRequestHandler(requestSchema, wrappedHandler); - } - // Non-elicitation handlers use default behavior - return super.setRequestHandler(requestSchema, handler); - } - assertCapability(capability, method) { - var _a; - if (!((_a = this._serverCapabilities) === null || _a === void 0 ? void 0 : _a[capability])) { - throw new Error(`Server does not support ${capability} (required for ${method})`); - } - } - async connect(transport, options) { - await super.connect(transport); - // When transport sessionId is already set this means we are trying to reconnect. - // In this case we don't need to initialize again. - if (transport.sessionId !== undefined) { - return; - } - try { - const result = await this.request({ - method: 'initialize', - params: { - protocolVersion: LATEST_PROTOCOL_VERSION, - capabilities: this._capabilities, - clientInfo: this._clientInfo - } - }, InitializeResultSchema, options); - if (result === undefined) { - throw new Error(`Server sent invalid initialize result: ${result}`); - } - if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) { - throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`); - } - this._serverCapabilities = result.capabilities; - this._serverVersion = result.serverInfo; - // HTTP transports must set the protocol version in each header after initialization. - if (transport.setProtocolVersion) { - transport.setProtocolVersion(result.protocolVersion); - } - this._instructions = result.instructions; - await this.notification({ - method: 'notifications/initialized' - }); - } - catch (error) { - // Disconnect if initialization fails. - void this.close(); - throw error; - } - } - /** - * After initialization has completed, this will be populated with the server's reported capabilities. - */ - getServerCapabilities() { - return this._serverCapabilities; - } - /** - * After initialization has completed, this will be populated with information about the server's name and version. - */ - getServerVersion() { - return this._serverVersion; - } - /** - * After initialization has completed, this may be populated with information about the server's instructions. - */ - getInstructions() { - return this._instructions; - } - assertCapabilityForMethod(method) { - var _a, _b, _c, _d, _e; - switch (method) { - case 'logging/setLevel': - if (!((_a = this._serverCapabilities) === null || _a === void 0 ? void 0 : _a.logging)) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case 'prompts/get': - case 'prompts/list': - if (!((_b = this._serverCapabilities) === null || _b === void 0 ? void 0 : _b.prompts)) { - throw new Error(`Server does not support prompts (required for ${method})`); - } - break; - case 'resources/list': - case 'resources/templates/list': - case 'resources/read': - case 'resources/subscribe': - case 'resources/unsubscribe': - if (!((_c = this._serverCapabilities) === null || _c === void 0 ? void 0 : _c.resources)) { - throw new Error(`Server does not support resources (required for ${method})`); - } - if (method === 'resources/subscribe' && !this._serverCapabilities.resources.subscribe) { - throw new Error(`Server does not support resource subscriptions (required for ${method})`); - } - break; - case 'tools/call': - case 'tools/list': - if (!((_d = this._serverCapabilities) === null || _d === void 0 ? void 0 : _d.tools)) { - throw new Error(`Server does not support tools (required for ${method})`); - } - break; - case 'completion/complete': - if (!((_e = this._serverCapabilities) === null || _e === void 0 ? void 0 : _e.completions)) { - throw new Error(`Server does not support completions (required for ${method})`); - } - break; - case 'initialize': - // No specific capability required for initialize - break; - case 'ping': - // No specific capability required for ping - break; - } - } - assertNotificationCapability(method) { - var _a; - switch (method) { - case 'notifications/roots/list_changed': - if (!((_a = this._capabilities.roots) === null || _a === void 0 ? void 0 : _a.listChanged)) { - throw new Error(`Client does not support roots list changed notifications (required for ${method})`); - } - break; - case 'notifications/initialized': - // No specific capability required for initialized - break; - case 'notifications/cancelled': - // Cancellation notifications are always allowed - break; - case 'notifications/progress': - // Progress notifications are always allowed - break; - } - } - assertRequestHandlerCapability(method) { - switch (method) { - case 'sampling/createMessage': - if (!this._capabilities.sampling) { - throw new Error(`Client does not support sampling capability (required for ${method})`); - } - break; - case 'elicitation/create': - if (!this._capabilities.elicitation) { - throw new Error(`Client does not support elicitation capability (required for ${method})`); - } - break; - case 'roots/list': - if (!this._capabilities.roots) { - throw new Error(`Client does not support roots capability (required for ${method})`); - } - break; - case 'ping': - // No specific capability required for ping - break; - } - } - async ping(options) { - return this.request({ method: 'ping' }, EmptyResultSchema, options); - } - async complete(params, options) { - return this.request({ method: 'completion/complete', params }, CompleteResultSchema, options); - } - async setLoggingLevel(level, options) { - return this.request({ method: 'logging/setLevel', params: { level } }, EmptyResultSchema, options); - } - async getPrompt(params, options) { - return this.request({ method: 'prompts/get', params }, GetPromptResultSchema, options); - } - async listPrompts(params, options) { - return this.request({ method: 'prompts/list', params }, ListPromptsResultSchema, options); - } - async listResources(params, options) { - return this.request({ method: 'resources/list', params }, ListResourcesResultSchema, options); - } - async listResourceTemplates(params, options) { - return this.request({ method: 'resources/templates/list', params }, ListResourceTemplatesResultSchema, options); - } - async readResource(params, options) { - return this.request({ method: 'resources/read', params }, ReadResourceResultSchema, options); - } - async subscribeResource(params, options) { - return this.request({ method: 'resources/subscribe', params }, EmptyResultSchema, options); - } - async unsubscribeResource(params, options) { - return this.request({ method: 'resources/unsubscribe', params }, EmptyResultSchema, options); - } - async callTool(params, resultSchema = CallToolResultSchema, options) { - const result = await this.request({ method: 'tools/call', params }, resultSchema, options); - // Check if the tool has an outputSchema - const validator = this.getToolOutputValidator(params.name); - if (validator) { - // If tool has outputSchema, it MUST return structuredContent (unless it's an error) - if (!result.structuredContent && !result.isError) { - throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`); - } - // Only validate structured content if present (not when there's an error) - if (result.structuredContent) { - try { - // Validate the structured content against the schema - const validationResult = validator(result.structuredContent); - if (!validationResult.valid) { - throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`); - } - } - catch (error) { - if (error instanceof McpError) { - throw error; - } - throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`); - } - } - } - return result; - } - /** - * Cache validators for tool output schemas. - * Called after listTools() to pre-compile validators for better performance. - */ - cacheToolOutputSchemas(tools) { - this._cachedToolOutputValidators.clear(); - for (const tool of tools) { - // If the tool has an outputSchema, create and cache the validator - if (tool.outputSchema) { - const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema); - this._cachedToolOutputValidators.set(tool.name, toolValidator); - } - } - } - /** - * Get cached validator for a tool - */ - getToolOutputValidator(toolName) { - return this._cachedToolOutputValidators.get(toolName); - } - async listTools(params, options) { - const result = await this.request({ method: 'tools/list', params }, ListToolsResultSchema, options); - // Cache the tools and their output schemas for future validation - this.cacheToolOutputSchemas(result.tools); - return result; - } - async sendRootsListChanged() { - return this.notification({ method: 'notifications/roots/list_changed' }); - } -} -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/esm/client/index.js.map b/dist/esm/client/index.js.map deleted file mode 100644 index 57ca9b491f..0000000000 --- a/dist/esm/client/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/client/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAA6C,MAAM,uBAAuB,CAAC;AAE/G,OAAO,EAEH,oBAAoB,EAOpB,oBAAoB,EACpB,iBAAiB,EACjB,SAAS,EAET,qBAAqB,EAErB,sBAAsB,EACtB,uBAAuB,EAEvB,uBAAuB,EAEvB,yBAAyB,EAEzB,iCAAiC,EAEjC,qBAAqB,EAErB,QAAQ,EAGR,wBAAwB,EAIxB,2BAA2B,EAI3B,kBAAkB,EAClB,mBAAmB,EACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AAEvE,OAAO,EAGH,cAAc,EACd,UAAU,EACV,SAAS,EAGZ,MAAM,yBAAyB,CAAC;AAGjC;;;;;GAKG;AACH,SAAS,wBAAwB,CAAC,MAAkC,EAAE,IAAa;IAC/E,IAAI,CAAC,MAAM,IAAI,IAAI,KAAK,IAAI,IAAI,OAAO,IAAI,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AsB,CAAC,QAAgB;QAC3C,OAAO,IAAI,CAAC,2BAA2B,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC1D,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,MAAmC,EAAE,OAAwB;QACzE,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,EAAE,qBAAqB,EAAE,OAAO,CAAC,CAAC;QAEpG,iEAAiE;QACjE,IAAI,CAAC,sBAAsB,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAE1C,OAAO,MAAM,CAAC;IAClB,CAAC;IAED,KAAK,CAAC,oBAAoB;QACtB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,kCAAkC,EAAE,CAAC,CAAC;IAC7E,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/client/middleware.d.ts b/dist/esm/client/middleware.d.ts deleted file mode 100644 index 726ac578ae..0000000000 --- a/dist/esm/client/middleware.d.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { OAuthClientProvider } from './auth.js'; -import { FetchLike } from '../shared/transport.js'; -/** - * Middleware function that wraps and enhances fetch functionality. - * Takes a fetch handler and returns an enhanced fetch handler. - */ -export type Middleware = (next: FetchLike) => FetchLike; -/** - * Creates a fetch wrapper that handles OAuth authentication automatically. - * - * This wrapper will: - * - Add Authorization headers with access tokens - * - Handle 401 responses by attempting re-authentication - * - Retry the original request after successful auth - * - Handle OAuth errors appropriately (InvalidClientError, etc.) - * - * The baseUrl parameter is optional and defaults to using the domain from the request URL. - * However, you should explicitly provide baseUrl when: - * - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com) - * - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /) - * - The OAuth server is on a different domain than your API requests - * - You want to ensure consistent OAuth behavior regardless of request URLs - * - * For MCP transports, set baseUrl to the same URL you pass to the transport constructor. - * - * Note: This wrapper is designed for general-purpose fetch operations. - * MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling - * and should not need this wrapper. - * - * @param provider - OAuth client provider for authentication - * @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain) - * @returns A fetch middleware function - */ -export declare const withOAuth: (provider: OAuthClientProvider, baseUrl?: string | URL) => Middleware; -/** - * Logger function type for HTTP requests - */ -export type RequestLogger = (input: { - method: string; - url: string | URL; - status: number; - statusText: string; - duration: number; - requestHeaders?: Headers; - responseHeaders?: Headers; - error?: Error; -}) => void; -/** - * Configuration options for the logging middleware - */ -export type LoggingOptions = { - /** - * Custom logger function, defaults to console logging - */ - logger?: RequestLogger; - /** - * Whether to include request headers in logs - * @default false - */ - includeRequestHeaders?: boolean; - /** - * Whether to include response headers in logs - * @default false - */ - includeResponseHeaders?: boolean; - /** - * Status level filter - only log requests with status >= this value - * Set to 0 to log all requests, 400 to log only errors - * @default 0 - */ - statusLevel?: number; -}; -/** - * Creates a fetch middleware that logs HTTP requests and responses. - * - * When called without arguments `withLogging()`, it uses the default logger that: - * - Logs successful requests (2xx) to `console.log` - * - Logs error responses (4xx/5xx) and network errors to `console.error` - * - Logs all requests regardless of status (statusLevel: 0) - * - Does not include request or response headers in logs - * - Measures and displays request duration in milliseconds - * - * Important: the default logger uses both `console.log` and `console.error` so it should not be used with - * `stdio` transports and applications. - * - * @param options - Logging configuration options - * @returns A fetch middleware function - */ -export declare const withLogging: (options?: LoggingOptions) => Middleware; -/** - * Composes multiple fetch middleware functions into a single middleware pipeline. - * Middleware are applied in the order they appear, creating a chain of handlers. - * - * @example - * ```typescript - * // Create a middleware pipeline that handles both OAuth and logging - * const enhancedFetch = applyMiddlewares( - * withOAuth(oauthProvider, 'https://api.example.com'), - * withLogging({ statusLevel: 400 }) - * )(fetch); - * - * // Use the enhanced fetch - it will handle auth and log errors - * const response = await enhancedFetch('https://api.example.com/data'); - * ``` - * - * @param middleware - Array of fetch middleware to compose into a pipeline - * @returns A single composed middleware function - */ -export declare const applyMiddlewares: (...middleware: Middleware[]) => Middleware; -/** - * Helper function to create custom fetch middleware with cleaner syntax. - * Provides the next handler and request details as separate parameters for easier access. - * - * @example - * ```typescript - * // Create custom authentication middleware - * const customAuthMiddleware = createMiddleware(async (next, input, init) => { - * const headers = new Headers(init?.headers); - * headers.set('X-Custom-Auth', 'my-token'); - * - * const response = await next(input, { ...init, headers }); - * - * if (response.status === 401) { - * console.log('Authentication failed'); - * } - * - * return response; - * }); - * - * // Create conditional middleware - * const conditionalMiddleware = createMiddleware(async (next, input, init) => { - * const url = typeof input === 'string' ? input : input.toString(); - * - * // Only add headers for API routes - * if (url.includes('/api/')) { - * const headers = new Headers(init?.headers); - * headers.set('X-API-Version', 'v2'); - * return next(input, { ...init, headers }); - * } - * - * // Pass through for non-API routes - * return next(input, init); - * }); - * - * // Create caching middleware - * const cacheMiddleware = createMiddleware(async (next, input, init) => { - * const cacheKey = typeof input === 'string' ? input : input.toString(); - * - * // Check cache first - * const cached = await getFromCache(cacheKey); - * if (cached) { - * return new Response(cached, { status: 200 }); - * } - * - * // Make request and cache result - * const response = await next(input, init); - * if (response.ok) { - * await saveToCache(cacheKey, await response.clone().text()); - * } - * - * return response; - * }); - * ``` - * - * @param handler - Function that receives the next handler and request parameters - * @returns A fetch middleware function - */ -export declare const createMiddleware: (handler: (next: FetchLike, input: string | URL, init?: RequestInit) => Promise) => Middleware; -//# sourceMappingURL=middleware.d.ts.map \ No newline at end of file diff --git a/dist/esm/client/middleware.d.ts.map b/dist/esm/client/middleware.d.ts.map deleted file mode 100644 index 88ac77806d..0000000000 --- a/dist/esm/client/middleware.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"middleware.d.ts","sourceRoot":"","sources":["../../../src/client/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsC,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AACvG,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;;GAGG;AACH,MAAM,MAAM,UAA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at end of file diff --git a/dist/esm/client/middleware.js b/dist/esm/client/middleware.js deleted file mode 100644 index 9e24de68f8..0000000000 --- a/dist/esm/client/middleware.js +++ /dev/null @@ -1,245 +0,0 @@ -import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js'; -/** - * Creates a fetch wrapper that handles OAuth authentication automatically. - * - * This wrapper will: - * - Add Authorization headers with access tokens - * - Handle 401 responses by attempting re-authentication - * - Retry the original request after successful auth - * - Handle OAuth errors appropriately (InvalidClientError, etc.) - * - * The baseUrl parameter is optional and defaults to using the domain from the request URL. - * However, you should explicitly provide baseUrl when: - * - Making requests to multiple subdomains (e.g., api.example.com, cdn.example.com) - * - Using API paths that differ from OAuth discovery paths (e.g., requesting /api/v1/data but OAuth is at /) - * - The OAuth server is on a different domain than your API requests - * - You want to ensure consistent OAuth behavior regardless of request URLs - * - * For MCP transports, set baseUrl to the same URL you pass to the transport constructor. - * - * Note: This wrapper is designed for general-purpose fetch operations. - * MCP transports (SSE and StreamableHTTP) already have built-in OAuth handling - * and should not need this wrapper. - * - * @param provider - OAuth client provider for authentication - * @param baseUrl - Base URL for OAuth server discovery (defaults to request URL domain) - * @returns A fetch middleware function - */ -export const withOAuth = (provider, baseUrl) => next => { - return async (input, init) => { - const makeRequest = async () => { - const headers = new Headers(init === null || init === void 0 ? void 0 : init.headers); - // Add authorization header if tokens are available - const tokens = await provider.tokens(); - if (tokens) { - headers.set('Authorization', `Bearer ${tokens.access_token}`); - } - return await next(input, { ...init, headers }); - }; - let response = await makeRequest(); - // Handle 401 responses by attempting re-authentication - if (response.status === 401) { - try { - const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); - // Use provided baseUrl or extract from request URL - const serverUrl = baseUrl || (typeof input === 'string' ? new URL(input).origin : input.origin); - const result = await auth(provider, { - serverUrl, - resourceMetadataUrl, - scope, - fetchFn: next - }); - if (result === 'REDIRECT') { - throw new UnauthorizedError('Authentication requires user authorization - redirect initiated'); - } - if (result !== 'AUTHORIZED') { - throw new UnauthorizedError(`Authentication failed with result: ${result}`); - } - // Retry the request with fresh tokens - response = await makeRequest(); - } - catch (error) { - if (error instanceof UnauthorizedError) { - throw error; - } - throw new UnauthorizedError(`Failed to re-authenticate: ${error instanceof Error ? error.message : String(error)}`); - } - } - // If we still have a 401 after re-auth attempt, throw an error - if (response.status === 401) { - const url = typeof input === 'string' ? input : input.toString(); - throw new UnauthorizedError(`Authentication failed for ${url}`); - } - return response; - }; -}; -/** - * Creates a fetch middleware that logs HTTP requests and responses. - * - * When called without arguments `withLogging()`, it uses the default logger that: - * - Logs successful requests (2xx) to `console.log` - * - Logs error responses (4xx/5xx) and network errors to `console.error` - * - Logs all requests regardless of status (statusLevel: 0) - * - Does not include request or response headers in logs - * - Measures and displays request duration in milliseconds - * - * Important: the default logger uses both `console.log` and `console.error` so it should not be used with - * `stdio` transports and applications. - * - * @param options - Logging configuration options - * @returns A fetch middleware function - */ -export const withLogging = (options = {}) => { - const { logger, includeRequestHeaders = false, includeResponseHeaders = false, statusLevel = 0 } = options; - const defaultLogger = input => { - const { method, url, status, statusText, duration, requestHeaders, responseHeaders, error } = input; - let message = error - ? `HTTP ${method} ${url} failed: ${error.message} (${duration}ms)` - : `HTTP ${method} ${url} ${status} ${statusText} (${duration}ms)`; - // Add headers to message if requested - if (includeRequestHeaders && requestHeaders) { - const reqHeaders = Array.from(requestHeaders.entries()) - .map(([key, value]) => `${key}: ${value}`) - .join(', '); - message += `\n Request Headers: {${reqHeaders}}`; - } - if (includeResponseHeaders && responseHeaders) { - const resHeaders = Array.from(responseHeaders.entries()) - .map(([key, value]) => `${key}: ${value}`) - .join(', '); - message += `\n Response Headers: {${resHeaders}}`; - } - if (error || status >= 400) { - // eslint-disable-next-line no-console - console.error(message); - } - else { - // eslint-disable-next-line no-console - console.log(message); - } - }; - const logFn = logger || defaultLogger; - return next => async (input, init) => { - const startTime = performance.now(); - const method = (init === null || init === void 0 ? void 0 : init.method) || 'GET'; - const url = typeof input === 'string' ? input : input.toString(); - const requestHeaders = includeRequestHeaders ? new Headers(init === null || init === void 0 ? void 0 : init.headers) : undefined; - try { - const response = await next(input, init); - const duration = performance.now() - startTime; - // Only log if status meets the log level threshold - if (response.status >= statusLevel) { - logFn({ - method, - url, - status: response.status, - statusText: response.statusText, - duration, - requestHeaders, - responseHeaders: includeResponseHeaders ? response.headers : undefined - }); - } - return response; - } - catch (error) { - const duration = performance.now() - startTime; - // Always log errors regardless of log level - logFn({ - method, - url, - status: 0, - statusText: 'Network Error', - duration, - requestHeaders, - error: error - }); - throw error; - } - }; -}; -/** - * Composes multiple fetch middleware functions into a single middleware pipeline. - * Middleware are applied in the order they appear, creating a chain of handlers. - * - * @example - * ```typescript - * // Create a middleware pipeline that handles both OAuth and logging - * const enhancedFetch = applyMiddlewares( - * withOAuth(oauthProvider, 'https://api.example.com'), - * withLogging({ statusLevel: 400 }) - * )(fetch); - * - * // Use the enhanced fetch - it will handle auth and log errors - * const response = await enhancedFetch('https://api.example.com/data'); - * ``` - * - * @param middleware - Array of fetch middleware to compose into a pipeline - * @returns A single composed middleware function - */ -export const applyMiddlewares = (...middleware) => { - return next => { - return middleware.reduce((handler, mw) => mw(handler), next); - }; -}; -/** - * Helper function to create custom fetch middleware with cleaner syntax. - * Provides the next handler and request details as separate parameters for easier access. - * - * @example - * ```typescript - * // Create custom authentication middleware - * const customAuthMiddleware = createMiddleware(async (next, input, init) => { - * const headers = new Headers(init?.headers); - * headers.set('X-Custom-Auth', 'my-token'); - * - * const response = await next(input, { ...init, headers }); - * - * if (response.status === 401) { - * console.log('Authentication failed'); - * } - * - * return response; - * }); - * - * // Create conditional middleware - * const conditionalMiddleware = createMiddleware(async (next, input, init) => { - * const url = typeof input === 'string' ? input : input.toString(); - * - * // Only add headers for API routes - * if (url.includes('/api/')) { - * const headers = new Headers(init?.headers); - * headers.set('X-API-Version', 'v2'); - * return next(input, { ...init, headers }); - * } - * - * // Pass through for non-API routes - * return next(input, init); - * }); - * - * // Create caching middleware - * const cacheMiddleware = createMiddleware(async (next, input, init) => { - * const cacheKey = typeof input === 'string' ? input : input.toString(); - * - * // Check cache first - * const cached = await getFromCache(cacheKey); - * if (cached) { - * return new Response(cached, { status: 200 }); - * } - * - * // Make request and cache result - * const response = await next(input, init); - * if (response.ok) { - * await saveToCache(cacheKey, await response.clone().text()); - * } - * - * return response; - * }); - * ``` - * - * @param handler - Function that receives the next handler and request parameters - * @returns A fetch middleware function - */ -export const createMiddleware = (handler) => { - return next => (input, init) => handler(next, input, init); -}; -//# sourceMappingURL=middleware.js.map \ No newline at end of file diff --git a/dist/esm/client/middleware.js.map b/dist/esm/client/middleware.js.map deleted file mode 100644 index eabfcc54d7..0000000000 --- a/dist/esm/client/middleware.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"middleware.js","sourceRoot":"","sources":["../../../src/client/middleware.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,4BAA4B,EAAuB,iBAAiB,EAAE,MAAM,WAAW,CAAC;AASvG;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,CAAC,MAAM,SAAS,GAClB,CAAC,QAA6B,EAAE,OAAsB,EAAc,EAAE,CACtE,IAAI,CAAC,EAAE;IACH,OAAO,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE;QACzB,MAAM,WAAW,GAAG,KAAK,IAAuB,EAAE;YAC9C,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,CAAC,CAAC;YAE3C,mDAAmD;YACnD,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,MAAM,EAAE,CAAC;YACvC,IAAI,MAAM,EAAE,CAAC;gBACT,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,UAAU,MAAM,CAAC,YAAY,EAAE,CAAC,CAAC;YAClE,CAAC;YAED,OAAO,MAAM,IAAI,CAAC,KAAK,EAAE,EAAE,GAAG,IAAI,EAAE,OAAO,EA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KAAK,EAAE,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,KAAqB,EAAE,IAAI,CAAC,CAAC;AAC/E,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/client/sse.d.ts b/dist/esm/client/sse.d.ts deleted file mode 100644 index acf99f1ea6..0000000000 --- a/dist/esm/client/sse.d.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { type ErrorEvent, type EventSourceInit } from 'eventsource'; -import { Transport, FetchLike } from '../shared/transport.js'; -import { JSONRPCMessage } from '../types.js'; -import { OAuthClientProvider } from './auth.js'; -export declare class SseError extends Error { - readonly code: number | undefined; - readonly event: ErrorEvent; - constructor(code: number | undefined, message: string | undefined, event: ErrorEvent); -} -/** - * Configuration options for the `SSEClientTransport`. - */ -export type SSEClientTransportOptions = { - /** - * An OAuth client provider to use for authentication. - * - * When an `authProvider` is specified and the SSE connection is started: - * 1. The connection is attempted with any existing access token from the `authProvider`. - * 2. If the access token has expired, the `authProvider` is used to refresh the token. - * 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`. - * - * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `SSEClientTransport.finishAuth` with the authorization code before retrying the connection. - * - * If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown. - * - * `UnauthorizedError` might also be thrown when sending any message over the SSE transport, indicating that the session has expired, and needs to be re-authed and reconnected. - */ - authProvider?: OAuthClientProvider; - /** - * Customizes the initial SSE request to the server (the request that begins the stream). - * - * NOTE: Setting this property will prevent an `Authorization` header from - * being automatically attached to the SSE request, if an `authProvider` is - * also given. This can be worked around by setting the `Authorization` header - * manually. - */ - eventSourceInit?: EventSourceInit; - /** - * Customizes recurring POST requests to the server. - */ - requestInit?: RequestInit; - /** - * Custom fetch implementation used for all network requests. - */ - fetch?: FetchLike; -}; -/** - * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving - * messages and make separate POST requests for sending messages. - * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period. - */ -export declare class SSEClientTransport implements Transport { - private _eventSource?; - private _endpoint?; - private _abortController?; - private _url; - private _resourceMetadataUrl?; - private _scope?; - private _eventSourceInit?; - private _requestInit?; - private _authProvider?; - private _fetch?; - private _fetchWithInit; - private _protocolVersion?; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage) => void; - constructor(url: URL, opts?: SSEClientTransportOptions); - private _authThenStart; - private _commonHeaders; - private _startOrAuth; - start(): Promise; - /** - * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. - */ - finishAuth(authorizationCode: string): Promise; - close(): Promise; - send(message: JSONRPCMessage): Promise; - setProtocolVersion(version: string): void; -} -//# sourceMappingURL=sse.d.ts.map \ No newline at end of file diff --git a/dist/esm/client/sse.d.ts.map b/dist/esm/client/sse.d.ts.map deleted file mode 100644 index 3a0053cfc6..0000000000 --- a/dist/esm/client/sse.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../../src/client/sse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,KAAK,UAAU,EAAE,KAAK,eAAe,EAAE,MAAM,aAAa,CAAC;AACjF,OAAO,EAAE,SAAS,EAAE,SAAS,EAAuB,MAAM,wBAAwB,CAAC;AACnF,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AACnE,OAAO,EAAkD,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AAEnH,qBAAa,QAAS,SAAQ,KAAK;aAEX,IAAI,EAAE,MAAM,GAAG,SAAS;aAExB,KAAK,EAAE,UAAU;gBAFjB,IAAI,EAAE,MAAM,GAAG,SAAS,EACxC,OAAO,EAAE,MAAM,GAAG,SAAS,EACX,KAAK,EAAE,UAAU;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OAAO,CAAC,IAAI,CAAC;IA8ClD,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;CAG5C"} \ No newline at end of file diff --git a/dist/esm/client/sse.js b/dist/esm/client/sse.js deleted file mode 100644 index 6045cb6ba3..0000000000 --- a/dist/esm/client/sse.js +++ /dev/null @@ -1,208 +0,0 @@ -import { EventSource } from 'eventsource'; -import { createFetchWithInit } from '../shared/transport.js'; -import { JSONRPCMessageSchema } from '../types.js'; -import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js'; -export class SseError extends Error { - constructor(code, message, event) { - super(`SSE error: ${message}`); - this.code = code; - this.event = event; - } -} -/** - * Client transport for SSE: this will connect to a server using Server-Sent Events for receiving - * messages and make separate POST requests for sending messages. - * @deprecated SSEClientTransport is deprecated. Prefer to use StreamableHTTPClientTransport where possible instead. Note that because some servers are still using SSE, clients may need to support both transports during the migration period. - */ -export class SSEClientTransport { - constructor(url, opts) { - this._url = url; - this._resourceMetadataUrl = undefined; - this._scope = undefined; - this._eventSourceInit = opts === null || opts === void 0 ? void 0 : opts.eventSourceInit; - this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit; - this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider; - this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch; - this._fetchWithInit = createFetchWithInit(opts === null || opts === void 0 ? void 0 : opts.fetch, opts === null || opts === void 0 ? void 0 : opts.requestInit); - } - async _authThenStart() { - var _a; - if (!this._authProvider) { - throw new UnauthorizedError('No auth provider'); - } - let result; - try { - result = await auth(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetchWithInit - }); - } - catch (error) { - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - throw error; - } - if (result !== 'AUTHORIZED') { - throw new UnauthorizedError(); - } - return await this._startOrAuth(); - } - async _commonHeaders() { - var _a; - const headers = {}; - if (this._authProvider) { - const tokens = await this._authProvider.tokens(); - if (tokens) { - headers['Authorization'] = `Bearer ${tokens.access_token}`; - } - } - if (this._protocolVersion) { - headers['mcp-protocol-version'] = this._protocolVersion; - } - return new Headers({ ...headers, ...(_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers }); - } - _startOrAuth() { - var _a, _b, _c; - const fetchImpl = ((_c = (_b = (_a = this === null || this === void 0 ? void 0 : this._eventSourceInit) === null || _a === void 0 ? void 0 : _a.fetch) !== null && _b !== void 0 ? _b : this._fetch) !== null && _c !== void 0 ? _c : fetch); - return new Promise((resolve, reject) => { - this._eventSource = new EventSource(this._url.href, { - ...this._eventSourceInit, - fetch: async (url, init) => { - const headers = await this._commonHeaders(); - headers.set('Accept', 'text/event-stream'); - const response = await fetchImpl(url, { - ...init, - headers - }); - if (response.status === 401 && response.headers.has('www-authenticate')) { - const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); - this._resourceMetadataUrl = resourceMetadataUrl; - this._scope = scope; - } - return response; - } - }); - this._abortController = new AbortController(); - this._eventSource.onerror = event => { - var _a; - if (event.code === 401 && this._authProvider) { - this._authThenStart().then(resolve, reject); - return; - } - const error = new SseError(event.code, event.message, event); - reject(error); - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }; - this._eventSource.onopen = () => { - // The connection is open, but we need to wait for the endpoint to be received. - }; - this._eventSource.addEventListener('endpoint', (event) => { - var _a; - const messageEvent = event; - try { - this._endpoint = new URL(messageEvent.data, this._url); - if (this._endpoint.origin !== this._url.origin) { - throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`); - } - } - catch (error) { - reject(error); - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - void this.close(); - return; - } - resolve(); - }); - this._eventSource.onmessage = (event) => { - var _a, _b; - const messageEvent = event; - let message; - try { - message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data)); - } - catch (error) { - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - return; - } - (_b = this.onmessage) === null || _b === void 0 ? void 0 : _b.call(this, message); - }; - }); - } - async start() { - if (this._eventSource) { - throw new Error('SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.'); - } - return await this._startOrAuth(); - } - /** - * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. - */ - async finishAuth(authorizationCode) { - if (!this._authProvider) { - throw new UnauthorizedError('No auth provider'); - } - const result = await auth(this._authProvider, { - serverUrl: this._url, - authorizationCode, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetchWithInit - }); - if (result !== 'AUTHORIZED') { - throw new UnauthorizedError('Failed to authorize'); - } - } - async close() { - var _a, _b, _c; - (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.abort(); - (_b = this._eventSource) === null || _b === void 0 ? void 0 : _b.close(); - (_c = this.onclose) === null || _c === void 0 ? void 0 : _c.call(this); - } - async send(message) { - var _a, _b, _c; - if (!this._endpoint) { - throw new Error('Not connected'); - } - try { - const headers = await this._commonHeaders(); - headers.set('content-type', 'application/json'); - const init = { - ...this._requestInit, - method: 'POST', - headers, - body: JSON.stringify(message), - signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal - }; - const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._endpoint, init); - if (!response.ok) { - if (response.status === 401 && this._authProvider) { - const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); - this._resourceMetadataUrl = resourceMetadataUrl; - this._scope = scope; - const result = await auth(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetchWithInit - }); - if (result !== 'AUTHORIZED') { - throw new UnauthorizedError(); - } - // Purposely _not_ awaited, so we don't call onerror twice - return this.send(message); - } - const text = await response.text().catch(() => null); - throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); - } - } - catch (error) { - (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error); - throw error; - } - } - setProtocolVersion(version) { - this._protocolVersion = version; - } -} -//# sourceMappingURL=sse.js.map \ No newline at end of file diff --git a/dist/esm/client/sse.js.map b/dist/esm/client/sse.js.map deleted file mode 100644 index aafaf36635..0000000000 --- a/dist/esm/client/sse.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"sse.js","sourceRoot":"","sources":["../../../src/client/sse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAyC,MAAM,aAAa,CAAC;AACjF,OAAO,EAAwB,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AACnF,OAAO,EAAkB,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,IAAI,EAAc,4BAA4B,EAAuB,iBAAiB,EAAE,MAAM,WAAW,CAAC;AAEnH,MAAM,OAAO,QAAS,SAAQ,KAAK;IAC/B,YACoB,IAAwB,EACxC,OAA2B,EACX,KAAiB;QAEjC,KAAK,CAAC,cAAc,OAAO,EAAE,CAAC,CAAC;QAJf,SAAI,GAAJ,IAAI,CAAoB;QAExB,UAAK,GAAL,KAAK,CAAY;IAGrC,CAAC;CACJ;AA2CD;;;;GAIG;AACH,MAAM,OAAO,kBAAkB;IAkB3B,YAAY,GAAQ,EAAE,IAAgC;QAClD,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;QAChB,IAAI,CAAC,oBAAoB,GAAG,SAAS,CAAC;QACtC,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;QACxB,IAAI,CAAC,gBAAgB,GAAG,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,eAAe,CAAC;QAC9C,IAAI,CAAC,YAAY,GAAG,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,WAAW,CAAC;QACtC,IAAI,CAAC,aAAa,GAAG,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,YAAY,CAAC;QACxC,IAAI,CAAC,MAAM,GAAG,IAAI,a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,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE;wBAC1C,SAAS,EAAE,IAAI,CAAC,IAAI;wBACpB,mBAAmB,EAAE,IAAI,CAAC,oBAAoB;wBAC9C,KAAK,EAAE,IAAI,CAAC,MAAM;wBAClB,OAAO,EAAE,IAAI,CAAC,cAAc;qBAC/B,CAAC,CAAC;oBACH,IAAI,MAAM,KAAK,YAAY,EAAE,CAAC;wBAC1B,MAAM,IAAI,iBAAiB,EAAE,CAAC;oBAClC,CAAC;oBAED,0DAA0D;oBAC1D,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;gBAC9B,CAAC;gBAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;gBACrD,MAAM,IAAI,KAAK,CAAC,mCAAmC,QAAQ,CAAC,MAAM,MAAM,IAAI,EAAE,CAAC,CAAC;YACpF,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,MAAA,IAAI,CAAC,OAAO,qDAAG,KAAc,CAAC,CAAC;YAC/B,MAAM,KAAK,CAAC;QAChB,CAAC;IACL,CAAC;IAED,kBAAkB,CAAC,OAAe;QAC9B,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;IACpC,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/client/stdio.d.ts b/dist/esm/client/stdio.d.ts deleted file mode 100644 index 58d0b6ccba..0000000000 --- a/dist/esm/client/stdio.d.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { IOType } from 'node:child_process'; -import { Stream } from 'node:stream'; -import { Transport } from '../shared/transport.js'; -import { JSONRPCMessage } from '../types.js'; -export type StdioServerParameters = { - /** - * The executable to run to start the server. - */ - command: string; - /** - * Command line arguments to pass to the executable. - */ - args?: string[]; - /** - * The environment to use when spawning the process. - * - * If not specified, the result of getDefaultEnvironment() will be used. - */ - env?: Record; - /** - * How to handle stderr of the child process. This matches the semantics of Node's `child_process.spawn`. - * - * The default is "inherit", meaning messages to stderr will be printed to the parent process's stderr. - */ - stderr?: IOType | Stream | number; - /** - * The working directory to use when spawning the process. - * - * If not specified, the current working directory will be inherited. - */ - cwd?: string; -}; -/** - * Environment variables to inherit by default, if an environment is not explicitly given. - */ -export declare const DEFAULT_INHERITED_ENV_VARS: string[]; -/** - * Returns a default environment object including only environment variables deemed safe to inherit. - */ -export declare function getDefaultEnvironment(): Record; -/** - * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout. - * - * This transport is only available in Node.js environments. - */ -export declare class StdioClientTransport implements Transport { - private _process?; - private _abortController; - private _readBuffer; - private _serverParams; - private _stderrStream; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage) => void; - constructor(server: StdioServerParameters); - /** - * Starts the server process and prepares to communicate with it. - */ - start(): Promise; - /** - * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". - * - * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to - * attach listeners before the start method is invoked. This prevents loss of any early - * error output emitted by the child process. - */ - get stderr(): Stream | null; - /** - * The child process pid spawned by this transport. - * - * This is only available after the transport has been started. - */ - get pid(): number | null; - private processReadBuffer; - close(): Promise; - send(message: JSONRPCMessage): Promise; -} -//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/dist/esm/client/stdio.d.ts.map b/dist/esm/client/stdio.d.ts.map deleted file mode 100644 index 44f6de451b..0000000000 --- a/dist/esm/client/stdio.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/client/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAE,MAAM,oBAAoB,CAAC;AAG1D,OAAO,EAAE,MAAM,EAAe,MAAM,aAAa,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EA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GAAG,OAAO,CAAC,IAAI,CAAC;CAc/C"} \ No newline at end of file diff --git a/dist/esm/client/stdio.js b/dist/esm/client/stdio.js deleted file mode 100644 index d77c64d15b..0000000000 --- a/dist/esm/client/stdio.js +++ /dev/null @@ -1,176 +0,0 @@ -import spawn from 'cross-spawn'; -import process from 'node:process'; -import { PassThrough } from 'node:stream'; -import { ReadBuffer, serializeMessage } from '../shared/stdio.js'; -/** - * Environment variables to inherit by default, if an environment is not explicitly given. - */ -export const DEFAULT_INHERITED_ENV_VARS = process.platform === 'win32' - ? [ - 'APPDATA', - 'HOMEDRIVE', - 'HOMEPATH', - 'LOCALAPPDATA', - 'PATH', - 'PROCESSOR_ARCHITECTURE', - 'SYSTEMDRIVE', - 'SYSTEMROOT', - 'TEMP', - 'USERNAME', - 'USERPROFILE', - 'PROGRAMFILES' - ] - : /* list inspired by the default env inheritance of sudo */ - ['HOME', 'LOGNAME', 'PATH', 'SHELL', 'TERM', 'USER']; -/** - * Returns a default environment object including only environment variables deemed safe to inherit. - */ -export function getDefaultEnvironment() { - const env = {}; - for (const key of DEFAULT_INHERITED_ENV_VARS) { - const value = process.env[key]; - if (value === undefined) { - continue; - } - if (value.startsWith('()')) { - // Skip functions, which are a security risk. - continue; - } - env[key] = value; - } - return env; -} -/** - * Client transport for stdio: this will connect to a server by spawning a process and communicating with it over stdin/stdout. - * - * This transport is only available in Node.js environments. - */ -export class StdioClientTransport { - constructor(server) { - this._abortController = new AbortController(); - this._readBuffer = new ReadBuffer(); - this._stderrStream = null; - this._serverParams = server; - if (server.stderr === 'pipe' || server.stderr === 'overlapped') { - this._stderrStream = new PassThrough(); - } - } - /** - * Starts the server process and prepares to communicate with it. - */ - async start() { - if (this._process) { - throw new Error('StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.'); - } - return new Promise((resolve, reject) => { - var _a, _b, _c, _d, _e; - this._process = spawn(this._serverParams.command, (_a = this._serverParams.args) !== null && _a !== void 0 ? _a : [], { - // merge default env with server env because mcp server needs some env vars - env: { - ...getDefaultEnvironment(), - ...this._serverParams.env - }, - stdio: ['pipe', 'pipe', (_b = this._serverParams.stderr) !== null && _b !== void 0 ? _b : 'inherit'], - shell: false, - signal: this._abortController.signal, - windowsHide: process.platform === 'win32' && isElectron(), - cwd: this._serverParams.cwd - }); - this._process.on('error', error => { - var _a, _b; - if (error.name === 'AbortError') { - // Expected when close() is called. - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - return; - } - reject(error); - (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); - }); - this._process.on('spawn', () => { - resolve(); - }); - this._process.on('close', _code => { - var _a; - this._process = undefined; - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - }); - (_c = this._process.stdin) === null || _c === void 0 ? void 0 : _c.on('error', error => { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }); - (_d = this._process.stdout) === null || _d === void 0 ? void 0 : _d.on('data', chunk => { - this._readBuffer.append(chunk); - this.processReadBuffer(); - }); - (_e = this._process.stdout) === null || _e === void 0 ? void 0 : _e.on('error', error => { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }); - if (this._stderrStream && this._process.stderr) { - this._process.stderr.pipe(this._stderrStream); - } - }); - } - /** - * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped". - * - * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to - * attach listeners before the start method is invoked. This prevents loss of any early - * error output emitted by the child process. - */ - get stderr() { - var _a, _b; - if (this._stderrStream) { - return this._stderrStream; - } - return (_b = (_a = this._process) === null || _a === void 0 ? void 0 : _a.stderr) !== null && _b !== void 0 ? _b : null; - } - /** - * The child process pid spawned by this transport. - * - * This is only available after the transport has been started. - */ - get pid() { - var _a, _b; - return (_b = (_a = this._process) === null || _a === void 0 ? void 0 : _a.pid) !== null && _b !== void 0 ? _b : null; - } - processReadBuffer() { - var _a, _b; - while (true) { - try { - const message = this._readBuffer.readMessage(); - if (message === null) { - break; - } - (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message); - } - catch (error) { - (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); - } - } - } - async close() { - this._abortController.abort(); - this._process = undefined; - this._readBuffer.clear(); - } - send(message) { - return new Promise(resolve => { - var _a; - if (!((_a = this._process) === null || _a === void 0 ? void 0 : _a.stdin)) { - throw new Error('Not connected'); - } - const json = serializeMessage(message); - if (this._process.stdin.write(json)) { - resolve(); - } - else { - this._process.stdin.once('drain', resolve); - } - }); - } -} -function isElectron() { - return 'type' in process; -} -//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/dist/esm/client/stdio.js.map b/dist/esm/client/stdio.js.map deleted file mode 100644 index ad681edebb..0000000000 --- a/dist/esm/client/stdio.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/client/stdio.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,aAAa,CAAC;AAChC,OAAO,OAAO,MAAM,cAAc,CAAC;AACnC,OAAO,EAAU,WAAW,EAAE,MAAM,aAAa,CAAC;AAClD,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAqClE;;GAEG;AACH,MAAM,CAAC,MAAM,0BAA0B,GACnC,OAAO,CAAC,QAAQ,KAAK,OAAO;IACxB,CAAC,CAAC;QACI,SAAS;QACT,WAAW;QACX,UAAU;QACV,cAAc;QACd,MAAM;QACN,wBAAwB;QACxB,aAAa;QACb,YAAY;QACZ,MAAM;QACN,UAAU;QACV,aAAa;QACb,cAAc;KACjB;IACH,CAAC,CAAC,0DAA0D;QAC1D,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAE/D;;GAEG;AACH,MAAM,UAAU,qBAAqB;IACjC,MAAM,GAAG,GAA2B,EAAE,CAAC;IA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K,CAAC,KAAK;QACP,IAAI,CAAC,gBAAgB,CAAC,KAAK,EAAE,CAAC;QAC9B,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC;QAC1B,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;IAC7B,CAAC;IAED,IAAI,CAAC,OAAuB;QACxB,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE;;YACzB,IAAI,CAAC,CAAA,MAAA,IAAI,CAAC,QAAQ,0CAAE,KAAK,CAAA,EAAE,CAAC;gBACxB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;YACrC,CAAC;YAED,MAAM,IAAI,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;YACvC,IAAI,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBAClC,OAAO,EAAE,CAAC;YACd,CAAC;iBAAM,CAAC;gBACJ,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YAC/C,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACJ;AAED,SAAS,UAAU;IACf,OAAO,MAAM,IAAI,OAAO,CAAC;AAC7B,CAAC"} \ No newline at end of file diff --git a/dist/esm/client/streamableHttp.d.ts b/dist/esm/client/streamableHttp.d.ts deleted file mode 100644 index 6c6a32f473..0000000000 --- a/dist/esm/client/streamableHttp.d.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { Transport, FetchLike } from '../shared/transport.js'; -import { JSONRPCMessage } from '../types.js'; -import { OAuthClientProvider } from './auth.js'; -export declare class StreamableHTTPError extends Error { - readonly code: number | undefined; - constructor(code: number | undefined, message: string | undefined); -} -/** - * Options for starting or authenticating an SSE connection - */ -export interface StartSSEOptions { - /** - * The resumption token used to continue long-running requests that were interrupted. - * - * This allows clients to reconnect and continue from where they left off. - */ - resumptionToken?: string; - /** - * A callback that is invoked when the resumption token changes. - * - * This allows clients to persist the latest token for potential reconnection. - */ - onresumptiontoken?: (token: string) => void; - /** - * Override Message ID to associate with the replay message - * so that response can be associate with the new resumed request. - */ - replayMessageId?: string | number; -} -/** - * Configuration options for reconnection behavior of the StreamableHTTPClientTransport. - */ -export interface StreamableHTTPReconnectionOptions { - /** - * Maximum backoff time between reconnection attempts in milliseconds. - * Default is 30000 (30 seconds). - */ - maxReconnectionDelay: number; - /** - * Initial backoff time between reconnection attempts in milliseconds. - * Default is 1000 (1 second). - */ - initialReconnectionDelay: number; - /** - * The factor by which the reconnection delay increases after each attempt. - * Default is 1.5. - */ - reconnectionDelayGrowFactor: number; - /** - * Maximum number of reconnection attempts before giving up. - * Default is 2. - */ - maxRetries: number; -} -/** - * Configuration options for the `StreamableHTTPClientTransport`. - */ -export type StreamableHTTPClientTransportOptions = { - /** - * An OAuth client provider to use for authentication. - * - * When an `authProvider` is specified and the connection is started: - * 1. The connection is attempted with any existing access token from the `authProvider`. - * 2. If the access token has expired, the `authProvider` is used to refresh the token. - * 3. If token refresh fails or no access token exists, and auth is required, `OAuthClientProvider.redirectToAuthorization` is called, and an `UnauthorizedError` will be thrown from `connect`/`start`. - * - * After the user has finished authorizing via their user agent, and is redirected back to the MCP client application, call `StreamableHTTPClientTransport.finishAuth` with the authorization code before retrying the connection. - * - * If an `authProvider` is not provided, and auth is required, an `UnauthorizedError` will be thrown. - * - * `UnauthorizedError` might also be thrown when sending any message over the transport, indicating that the session has expired, and needs to be re-authed and reconnected. - */ - authProvider?: OAuthClientProvider; - /** - * Customizes HTTP requests to the server. - */ - requestInit?: RequestInit; - /** - * Custom fetch implementation used for all network requests. - */ - fetch?: FetchLike; - /** - * Options to configure the reconnection behavior. - */ - reconnectionOptions?: StreamableHTTPReconnectionOptions; - /** - * Session ID for the connection. This is used to identify the session on the server. - * When not provided and connecting to a server that supports session IDs, the server will generate a new session ID. - */ - sessionId?: string; -}; -/** - * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. - * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events - * for receiving messages. - */ -export declare class StreamableHTTPClientTransport implements Transport { - private _abortController?; - private _url; - private _resourceMetadataUrl?; - private _scope?; - private _requestInit?; - private _authProvider?; - private _fetch?; - private _fetchWithInit; - private _sessionId?; - private _reconnectionOptions; - private _protocolVersion?; - private _hasCompletedAuthFlow; - private _lastUpscopingHeader?; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage) => void; - constructor(url: URL, opts?: StreamableHTTPClientTransportOptions); - private _authThenStart; - private _commonHeaders; - private _startOrAuthSse; - /** - * Calculates the next reconnection delay using backoff algorithm - * - * @param attempt Current reconnection attempt count for the specific stream - * @returns Time to wait in milliseconds before next reconnection attempt - */ - private _getNextReconnectionDelay; - /** - * Schedule a reconnection attempt with exponential backoff - * - * @param lastEventId The ID of the last received event for resumability - * @param attemptCount Current reconnection attempt count for this specific stream - */ - private _scheduleReconnection; - private _handleSseStream; - start(): Promise; - /** - * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. - */ - finishAuth(authorizationCode: string): Promise; - close(): Promise; - send(message: JSONRPCMessage | JSONRPCMessage[], options?: { - resumptionToken?: string; - onresumptiontoken?: (token: string) => void; - }): Promise; - get sessionId(): string | undefined; - /** - * Terminates the current session by sending a DELETE request to the server. - * - * Clients that no longer need a particular session - * (e.g., because the user is leaving the client application) SHOULD send an - * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly - * terminate the session. - * - * The server MAY respond with HTTP 405 Method Not Allowed, indicating that - * the server does not allow clients to terminate sessions. - */ - terminateSession(): Promise; - setProtocolVersion(version: string): void; - get protocolVersion(): string | undefined; -} -//# sourceMappingURL=streamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/esm/client/streamableHttp.d.ts.map b/dist/esm/client/streamableHttp.d.ts.map deleted file mode 100644 index cbca11957b..0000000000 --- a/dist/esm/client/streamableHttp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"streamableHttp.d.ts","sourceRoot":"","sources":["../../../src/client/streamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,SAAS,EAAyC,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAkE,cAAc,EAAwB,MAAM,aAAa,CAAC;AACnI,OAAO,EAAkD,mBAAmB,EAAqB,MAAM,WAAW,CAAC;AAWnH,qBAAa,mBAAoB,SAAQ,KAAK;aAEtB,IAAI,EAAE,MAAM,GAAG,SAAS;gBAAxB,IAAI,EAAE,MAAM,GAAG,SAAS,EACxC,OAAO,EAAE,MAAM,GAAG,SAAS;CAIlC;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC5B;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;;OAIG;IACH,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IAE5C;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;CACrC;AAED;;GAEG;AACH,MAAM,WAAW,iCAAiC;IAC9C;;;OAGG;IACH,oBAAoB,EAAE,MAAM,CAAC;IAE7B;;;OAGG;IACH,wBAAwB,EAAE,MAAM,CAAC;IAEjC;;;OAGG;IACH,2BAA2B,EAAE,MAAM,CAAC;IAEpC;;;OAGG;IACH,UAAU,EAAE,MAAM,CAAC;CACtB;AAED;;GAEG;AACH,MAAM,MAAM,oCAAoC,GAAG;IAC/C;;;;;;;;;;;;;OAaG;IACH,YAAY,CAAC,EAAE,mBAAmB,CAAC;IAEnC;;OAEG;IACH,WAAW,CAAC,EAAE,WAAW,CAAC;IAE1B;;OAEG;IACH,KAAK,CAAC,EAAE,SAAS,CAAC;IAElB;;OAEG;IACH,mBAAmB,CAAC,EAAE,iCAAiC,CAAC;IAExD;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB,CAAC;AAE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GACpF,OAAO,CAAC,IAAI,CAAC;IAoJhB,IAAI,SAAS,IAAI,MAAM,GAAG,SAAS,CAElC;IAED;;;;;;;;;;OAUG;IACG,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;IA8BvC,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAGzC,IAAI,eAAe,IAAI,MAAM,GAAG,SAAS,CAExC;CACJ"} \ No newline at end of file diff --git a/dist/esm/client/streamableHttp.js b/dist/esm/client/streamableHttp.js deleted file mode 100644 index 808dc097d0..0000000000 --- a/dist/esm/client/streamableHttp.js +++ /dev/null @@ -1,421 +0,0 @@ -import { createFetchWithInit, normalizeHeaders } from '../shared/transport.js'; -import { isInitializedNotification, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessageSchema } from '../types.js'; -import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js'; -import { EventSourceParserStream } from 'eventsource-parser/stream'; -// Default reconnection options for StreamableHTTP connections -const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = { - initialReconnectionDelay: 1000, - maxReconnectionDelay: 30000, - reconnectionDelayGrowFactor: 1.5, - maxRetries: 2 -}; -export class StreamableHTTPError extends Error { - constructor(code, message) { - super(`Streamable HTTP error: ${message}`); - this.code = code; - } -} -/** - * Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. - * It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events - * for receiving messages. - */ -export class StreamableHTTPClientTransport { - constructor(url, opts) { - var _a; - this._hasCompletedAuthFlow = false; // Circuit breaker: detect auth success followed by immediate 401 - this._url = url; - this._resourceMetadataUrl = undefined; - this._scope = undefined; - this._requestInit = opts === null || opts === void 0 ? void 0 : opts.requestInit; - this._authProvider = opts === null || opts === void 0 ? void 0 : opts.authProvider; - this._fetch = opts === null || opts === void 0 ? void 0 : opts.fetch; - this._fetchWithInit = createFetchWithInit(opts === null || opts === void 0 ? void 0 : opts.fetch, opts === null || opts === void 0 ? void 0 : opts.requestInit); - this._sessionId = opts === null || opts === void 0 ? void 0 : opts.sessionId; - this._reconnectionOptions = (_a = opts === null || opts === void 0 ? void 0 : opts.reconnectionOptions) !== null && _a !== void 0 ? _a : DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS; - } - async _authThenStart() { - var _a; - if (!this._authProvider) { - throw new UnauthorizedError('No auth provider'); - } - let result; - try { - result = await auth(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetchWithInit - }); - } - catch (error) { - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - throw error; - } - if (result !== 'AUTHORIZED') { - throw new UnauthorizedError(); - } - return await this._startOrAuthSse({ resumptionToken: undefined }); - } - async _commonHeaders() { - var _a; - const headers = {}; - if (this._authProvider) { - const tokens = await this._authProvider.tokens(); - if (tokens) { - headers['Authorization'] = `Bearer ${tokens.access_token}`; - } - } - if (this._sessionId) { - headers['mcp-session-id'] = this._sessionId; - } - if (this._protocolVersion) { - headers['mcp-protocol-version'] = this._protocolVersion; - } - const extraHeaders = normalizeHeaders((_a = this._requestInit) === null || _a === void 0 ? void 0 : _a.headers); - return new Headers({ - ...headers, - ...extraHeaders - }); - } - async _startOrAuthSse(options) { - var _a, _b, _c; - const { resumptionToken } = options; - try { - // Try to open an initial SSE stream with GET to listen for server messages - // This is optional according to the spec - server may not support it - const headers = await this._commonHeaders(); - headers.set('Accept', 'text/event-stream'); - // Include Last-Event-ID header for resumable streams if provided - if (resumptionToken) { - headers.set('last-event-id', resumptionToken); - } - const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(this._url, { - method: 'GET', - headers, - signal: (_b = this._abortController) === null || _b === void 0 ? void 0 : _b.signal - }); - if (!response.ok) { - if (response.status === 401 && this._authProvider) { - // Need to authenticate - return await this._authThenStart(); - } - // 405 indicates that the server does not offer an SSE stream at GET endpoint - // This is an expected case that should not trigger an error - if (response.status === 405) { - return; - } - throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`); - } - this._handleSseStream(response.body, options, true); - } - catch (error) { - (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error); - throw error; - } - } - /** - * Calculates the next reconnection delay using backoff algorithm - * - * @param attempt Current reconnection attempt count for the specific stream - * @returns Time to wait in milliseconds before next reconnection attempt - */ - _getNextReconnectionDelay(attempt) { - // Access default values directly, ensuring they're never undefined - const initialDelay = this._reconnectionOptions.initialReconnectionDelay; - const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor; - const maxDelay = this._reconnectionOptions.maxReconnectionDelay; - // Cap at maximum delay - return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay); - } - /** - * Schedule a reconnection attempt with exponential backoff - * - * @param lastEventId The ID of the last received event for resumability - * @param attemptCount Current reconnection attempt count for this specific stream - */ - _scheduleReconnection(options, attemptCount = 0) { - var _a; - // Use provided options or default options - const maxRetries = this._reconnectionOptions.maxRetries; - // Check if we've exceeded maximum retry attempts - if (maxRetries > 0 && attemptCount >= maxRetries) { - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`)); - return; - } - // Calculate next delay based on current attempt count - const delay = this._getNextReconnectionDelay(attemptCount); - // Schedule the reconnection - setTimeout(() => { - // Use the last event ID to resume where we left off - this._startOrAuthSse(options).catch(error => { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(`Failed to reconnect SSE stream: ${error instanceof Error ? error.message : String(error)}`)); - // Schedule another attempt if this one failed, incrementing the attempt counter - this._scheduleReconnection(options, attemptCount + 1); - }); - }, delay); - } - _handleSseStream(stream, options, isReconnectable) { - if (!stream) { - return; - } - const { onresumptiontoken, replayMessageId } = options; - let lastEventId; - const processStream = async () => { - var _a, _b, _c, _d; - // this is the closest we can get to trying to catch network errors - // if something happens reader will throw - try { - // Create a pipeline: binary stream -> text decoder -> SSE parser - const reader = stream - .pipeThrough(new TextDecoderStream()) - .pipeThrough(new EventSourceParserStream()) - .getReader(); - while (true) { - const { value: event, done } = await reader.read(); - if (done) { - break; - } - // Update last event ID if provided - if (event.id) { - lastEventId = event.id; - onresumptiontoken === null || onresumptiontoken === void 0 ? void 0 : onresumptiontoken(event.id); - } - if (!event.event || event.event === 'message') { - try { - const message = JSONRPCMessageSchema.parse(JSON.parse(event.data)); - if (replayMessageId !== undefined && isJSONRPCResponse(message)) { - message.id = replayMessageId; - } - (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message); - } - catch (error) { - (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); - } - } - } - } - catch (error) { - // Handle stream errors - likely a network disconnect - (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, new Error(`SSE stream disconnected: ${error}`)); - // Attempt to reconnect if the stream disconnects unexpectedly and we aren't closing - if (isReconnectable && this._abortController && !this._abortController.signal.aborted) { - // Use the exponential backoff reconnection strategy - try { - this._scheduleReconnection({ - resumptionToken: lastEventId, - onresumptiontoken, - replayMessageId - }, 0); - } - catch (error) { - (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, new Error(`Failed to reconnect: ${error instanceof Error ? error.message : String(error)}`)); - } - } - } - }; - processStream(); - } - async start() { - if (this._abortController) { - throw new Error('StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.'); - } - this._abortController = new AbortController(); - } - /** - * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth. - */ - async finishAuth(authorizationCode) { - if (!this._authProvider) { - throw new UnauthorizedError('No auth provider'); - } - const result = await auth(this._authProvider, { - serverUrl: this._url, - authorizationCode, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetchWithInit - }); - if (result !== 'AUTHORIZED') { - throw new UnauthorizedError('Failed to authorize'); - } - } - async close() { - var _a, _b; - // Abort any pending requests - (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.abort(); - (_b = this.onclose) === null || _b === void 0 ? void 0 : _b.call(this); - } - async send(message, options) { - var _a, _b, _c, _d; - try { - const { resumptionToken, onresumptiontoken } = options || {}; - if (resumptionToken) { - // If we have at last event ID, we need to reconnect the SSE stream - this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : undefined }).catch(err => { var _a; return (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, err); }); - return; - } - const headers = await this._commonHeaders(); - headers.set('content-type', 'application/json'); - headers.set('accept', 'application/json, text/event-stream'); - const init = { - ...this._requestInit, - method: 'POST', - headers, - body: JSON.stringify(message), - signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal - }; - const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._url, init); - // Handle session ID received during initialization - const sessionId = response.headers.get('mcp-session-id'); - if (sessionId) { - this._sessionId = sessionId; - } - if (!response.ok) { - if (response.status === 401 && this._authProvider) { - // Prevent infinite recursion when server returns 401 after successful auth - if (this._hasCompletedAuthFlow) { - throw new StreamableHTTPError(401, 'Server returned 401 after successful authentication'); - } - const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response); - this._resourceMetadataUrl = resourceMetadataUrl; - this._scope = scope; - const result = await auth(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetchWithInit - }); - if (result !== 'AUTHORIZED') { - throw new UnauthorizedError(); - } - // Mark that we completed auth flow - this._hasCompletedAuthFlow = true; - // Purposely _not_ awaited, so we don't call onerror twice - return this.send(message); - } - if (response.status === 403 && this._authProvider) { - const { resourceMetadataUrl, scope, error } = extractWWWAuthenticateParams(response); - if (error === 'insufficient_scope') { - const wwwAuthHeader = response.headers.get('WWW-Authenticate'); - // Check if we've already tried upscoping with this header to prevent infinite loops. - if (this._lastUpscopingHeader === wwwAuthHeader) { - throw new StreamableHTTPError(403, 'Server returned 403 after trying upscoping'); - } - if (scope) { - this._scope = scope; - } - if (resourceMetadataUrl) { - this._resourceMetadataUrl = resourceMetadataUrl; - } - // Mark that upscoping was tried. - this._lastUpscopingHeader = wwwAuthHeader !== null && wwwAuthHeader !== void 0 ? wwwAuthHeader : undefined; - const result = await auth(this._authProvider, { - serverUrl: this._url, - resourceMetadataUrl: this._resourceMetadataUrl, - scope: this._scope, - fetchFn: this._fetch - }); - if (result !== 'AUTHORIZED') { - throw new UnauthorizedError(); - } - return this.send(message); - } - } - const text = await response.text().catch(() => null); - throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`); - } - // Reset auth loop flag on successful response - this._hasCompletedAuthFlow = false; - this._lastUpscopingHeader = undefined; - // If the response is 202 Accepted, there's no body to process - if (response.status === 202) { - // if the accepted notification is initialized, we start the SSE stream - // if it's supported by the server - if (isInitializedNotification(message)) { - // Start without a lastEventId since this is a fresh connection - this._startOrAuthSse({ resumptionToken: undefined }).catch(err => { var _a; return (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, err); }); - } - return; - } - // Get original message(s) for detecting request IDs - const messages = Array.isArray(message) ? message : [message]; - const hasRequests = messages.filter(msg => 'method' in msg && 'id' in msg && msg.id !== undefined).length > 0; - // Check the response type - const contentType = response.headers.get('content-type'); - if (hasRequests) { - if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('text/event-stream')) { - // Handle SSE stream responses for requests - // We use the same handler as standalone streams, which now supports - // reconnection with the last event ID - this._handleSseStream(response.body, { onresumptiontoken }, false); - } - else if (contentType === null || contentType === void 0 ? void 0 : contentType.includes('application/json')) { - // For non-streaming servers, we might get direct JSON responses - const data = await response.json(); - const responseMessages = Array.isArray(data) - ? data.map(msg => JSONRPCMessageSchema.parse(msg)) - : [JSONRPCMessageSchema.parse(data)]; - for (const msg of responseMessages) { - (_c = this.onmessage) === null || _c === void 0 ? void 0 : _c.call(this, msg); - } - } - else { - throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`); - } - } - } - catch (error) { - (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error); - throw error; - } - } - get sessionId() { - return this._sessionId; - } - /** - * Terminates the current session by sending a DELETE request to the server. - * - * Clients that no longer need a particular session - * (e.g., because the user is leaving the client application) SHOULD send an - * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly - * terminate the session. - * - * The server MAY respond with HTTP 405 Method Not Allowed, indicating that - * the server does not allow clients to terminate sessions. - */ - async terminateSession() { - var _a, _b, _c; - if (!this._sessionId) { - return; // No session to terminate - } - try { - const headers = await this._commonHeaders(); - const init = { - ...this._requestInit, - method: 'DELETE', - headers, - signal: (_a = this._abortController) === null || _a === void 0 ? void 0 : _a.signal - }; - const response = await ((_b = this._fetch) !== null && _b !== void 0 ? _b : fetch)(this._url, init); - // We specifically handle 405 as a valid response according to the spec, - // meaning the server does not support explicit session termination - if (!response.ok && response.status !== 405) { - throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`); - } - this._sessionId = undefined; - } - catch (error) { - (_c = this.onerror) === null || _c === void 0 ? void 0 : _c.call(this, error); - throw error; - } - } - setProtocolVersion(version) { - this._protocolVersion = version; - } - get protocolVersion() { - return this._protocolVersion; - } -} -//# sourceMappingURL=streamableHttp.js.map \ No newline at end of file diff --git a/dist/esm/client/streamableHttp.js.map b/dist/esm/client/streamableHttp.js.map deleted file mode 100644 index e86b4545bc..0000000000 --- a/dist/esm/client/streamableHttp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"streamableHttp.js","sourceRoot":"","sources":["../../../src/client/streamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwB,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAE,yBAAyB,EAAE,gBAAgB,EAAE,iBAAiB,EAAkB,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACnI,OAAO,EAAE,IAAI,EAAc,4BAA4B,EAAuB,iBAAiB,EAA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AG,KAAc,CAAC,CAAC;YAC/B,MAAM,KAAK,CAAC;QAChB,CAAC;IACL,CAAC;IAED,kBAAkB,CAAC,OAAe;QAC9B,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;IACpC,CAAC;IACD,IAAI,eAAe;QACf,OAAO,IAAI,CAAC,gBAAgB,CAAC;IACjC,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/client/websocket.d.ts b/dist/esm/client/websocket.d.ts deleted file mode 100644 index 78f95de3b9..0000000000 --- a/dist/esm/client/websocket.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Transport } from '../shared/transport.js'; -import { JSONRPCMessage } from '../types.js'; -/** - * Client transport for WebSocket: this will connect to a server over the WebSocket protocol. - */ -export declare class WebSocketClientTransport implements Transport { - private _socket?; - private _url; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage) => void; - constructor(url: URL); - start(): Promise; - close(): Promise; - send(message: JSONRPCMessage): Promise; -} -//# sourceMappingURL=websocket.d.ts.map \ No newline at end of file diff --git a/dist/esm/client/websocket.d.ts.map b/dist/esm/client/websocket.d.ts.map deleted file mode 100644 index 2882d98226..0000000000 --- a/dist/esm/client/websocket.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"websocket.d.ts","sourceRoot":"","sources":["../../../src/client/websocket.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AAInE;;GAEG;AACH,qBAAa,wBAAyB,YAAW,SAAS;IACtD,OAAO,CAAC,OAAO,CAAC,CAAY;IAC5B,OAAO,CAAC,IAAI,CAAM;IAElB,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;gBAElC,GAAG,EAAE,GAAG;IAIpB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAsChB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAW/C"} \ No newline at end of file diff --git a/dist/esm/client/websocket.js b/dist/esm/client/websocket.js deleted file mode 100644 index d55feabeb7..0000000000 --- a/dist/esm/client/websocket.js +++ /dev/null @@ -1,59 +0,0 @@ -import { JSONRPCMessageSchema } from '../types.js'; -const SUBPROTOCOL = 'mcp'; -/** - * Client transport for WebSocket: this will connect to a server over the WebSocket protocol. - */ -export class WebSocketClientTransport { - constructor(url) { - this._url = url; - } - start() { - if (this._socket) { - throw new Error('WebSocketClientTransport already started! If using Client class, note that connect() calls start() automatically.'); - } - return new Promise((resolve, reject) => { - this._socket = new WebSocket(this._url, SUBPROTOCOL); - this._socket.onerror = event => { - var _a; - const error = 'error' in event ? event.error : new Error(`WebSocket error: ${JSON.stringify(event)}`); - reject(error); - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }; - this._socket.onopen = () => { - resolve(); - }; - this._socket.onclose = () => { - var _a; - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - }; - this._socket.onmessage = (event) => { - var _a, _b; - let message; - try { - message = JSONRPCMessageSchema.parse(JSON.parse(event.data)); - } - catch (error) { - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - return; - } - (_b = this.onmessage) === null || _b === void 0 ? void 0 : _b.call(this, message); - }; - }); - } - async close() { - var _a; - (_a = this._socket) === null || _a === void 0 ? void 0 : _a.close(); - } - send(message) { - return new Promise((resolve, reject) => { - var _a; - if (!this._socket) { - reject(new Error('Not connected')); - return; - } - (_a = this._socket) === null || _a === void 0 ? void 0 : _a.send(JSON.stringify(message)); - resolve(); - }); - } -} -//# sourceMappingURL=websocket.js.map \ No newline at end of file diff --git a/dist/esm/client/websocket.js.map b/dist/esm/client/websocket.js.map deleted file mode 100644 index 616164b1d9..0000000000 --- a/dist/esm/client/websocket.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"websocket.js","sourceRoot":"","sources":["../../../src/client/websocket.ts"],"names":[],"mappings":"AACA,OAAO,EAAkB,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnE,MAAM,WAAW,GAAG,KAAK,CAAC;AAE1B;;GAEG;AACH,MAAM,OAAO,wBAAwB;IAQjC,YAAY,GAAQ;QAChB,IAAI,CAAC,IAAI,GAAG,GAAG,CAAC;IACpB,CAAC;IAED,KAAK;QACD,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACf,MAAM,IAAI,KAAK,CACX,mHAAmH,CACtH,CAAC;QACN,CAAC;QAED,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACnC,IAAI,CAAC,OAAO,GAAG,IAAI,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;YAErD,IAAI,CAAC,OAAO,CAAC,OAAO,GAAG,KAAK,CAAC,EAAE;;gBAC3B,MAAM,KAAK,GAAG,OAAO,IAAI,KAAK,CAAC,CAAC,CAAE,KAAK,CAAC,KAAe,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,oBAAoB,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;gBACjH,MAAM,CAAC,KAAK,CAAC,CAAC;gBACd,MAAA,IAAI,CAAC,OAAO,qDAAG,KAAK,CAAC,CAAC;YAC1B,CAAC,CAAC;YAEF,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,GAAG,EAAE;gBACvB,OAAO,EAAE,CAAC;YACd,CAAC,CAAC;YAEF,IAAI,CAAC,OAAO,CAAC,OAAO,GAAG,GAAG,EAAE;;gBACxB,MAAA,IAAI,CAAC,OAAO,oDAAI,CAAC;YACrB,CAAC,CAAC;YAEF,IAAI,CAAC,OAAO,CAAC,SAAS,GAAG,CAAC,KAAmB,EAAE,EAAE;;gBAC7C,IAAI,OAAuB,CAAC;gBAC5B,IAAI,CAAC;oBACD,OAAO,GAAG,oBAAoB,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;gBACjE,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACb,MAAA,IAAI,CAAC,OAAO,qDAAG,KAAc,CAAC,CAAC;oBAC/B,OAAO;gBACX,CAAC;gBAED,MAAA,IAAI,CAAC,SAAS,qDAAG,OAAO,CAAC,CAAC;YAC9B,CAAC,CAAC;QACN,CAAC,CAAC,CAAC;IACP,CAAC;IAED,KAAK,CAAC,KAAK;;QACP,MAAA,IAAI,CAAC,OAAO,0CAAE,KAAK,EAAE,CAAC;IAC1B,CAAC;IAED,IAAI,CAAC,OAAuB;QACxB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;;YACnC,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;gBAChB,MAAM,CAAC,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC,CAAC;gBACnC,OAAO;YACX,CAAC;YAED,MAAA,IAAI,CAAC,OAAO,0CAAE,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;YAC5C,OAAO,EAAE,CAAC;QACd,CAAC,CAAC,CAAC;IACP,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/examples/client/elicitationUrlExample.d.ts b/dist/esm/examples/client/elicitationUrlExample.d.ts deleted file mode 100644 index 611f6eba22..0000000000 --- a/dist/esm/examples/client/elicitationUrlExample.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=elicitationUrlExample.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/client/elicitationUrlExample.d.ts.map b/dist/esm/examples/client/elicitationUrlExample.d.ts.map deleted file mode 100644 index e749adfb95..0000000000 --- a/dist/esm/examples/client/elicitationUrlExample.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"elicitationUrlExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/elicitationUrlExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/client/elicitationUrlExample.js b/dist/esm/examples/client/elicitationUrlExample.js deleted file mode 100644 index 741e83d3ed..0000000000 --- a/dist/esm/examples/client/elicitationUrlExample.js +++ /dev/null @@ -1,691 +0,0 @@ -// Run with: npx tsx src/examples/client/elicitationUrlExample.ts -// -// This example demonstrates how to use URL elicitation to securely -// collect user input in a remote (HTTP) server. -// URL elicitation allows servers to prompt the end-user to open a URL in their browser -// to collect sensitive information. -import { Client } from '../../client/index.js'; -import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; -import { createInterface } from 'node:readline'; -import { ListToolsResultSchema, CallToolResultSchema, ElicitRequestSchema, McpError, ErrorCode, UrlElicitationRequiredError, ElicitationCompleteNotificationSchema } from '../../types.js'; -import { getDisplayName } from '../../shared/metadataUtils.js'; -import { exec } from 'node:child_process'; -import { InMemoryOAuthClientProvider } from './simpleOAuthClientProvider.js'; -import { UnauthorizedError } from '../../client/auth.js'; -import { createServer } from 'node:http'; -// Set up OAuth (required for this example) -const OAUTH_CALLBACK_PORT = 8090; // Use different port than auth server (3001) -const OAUTH_CALLBACK_URL = `http://localhost:${OAUTH_CALLBACK_PORT}/callback`; -let oauthProvider = undefined; -console.log('Getting OAuth token...'); -const clientMetadata = { - client_name: 'Elicitation MCP Client', - redirect_uris: [OAUTH_CALLBACK_URL], - grant_types: ['authorization_code', 'refresh_token'], - response_types: ['code'], - token_endpoint_auth_method: 'client_secret_post', - scope: 'mcp:tools' -}; -oauthProvider = new InMemoryOAuthClientProvider(OAUTH_CALLBACK_URL, clientMetadata, (redirectUrl) => { - console.log(`🌐 Opening browser for OAuth redirect: ${redirectUrl.toString()}`); - openBrowser(redirectUrl.toString()); -}); -// Create readline interface for user input -const readline = createInterface({ - input: process.stdin, - output: process.stdout -}); -let abortCommand = new AbortController(); -// Global client and transport for interactive commands -let client = null; -let transport = null; -let serverUrl = 'http://localhost:3000/mcp'; -let sessionId = undefined; -let isProcessingCommand = false; -let isProcessingElicitations = false; -const elicitationQueue = []; -let elicitationQueueSignal = null; -let elicitationsCompleteSignal = null; -// Map to track pending URL elicitations waiting for completion notifications -const pendingURLElicitations = new Map(); -async function main() { - console.log('MCP Interactive Client'); - console.log('====================='); - // Connect to server immediately with default settings - await connect(); - // Start the elicitation loop in the background - elicitationLoop().catch(error => { - console.error('Unexpected error in elicitation loop:', error); - process.exit(1); - }); - // Short delay allowing the server to send any SSE elicitations on connection - await new Promise(resolve => setTimeout(resolve, 200)); - // Wait until we are done processing any initial elicitations - await waitForElicitationsToComplete(); - // Print help and start the command loop - printHelp(); - await commandLoop(); -} -async function waitForElicitationsToComplete() { - // Wait until the queue is empty and nothing is being processed - while (elicitationQueue.length > 0 || isProcessingElicitations) { - await new Promise(resolve => setTimeout(resolve, 100)); - } -} -function printHelp() { - console.log('\nAvailable commands:'); - console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)'); - console.log(' disconnect - Disconnect from server'); - console.log(' terminate-session - Terminate the current session'); - console.log(' reconnect - Reconnect to the server'); - console.log(' list-tools - List available tools'); - console.log(' call-tool [args] - Call a tool with optional JSON arguments'); - console.log(' payment-confirm - Test URL elicitation via error response with payment-confirm tool'); - console.log(' third-party-auth - Test tool that requires third-party OAuth credentials'); - console.log(' help - Show this help'); - console.log(' quit - Exit the program'); -} -async function commandLoop() { - await new Promise(resolve => { - if (!isProcessingElicitations) { - resolve(); - } - else { - elicitationsCompleteSignal = resolve; - } - }); - readline.question('\n> ', { signal: abortCommand.signal }, async (input) => { - var _a; - isProcessingCommand = true; - const args = input.trim().split(/\s+/); - const command = (_a = args[0]) === null || _a === void 0 ? void 0 : _a.toLowerCase(); - try { - switch (command) { - case 'connect': - await connect(args[1]); - break; - case 'disconnect': - await disconnect(); - break; - case 'terminate-session': - await terminateSession(); - break; - case 'reconnect': - await reconnect(); - break; - case 'list-tools': - await listTools(); - break; - case 'call-tool': - if (args.length < 2) { - console.log('Usage: call-tool [args]'); - } - else { - const toolName = args[1]; - let toolArgs = {}; - if (args.length > 2) { - try { - toolArgs = JSON.parse(args.slice(2).join(' ')); - } - catch (_b) { - console.log('Invalid JSON arguments. Using empty args.'); - } - } - await callTool(toolName, toolArgs); - } - break; - case 'payment-confirm': - await callPaymentConfirmTool(); - break; - case 'third-party-auth': - await callThirdPartyAuthTool(); - break; - case 'help': - printHelp(); - break; - case 'quit': - case 'exit': - await cleanup(); - return; - default: - if (command) { - console.log(`Unknown command: ${command}`); - } - break; - } - } - catch (error) { - console.error(`Error executing command: ${error}`); - } - finally { - isProcessingCommand = false; - } - // Process another command after we've processed the this one - await commandLoop(); - }); -} -async function elicitationLoop() { - while (true) { - // Wait until we have elicitations to process - await new Promise(resolve => { - if (elicitationQueue.length > 0) { - resolve(); - } - else { - elicitationQueueSignal = resolve; - } - }); - isProcessingElicitations = true; - abortCommand.abort(); // Abort the command loop if it's running - // Process all queued elicitations - while (elicitationQueue.length > 0) { - const queued = elicitationQueue.shift(); - console.log(`📤 Processing queued elicitation (${elicitationQueue.length} remaining)`); - try { - const result = await handleElicitationRequest(queued.request); - queued.resolve(result); - } - catch (error) { - queued.reject(error instanceof Error ? error : new Error(String(error))); - } - } - console.log('✅ All queued elicitations processed. Resuming command loop...\n'); - isProcessingElicitations = false; - // Reset the abort controller for the next command loop - abortCommand = new AbortController(); - // Resume the command loop - if (elicitationsCompleteSignal) { - elicitationsCompleteSignal(); - elicitationsCompleteSignal = null; - } - } -} -async function openBrowser(url) { - const command = `open "${url}"`; - exec(command, error => { - if (error) { - console.error(`Failed to open browser: ${error.message}`); - console.log(`Please manually open: ${url}`); - } - }); -} -/** - * Enqueues an elicitation request and returns the result. - * - * This function is used so that our CLI (which can only handle one input request at a time) - * can handle elicitation requests and the command loop. - * - * @param request - The elicitation request to be handled - * @returns The elicitation result - */ -async function elicitationRequestHandler(request) { - // If we are processing a command, handle this elicitation immediately - if (isProcessingCommand) { - console.log('📋 Processing elicitation immediately (during command execution)'); - return await handleElicitationRequest(request); - } - // Otherwise, queue the request to be handled by the elicitation loop - console.log(`📥 Queueing elicitation request (queue size will be: ${elicitationQueue.length + 1})`); - return new Promise((resolve, reject) => { - elicitationQueue.push({ - request, - resolve, - reject - }); - // Signal the elicitation loop that there's work to do - if (elicitationQueueSignal) { - elicitationQueueSignal(); - elicitationQueueSignal = null; - } - }); -} -/** - * Handles an elicitation request. - * - * This function is used to handle the elicitation request and return the result. - * - * @param request - The elicitation request to be handled - * @returns The elicitation result - */ -async function handleElicitationRequest(request) { - const mode = request.params.mode; - console.log('\n🔔 Elicitation Request Received:'); - console.log(`Mode: ${mode}`); - if (mode === 'url') { - return { - action: await handleURLElicitation(request.params) - }; - } - else { - // Should not happen because the client declares its capabilities to the server, - // but being defensive is a good practice: - throw new McpError(ErrorCode.InvalidParams, `Unsupported elicitation mode: ${mode}`); - } -} -/** - * Handles a URL elicitation by opening the URL in the browser. - * - * Note: This is a shared code for both request handlers and error handlers. - * As a result of sharing schema, there is no big forking of logic for the client. - * - * @param params - The URL elicitation request parameters - * @returns The action to take (accept, cancel, or decline) - */ -async function handleURLElicitation(params) { - const url = params.url; - const elicitationId = params.elicitationId; - const message = params.message; - console.log(`🆔 Elicitation ID: ${elicitationId}`); // Print for illustration - // Parse URL to show domain for security - let domain = 'unknown domain'; - try { - const parsedUrl = new URL(url); - domain = parsedUrl.hostname; - } - catch (_a) { - console.error('Invalid URL provided by server'); - return 'decline'; - } - // Example security warning to help prevent phishing attacks - console.log('\n⚠️ \x1b[33mSECURITY WARNING\x1b[0m ⚠️'); - console.log('\x1b[33mThe server is requesting you to open an external URL.\x1b[0m'); - console.log('\x1b[33mOnly proceed if you trust this server and understand why it needs this.\x1b[0m\n'); - console.log(`🌐 Target domain: \x1b[36m${domain}\x1b[0m`); - console.log(`🔗 Full URL: \x1b[36m${url}\x1b[0m`); - console.log(`\nℹ️ Server's reason:\n\n\x1b[36m${message}\x1b[0m\n`); - // 1. Ask for user consent to open the URL - const consent = await new Promise(resolve => { - readline.question('\nDo you want to open this URL in your browser? (y/n): ', input => { - resolve(input.trim().toLowerCase()); - }); - }); - // 2. If user did not consent, return appropriate result - if (consent === 'no' || consent === 'n') { - console.log('❌ URL navigation declined.'); - return 'decline'; - } - else if (consent !== 'yes' && consent !== 'y') { - console.log('🚫 Invalid response. Cancelling elicitation.'); - return 'cancel'; - } - // 3. Wait for completion notification in the background - const completionPromise = new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - pendingURLElicitations.delete(elicitationId); - console.log(`\x1b[31m❌ Elicitation ${elicitationId} timed out waiting for completion.\x1b[0m`); - reject(new Error('Elicitation completion timeout')); - }, 5 * 60 * 1000); // 5 minute timeout - pendingURLElicitations.set(elicitationId, { - resolve: () => { - clearTimeout(timeout); - resolve(); - }, - reject, - timeout - }); - }); - completionPromise.catch(error => { - console.error('Background completion wait failed:', error); - }); - // 4. Open the URL in the browser - console.log(`\n🚀 Opening browser to: ${url}`); - await openBrowser(url); - console.log('\n⏳ Waiting for you to complete the interaction in your browser...'); - console.log(' The server will send a notification once you complete the action.'); - // 5. Acknowledge the user accepted the elicitation - return 'accept'; -} -/** - * Example OAuth callback handler - in production, use a more robust approach - * for handling callbacks and storing tokens - */ -/** - * Starts a temporary HTTP server to receive the OAuth callback - */ -async function waitForOAuthCallback() { - return new Promise((resolve, reject) => { - const server = createServer((req, res) => { - // Ignore favicon requests - if (req.url === '/favicon.ico') { - res.writeHead(404); - res.end(); - return; - } - console.log(`📥 Received callback: ${req.url}`); - const parsedUrl = new URL(req.url || '', 'http://localhost'); - const code = parsedUrl.searchParams.get('code'); - const error = parsedUrl.searchParams.get('error'); - if (code) { - console.log(`✅ Authorization code received: ${code === null || code === void 0 ? void 0 : code.substring(0, 10)}...`); - res.writeHead(200, { 'Content-Type': 'text/html' }); - res.end(` - - -

Authorization Successful!

-

This simulates successful authorization of the MCP client, which now has an access token for the MCP server.

-

This window will close automatically in 10 seconds.

- - - - `); - resolve(code); - setTimeout(() => server.close(), 15000); - } - else if (error) { - console.log(`❌ Authorization error: ${error}`); - res.writeHead(400, { 'Content-Type': 'text/html' }); - res.end(` - - -

Authorization Failed

-

Error: ${error}

- - - `); - reject(new Error(`OAuth authorization failed: ${error}`)); - } - else { - console.log(`❌ No authorization code or error in callback`); - res.writeHead(400); - res.end('Bad request'); - reject(new Error('No authorization code provided')); - } - }); - server.listen(OAUTH_CALLBACK_PORT, () => { - console.log(`OAuth callback server started on http://localhost:${OAUTH_CALLBACK_PORT}`); - }); - }); -} -/** - * Attempts to connect to the MCP server with OAuth authentication. - * Handles OAuth flow recursively if authorization is required. - */ -async function attemptConnection(oauthProvider) { - console.log('🚢 Creating transport with OAuth provider...'); - const baseUrl = new URL(serverUrl); - transport = new StreamableHTTPClientTransport(baseUrl, { - sessionId: sessionId, - authProvider: oauthProvider - }); - console.log('🚢 Transport created'); - try { - console.log('🔌 Attempting connection (this will trigger OAuth redirect if needed)...'); - await client.connect(transport); - sessionId = transport.sessionId; - console.log('Transport created with session ID:', sessionId); - console.log('✅ Connected successfully'); - } - catch (error) { - if (error instanceof UnauthorizedError) { - console.log('🔐 OAuth required - waiting for authorization...'); - const callbackPromise = waitForOAuthCallback(); - const authCode = await callbackPromise; - await transport.finishAuth(authCode); - console.log('🔐 Authorization code received:', authCode); - console.log('🔌 Reconnecting with authenticated transport...'); - // Recursively retry connection after OAuth completion - await attemptConnection(oauthProvider); - } - else { - console.error('❌ Connection failed with non-auth error:', error); - throw error; - } - } -} -async function connect(url) { - if (client) { - console.log('Already connected. Disconnect first.'); - return; - } - if (url) { - serverUrl = url; - } - console.log(`🔗 Attempting to connect to ${serverUrl}...`); - // Create a new client with elicitation capability - console.log('👤 Creating MCP client...'); - client = new Client({ - name: 'example-client', - version: '1.0.0' - }, { - capabilities: { - elicitation: { - // Only URL elicitation is supported in this demo - // (see server/elicitationExample.ts for a demo of form mode elicitation) - url: {} - } - } - }); - console.log('👤 Client created'); - // Set up elicitation request handler with proper validation - client.setRequestHandler(ElicitRequestSchema, elicitationRequestHandler); - // Set up notification handler for elicitation completion - client.setNotificationHandler(ElicitationCompleteNotificationSchema, notification => { - const { elicitationId } = notification.params; - const pending = pendingURLElicitations.get(elicitationId); - if (pending) { - clearTimeout(pending.timeout); - pendingURLElicitations.delete(elicitationId); - console.log(`\x1b[32m✅ Elicitation ${elicitationId} completed!\x1b[0m`); - pending.resolve(); - } - else { - // Shouldn't happen - discard it! - console.warn(`Received completion notification for unknown elicitation: ${elicitationId}`); - } - }); - try { - console.log('🔐 Starting OAuth flow...'); - await attemptConnection(oauthProvider); - console.log('Connected to MCP server'); - // Set up error handler after connection is established so we don't double log errors - client.onerror = error => { - console.error('\x1b[31mClient error:', error, '\x1b[0m'); - }; - } - catch (error) { - console.error('Failed to connect:', error); - client = null; - transport = null; - return; - } -} -async function disconnect() { - if (!client || !transport) { - console.log('Not connected.'); - return; - } - try { - await transport.close(); - console.log('Disconnected from MCP server'); - client = null; - transport = null; - } - catch (error) { - console.error('Error disconnecting:', error); - } -} -async function terminateSession() { - if (!client || !transport) { - console.log('Not connected.'); - return; - } - try { - console.log('Terminating session with ID:', transport.sessionId); - await transport.terminateSession(); - console.log('Session terminated successfully'); - // Check if sessionId was cleared after termination - if (!transport.sessionId) { - console.log('Session ID has been cleared'); - sessionId = undefined; - // Also close the transport and clear client objects - await transport.close(); - console.log('Transport closed after session termination'); - client = null; - transport = null; - } - else { - console.log('Server responded with 405 Method Not Allowed (session termination not supported)'); - console.log('Session ID is still active:', transport.sessionId); - } - } - catch (error) { - console.error('Error terminating session:', error); - } -} -async function reconnect() { - if (client) { - await disconnect(); - } - await connect(); -} -async function listTools() { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const toolsRequest = { - method: 'tools/list', - params: {} - }; - const toolsResult = await client.request(toolsRequest, ListToolsResultSchema); - console.log('Available tools:'); - if (toolsResult.tools.length === 0) { - console.log(' No tools available'); - } - else { - for (const tool of toolsResult.tools) { - console.log(` - id: ${tool.name}, name: ${getDisplayName(tool)}, description: ${tool.description}`); - } - } - } - catch (error) { - console.log(`Tools not supported by this server (${error})`); - } -} -async function callTool(name, args) { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const request = { - method: 'tools/call', - params: { - name, - arguments: args - } - }; - console.log(`Calling tool '${name}' with args:`, args); - const result = await client.request(request, CallToolResultSchema); - console.log('Tool result:'); - const resourceLinks = []; - result.content.forEach(item => { - if (item.type === 'text') { - console.log(` ${item.text}`); - } - else if (item.type === 'resource_link') { - const resourceLink = item; - resourceLinks.push(resourceLink); - console.log(` 📁 Resource Link: ${resourceLink.name}`); - console.log(` URI: ${resourceLink.uri}`); - if (resourceLink.mimeType) { - console.log(` Type: ${resourceLink.mimeType}`); - } - if (resourceLink.description) { - console.log(` Description: ${resourceLink.description}`); - } - } - else if (item.type === 'resource') { - console.log(` [Embedded Resource: ${item.resource.uri}]`); - } - else if (item.type === 'image') { - console.log(` [Image: ${item.mimeType}]`); - } - else if (item.type === 'audio') { - console.log(` [Audio: ${item.mimeType}]`); - } - else { - console.log(` [Unknown content type]:`, item); - } - }); - // Offer to read resource links - if (resourceLinks.length > 0) { - console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource ' to read their content.`); - } - } - catch (error) { - if (error instanceof UrlElicitationRequiredError) { - console.log('\n🔔 Elicitation Required Error Received:'); - console.log(`Message: ${error.message}`); - for (const e of error.elicitations) { - await handleURLElicitation(e); // For the error handler, we discard the action result because we don't respond to an error response - } - return; - } - console.log(`Error calling tool ${name}: ${error}`); - } -} -async function cleanup() { - if (client && transport) { - try { - // First try to terminate the session gracefully - if (transport.sessionId) { - try { - console.log('Terminating session before exit...'); - await transport.terminateSession(); - console.log('Session terminated successfully'); - } - catch (error) { - console.error('Error terminating session:', error); - } - } - // Then close the transport - await transport.close(); - } - catch (error) { - console.error('Error closing transport:', error); - } - } - process.stdin.setRawMode(false); - readline.close(); - console.log('\nGoodbye!'); - process.exit(0); -} -async function callPaymentConfirmTool() { - console.log('Calling payment-confirm tool...'); - await callTool('payment-confirm', { cartId: 'cart_123' }); -} -async function callThirdPartyAuthTool() { - console.log('Calling third-party-auth tool...'); - await callTool('third-party-auth', { param1: 'test' }); -} -// Set up raw mode for keyboard input to capture Escape key -process.stdin.setRawMode(true); -process.stdin.on('data', async (data) => { - // Check for Escape key (27) - if (data.length === 1 && data[0] === 27) { - console.log('\nESC key pressed. Disconnecting from server...'); - // Abort current operation and disconnect from server - if (client && transport) { - await disconnect(); - console.log('Disconnected. Press Enter to continue.'); - } - else { - console.log('Not connected to server.'); - } - // Re-display the prompt - process.stdout.write('> '); - } -}); -// Handle Ctrl+C -process.on('SIGINT', async () => { - console.log('\nReceived SIGINT. Cleaning up...'); - await cleanup(); -}); -// Start the interactive client -main().catch((error) => { - console.error('Error running MCP client:', error); - process.exit(1); -}); -//# sourceMappingURL=elicitationUrlExample.js.map \ No newline at end of file diff --git a/dist/esm/examples/client/elicitationUrlExample.js.map b/dist/esm/examples/client/elicitationUrlExample.js.map deleted file mode 100644 index 4b59163929..0000000000 --- a/dist/esm/examples/client/elicitationUrlExample.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"elicitationUrlExample.js","sourceRoot":"","sources":["../../../../src/examples/client/elicitationUrlExample.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,EAAE;AACF,mEAAmE;AACnE,gDAAgD;AAChD,uFAAuF;AACvF,oCAAoC;AAEpC,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAEH,qBAAqB,EAErB,oBAAoB,EACpB,mBAAmB,EAKnB,QAAQ,EACR,SA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AI,CAAC,CAAC;IAC/B,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,gBAAgB;AAChB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;IACjD,MAAM,OAAO,EAAE,CAAC;AACpB,CAAC,CAAC,CAAC;AAEH,+BAA+B;AAC/B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/client/multipleClientsParallel.d.ts b/dist/esm/examples/client/multipleClientsParallel.d.ts deleted file mode 100644 index 0ac5af8e56..0000000000 --- a/dist/esm/examples/client/multipleClientsParallel.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=multipleClientsParallel.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/client/multipleClientsParallel.d.ts.map b/dist/esm/examples/client/multipleClientsParallel.d.ts.map deleted file mode 100644 index 91051dc946..0000000000 --- a/dist/esm/examples/client/multipleClientsParallel.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"multipleClientsParallel.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/multipleClientsParallel.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/client/multipleClientsParallel.js b/dist/esm/examples/client/multipleClientsParallel.js deleted file mode 100644 index 4264856735..0000000000 --- a/dist/esm/examples/client/multipleClientsParallel.js +++ /dev/null @@ -1,132 +0,0 @@ -import { Client } from '../../client/index.js'; -import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; -import { CallToolResultSchema, LoggingMessageNotificationSchema } from '../../types.js'; -/** - * Multiple Clients MCP Example - * - * This client demonstrates how to: - * 1. Create multiple MCP clients in parallel - * 2. Each client calls a single tool - * 3. Track notifications from each client independently - */ -// Command line args processing -const args = process.argv.slice(2); -const serverUrl = args[0] || 'http://localhost:3000/mcp'; -async function createAndRunClient(config) { - console.log(`[${config.id}] Creating client: ${config.name}`); - const client = new Client({ - name: config.name, - version: '1.0.0' - }); - const transport = new StreamableHTTPClientTransport(new URL(serverUrl)); - // Set up client-specific error handler - client.onerror = error => { - console.error(`[${config.id}] Client error:`, error); - }; - // Set up client-specific notification handler - client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { - console.log(`[${config.id}] Notification: ${notification.params.data}`); - }); - try { - // Connect to the server - await client.connect(transport); - console.log(`[${config.id}] Connected to MCP server`); - // Call the specified tool - console.log(`[${config.id}] Calling tool: ${config.toolName}`); - const toolRequest = { - method: 'tools/call', - params: { - name: config.toolName, - arguments: { - ...config.toolArguments, - // Add client ID to arguments for identification in notifications - caller: config.id - } - } - }; - const result = await client.request(toolRequest, CallToolResultSchema); - console.log(`[${config.id}] Tool call completed`); - // Keep the connection open for a bit to receive notifications - await new Promise(resolve => setTimeout(resolve, 5000)); - // Disconnect - await transport.close(); - console.log(`[${config.id}] Disconnected from MCP server`); - return { id: config.id, result }; - } - catch (error) { - console.error(`[${config.id}] Error:`, error); - throw error; - } -} -async function main() { - console.log('MCP Multiple Clients Example'); - console.log('============================'); - console.log(`Server URL: ${serverUrl}`); - console.log(''); - try { - // Define client configurations - const clientConfigs = [ - { - id: 'client1', - name: 'basic-client-1', - toolName: 'start-notification-stream', - toolArguments: { - interval: 3, // 1 second between notifications - count: 5 // Send 5 notifications - } - }, - { - id: 'client2', - name: 'basic-client-2', - toolName: 'start-notification-stream', - toolArguments: { - interval: 2, // 2 seconds between notifications - count: 3 // Send 3 notifications - } - }, - { - id: 'client3', - name: 'basic-client-3', - toolName: 'start-notification-stream', - toolArguments: { - interval: 1, // 0.5 second between notifications - count: 8 // Send 8 notifications - } - } - ]; - // Start all clients in parallel - console.log(`Starting ${clientConfigs.length} clients in parallel...`); - console.log(''); - const clientPromises = clientConfigs.map(config => createAndRunClient(config)); - const results = await Promise.all(clientPromises); - // Display results from all clients - console.log('\n=== Final Results ==='); - results.forEach(({ id, result }) => { - console.log(`\n[${id}] Tool result:`); - if (Array.isArray(result.content)) { - result.content.forEach((item) => { - if (item.type === 'text' && item.text) { - console.log(` ${item.text}`); - } - else { - console.log(` ${item.type} content:`, item); - } - }); - } - else { - console.log(` Unexpected result format:`, result); - } - }); - console.log('\n=== All clients completed successfully ==='); - } - catch (error) { - console.error('Error running multiple clients:', error); - process.exit(1); - } -} -// Start the example -main().catch((error) => { - console.error('Error running MCP multiple clients example:', error); - process.exit(1); -}); -//# sourceMappingURL=multipleClientsParallel.js.map \ No newline at end of file diff --git a/dist/esm/examples/client/multipleClientsParallel.js.map b/dist/esm/examples/client/multipleClientsParallel.js.map deleted file mode 100644 index d02ce22805..0000000000 --- a/dist/esm/examples/client/multipleClientsParallel.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"multipleClientsParallel.js","sourceRoot":"","sources":["../../../../src/examples/client/multipleClientsParallel.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAmB,oBAAoB,EAAE,gCAAgC,EAAkB,MAAM,gBAAgB,CAAC;AAEzH;;;;;;;GAOG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AASzD,KAAK,UAAU,kBAAkB,CAAC,MAAoB;IAClD,OAAO,CAAC,GAAG,CAAC,IAAI,MAAM,CAAC,EAAE,sBAAsB,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;IAE9D,MAAM,MAAM,GAAG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,CAAC;QACL,CAAC,CAAC,CAAC;QAEH,OAAO,CAAC,GAAG,CAAC,8CAA8C,CAAC,CAAC;IAChE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC,CAAC;QACxD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;AACL,CAAC;AAED,oBAAoB;AACpB,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,6CAA6C,EAAE,KAAK,CAAC,CAAC;IACpE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/client/parallelToolCallsClient.d.ts b/dist/esm/examples/client/parallelToolCallsClient.d.ts deleted file mode 100644 index e93d4d69d2..0000000000 --- a/dist/esm/examples/client/parallelToolCallsClient.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=parallelToolCallsClient.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/client/parallelToolCallsClient.d.ts.map b/dist/esm/examples/client/parallelToolCallsClient.d.ts.map deleted file mode 100644 index 25a3b820cf..0000000000 --- a/dist/esm/examples/client/parallelToolCallsClient.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"parallelToolCallsClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/parallelToolCallsClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/client/parallelToolCallsClient.js b/dist/esm/examples/client/parallelToolCallsClient.js deleted file mode 100644 index 9d2a2e9153..0000000000 --- a/dist/esm/examples/client/parallelToolCallsClient.js +++ /dev/null @@ -1,174 +0,0 @@ -import { Client } from '../../client/index.js'; -import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; -import { ListToolsResultSchema, CallToolResultSchema, LoggingMessageNotificationSchema } from '../../types.js'; -/** - * Parallel Tool Calls MCP Client - * - * This client demonstrates how to: - * 1. Start multiple tool calls in parallel - * 2. Track notifications from each tool call using a caller parameter - */ -// Command line args processing -const args = process.argv.slice(2); -const serverUrl = args[0] || 'http://localhost:3000/mcp'; -async function main() { - console.log('MCP Parallel Tool Calls Client'); - console.log('=============================='); - console.log(`Connecting to server at: ${serverUrl}`); - let client; - let transport; - try { - // Create client with streamable HTTP transport - client = new Client({ - name: 'parallel-tool-calls-client', - version: '1.0.0' - }); - client.onerror = error => { - console.error('Client error:', error); - }; - // Connect to the server - transport = new StreamableHTTPClientTransport(new URL(serverUrl)); - await client.connect(transport); - console.log('Successfully connected to MCP server'); - // Set up notification handler with caller identification - client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { - console.log(`Notification: ${notification.params.data}`); - }); - console.log('List tools'); - const toolsRequest = await listTools(client); - console.log('Tools: ', toolsRequest); - // 2. Start multiple notification tools in parallel - console.log('\n=== Starting Multiple Notification Streams in Parallel ==='); - const toolResults = await startParallelNotificationTools(client); - // Log the results from each tool call - for (const [caller, result] of Object.entries(toolResults)) { - console.log(`\n=== Tool result for ${caller} ===`); - result.content.forEach((item) => { - if (item.type === 'text') { - console.log(` ${item.text}`); - } - else { - console.log(` ${item.type} content:`, item); - } - }); - } - // 3. Wait for all notifications (10 seconds) - console.log('\n=== Waiting for all notifications ==='); - await new Promise(resolve => setTimeout(resolve, 10000)); - // 4. Disconnect - console.log('\n=== Disconnecting ==='); - await transport.close(); - console.log('Disconnected from MCP server'); - } - catch (error) { - console.error('Error running client:', error); - process.exit(1); - } -} -/** - * List available tools on the server - */ -async function listTools(client) { - try { - const toolsRequest = { - method: 'tools/list', - params: {} - }; - const toolsResult = await client.request(toolsRequest, ListToolsResultSchema); - console.log('Available tools:'); - if (toolsResult.tools.length === 0) { - console.log(' No tools available'); - } - else { - for (const tool of toolsResult.tools) { - console.log(` - ${tool.name}: ${tool.description}`); - } - } - } - catch (error) { - console.log(`Tools not supported by this server: ${error}`); - } -} -/** - * Start multiple notification tools in parallel with different configurations - * Each tool call includes a caller parameter to identify its notifications - */ -async function startParallelNotificationTools(client) { - try { - // Define multiple tool calls with different configurations - const toolCalls = [ - { - caller: 'fast-notifier', - request: { - method: 'tools/call', - params: { - name: 'start-notification-stream', - arguments: { - interval: 2, // 0.5 second between notifications - count: 10, // Send 10 notifications - caller: 'fast-notifier' // Identify this tool call - } - } - } - }, - { - caller: 'slow-notifier', - request: { - method: 'tools/call', - params: { - name: 'start-notification-stream', - arguments: { - interval: 5, // 2 seconds between notifications - count: 5, // Send 5 notifications - caller: 'slow-notifier' // Identify this tool call - } - } - } - }, - { - caller: 'burst-notifier', - request: { - method: 'tools/call', - params: { - name: 'start-notification-stream', - arguments: { - interval: 1, // 0.1 second between notifications - count: 3, // Send just 3 notifications - caller: 'burst-notifier' // Identify this tool call - } - } - } - } - ]; - console.log(`Starting ${toolCalls.length} notification tools in parallel...`); - // Start all tool calls in parallel - const toolPromises = toolCalls.map(({ caller, request }) => { - console.log(`Starting tool call for ${caller}...`); - return client - .request(request, CallToolResultSchema) - .then(result => ({ caller, result })) - .catch(error => { - console.error(`Error in tool call for ${caller}:`, error); - throw error; - }); - }); - // Wait for all tool calls to complete - const results = await Promise.all(toolPromises); - // Organize results by caller - const resultsByTool = {}; - results.forEach(({ caller, result }) => { - resultsByTool[caller] = result; - }); - return resultsByTool; - } - catch (error) { - console.error(`Error starting parallel notification tools:`, error); - throw error; - } -} -// Start the client -main().catch((error) => { - console.error('Error running MCP client:', error); - process.exit(1); -}); -//# sourceMappingURL=parallelToolCallsClient.js.map \ No newline at end of file diff --git a/dist/esm/examples/client/parallelToolCallsClient.js.map b/dist/esm/examples/client/parallelToolCallsClient.js.map deleted file mode 100644 index 0a044818ef..0000000000 --- a/dist/esm/examples/client/parallelToolCallsClient.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"parallelToolCallsClient.js","sourceRoot":"","sources":["../../../../src/examples/client/parallelTool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AC;QAEH,sCAAsC;QACtC,MAAM,OAAO,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;QAEhD,6BAA6B;QAC7B,MAAM,aAAa,GAAmC,EAAE,CAAC;QACzD,OAAO,CAAC,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,EAAE;YACnC,aAAa,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;QACnC,CAAC,CAAC,CAAC;QAEH,OAAO,aAAa,CAAC;IACzB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,KAAK,CAAC,6CAA6C,EAAE,KAAK,CAAC,CAAC;QACpE,MAAM,KAAK,CAAC;IAChB,CAAC;AACL,CAAC;AAED,mBAAmB;AACnB,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClient.d.ts b/dist/esm/examples/client/simpleOAuthClient.d.ts deleted file mode 100644 index e4b43dbc01..0000000000 --- a/dist/esm/examples/client/simpleOAuthClient.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env node -export {}; -//# sourceMappingURL=simpleOAuthClient.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClient.d.ts.map b/dist/esm/examples/client/simpleOAuthClient.d.ts.map deleted file mode 100644 index c09eef86ea..0000000000 --- a/dist/esm/examples/client/simpleOAuthClient.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleOAuthClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClient.js b/dist/esm/examples/client/simpleOAuthClient.js deleted file mode 100644 index 4ad45fda2d..0000000000 --- a/dist/esm/examples/client/simpleOAuthClient.js +++ /dev/null @@ -1,335 +0,0 @@ -#!/usr/bin/env node -import { createServer } from 'node:http'; -import { createInterface } from 'node:readline'; -import { URL } from 'node:url'; -import { exec } from 'node:child_process'; -import { Client } from '../../client/index.js'; -import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; -import { CallToolResultSchema, ListToolsResultSchema } from '../../types.js'; -import { UnauthorizedError } from '../../client/auth.js'; -import { InMemoryOAuthClientProvider } from './simpleOAuthClientProvider.js'; -// Configuration -const DEFAULT_SERVER_URL = 'http://localhost:3000/mcp'; -const CALLBACK_PORT = 8090; // Use different port than auth server (3001) -const CALLBACK_URL = `http://localhost:${CALLBACK_PORT}/callback`; -/** - * Interactive MCP client with OAuth authentication - * Demonstrates the complete OAuth flow with browser-based authorization - */ -class InteractiveOAuthClient { - constructor(serverUrl, clientMetadataUrl) { - this.serverUrl = serverUrl; - this.clientMetadataUrl = clientMetadataUrl; - this.client = null; - this.rl = createInterface({ - input: process.stdin, - output: process.stdout - }); - } - /** - * Prompts user for input via readline - */ - async question(query) { - return new Promise(resolve => { - this.rl.question(query, resolve); - }); - } - /** - * Opens the authorization URL in the user's default browser - */ - async openBrowser(url) { - console.log(`🌐 Opening browser for authorization: ${url}`); - const command = `open "${url}"`; - exec(command, error => { - if (error) { - console.error(`Failed to open browser: ${error.message}`); - console.log(`Please manually open: ${url}`); - } - }); - } - /** - * Example OAuth callback handler - in production, use a more robust approach - * for handling callbacks and storing tokens - */ - /** - * Starts a temporary HTTP server to receive the OAuth callback - */ - async waitForOAuthCallback() { - return new Promise((resolve, reject) => { - const server = createServer((req, res) => { - // Ignore favicon requests - if (req.url === '/favicon.ico') { - res.writeHead(404); - res.end(); - return; - } - console.log(`📥 Received callback: ${req.url}`); - const parsedUrl = new URL(req.url || '', 'http://localhost'); - const code = parsedUrl.searchParams.get('code'); - const error = parsedUrl.searchParams.get('error'); - if (code) { - console.log(`✅ Authorization code received: ${code === null || code === void 0 ? void 0 : code.substring(0, 10)}...`); - res.writeHead(200, { 'Content-Type': 'text/html' }); - res.end(` - - -

Authorization Successful!

-

You can close this window and return to the terminal.

- - - - `); - resolve(code); - setTimeout(() => server.close(), 3000); - } - else if (error) { - console.log(`❌ Authorization error: ${error}`); - res.writeHead(400, { 'Content-Type': 'text/html' }); - res.end(` - - -

Authorization Failed

-

Error: ${error}

- - - `); - reject(new Error(`OAuth authorization failed: ${error}`)); - } - else { - console.log(`❌ No authorization code or error in callback`); - res.writeHead(400); - res.end('Bad request'); - reject(new Error('No authorization code provided')); - } - }); - server.listen(CALLBACK_PORT, () => { - console.log(`OAuth callback server started on http://localhost:${CALLBACK_PORT}`); - }); - }); - } - async attemptConnection(oauthProvider) { - console.log('🚢 Creating transport with OAuth provider...'); - const baseUrl = new URL(this.serverUrl); - const transport = new StreamableHTTPClientTransport(baseUrl, { - authProvider: oauthProvider - }); - console.log('🚢 Transport created'); - try { - console.log('🔌 Attempting connection (this will trigger OAuth redirect)...'); - await this.client.connect(transport); - console.log('✅ Connected successfully'); - } - catch (error) { - if (error instanceof UnauthorizedError) { - console.log('🔐 OAuth required - waiting for authorization...'); - const callbackPromise = this.waitForOAuthCallback(); - const authCode = await callbackPromise; - await transport.finishAuth(authCode); - console.log('🔐 Authorization code received:', authCode); - console.log('🔌 Reconnecting with authenticated transport...'); - await this.attemptConnection(oauthProvider); - } - else { - console.error('❌ Connection failed with non-auth error:', error); - throw error; - } - } - } - /** - * Establishes connection to the MCP server with OAuth authentication - */ - async connect() { - console.log(`🔗 Attempting to connect to ${this.serverUrl}...`); - const clientMetadata = { - client_name: 'Simple OAuth MCP Client', - redirect_uris: [CALLBACK_URL], - grant_types: ['authorization_code', 'refresh_token'], - response_types: ['code'], - token_endpoint_auth_method: 'client_secret_post' - }; - console.log('🔐 Creating OAuth provider...'); - const oauthProvider = new InMemoryOAuthClientProvider(CALLBACK_URL, clientMetadata, (redirectUrl) => { - console.log(`📌 OAuth redirect handler called - opening browser`); - console.log(`Opening browser to: ${redirectUrl.toString()}`); - this.openBrowser(redirectUrl.toString()); - }, this.clientMetadataUrl); - console.log('🔐 OAuth provider created'); - console.log('👤 Creating MCP client...'); - this.client = new Client({ - name: 'simple-oauth-client', - version: '1.0.0' - }, { capabilities: {} }); - console.log('👤 Client created'); - console.log('🔐 Starting OAuth flow...'); - await this.attemptConnection(oauthProvider); - // Start interactive loop - await this.interactiveLoop(); - } - /** - * Main interactive loop for user commands - */ - async interactiveLoop() { - console.log('\n🎯 Interactive MCP Client with OAuth'); - console.log('Commands:'); - console.log(' list - List available tools'); - console.log(' call [args] - Call a tool'); - console.log(' quit - Exit the client'); - console.log(); - while (true) { - try { - const command = await this.question('mcp> '); - if (!command.trim()) { - continue; - } - if (command === 'quit') { - console.log('\n👋 Goodbye!'); - this.close(); - process.exit(0); - } - else if (command === 'list') { - await this.listTools(); - } - else if (command.startsWith('call ')) { - await this.handleCallTool(command); - } - else { - console.log("❌ Unknown command. Try 'list', 'call ', or 'quit'"); - } - } - catch (error) { - if (error instanceof Error && error.message === 'SIGINT') { - console.log('\n\n👋 Goodbye!'); - break; - } - console.error('❌ Error:', error); - } - } - } - async listTools() { - if (!this.client) { - console.log('❌ Not connected to server'); - return; - } - try { - const request = { - method: 'tools/list', - params: {} - }; - const result = await this.client.request(request, ListToolsResultSchema); - if (result.tools && result.tools.length > 0) { - console.log('\n📋 Available tools:'); - result.tools.forEach((tool, index) => { - console.log(`${index + 1}. ${tool.name}`); - if (tool.description) { - console.log(` Description: ${tool.description}`); - } - console.log(); - }); - } - else { - console.log('No tools available'); - } - } - catch (error) { - console.error('❌ Failed to list tools:', error); - } - } - async handleCallTool(command) { - const parts = command.split(/\s+/); - const toolName = parts[1]; - if (!toolName) { - console.log('❌ Please specify a tool name'); - return; - } - // Parse arguments (simple JSON-like format) - let toolArgs = {}; - if (parts.length > 2) { - const argsString = parts.slice(2).join(' '); - try { - toolArgs = JSON.parse(argsString); - } - catch (_a) { - console.log('❌ Invalid arguments format (expected JSON)'); - return; - } - } - await this.callTool(toolName, toolArgs); - } - async callTool(toolName, toolArgs) { - if (!this.client) { - console.log('❌ Not connected to server'); - return; - } - try { - const request = { - method: 'tools/call', - params: { - name: toolName, - arguments: toolArgs - } - }; - const result = await this.client.request(request, CallToolResultSchema); - console.log(`\n🔧 Tool '${toolName}' result:`); - if (result.content) { - result.content.forEach(content => { - if (content.type === 'text') { - console.log(content.text); - } - else { - console.log(content); - } - }); - } - else { - console.log(result); - } - } - catch (error) { - console.error(`❌ Failed to call tool '${toolName}':`, error); - } - } - close() { - this.rl.close(); - if (this.client) { - // Note: Client doesn't have a close method in the current implementation - // This would typically close the transport connection - } - } -} -/** - * Main entry point - */ -async function main() { - const args = process.argv.slice(2); - const serverUrl = args[0] || DEFAULT_SERVER_URL; - const clientMetadataUrl = args[1]; - console.log('🚀 Simple MCP OAuth Client'); - console.log(`Connecting to: ${serverUrl}`); - if (clientMetadataUrl) { - console.log(`Client Metadata URL: ${clientMetadataUrl}`); - } - console.log(); - const client = new InteractiveOAuthClient(serverUrl, clientMetadataUrl); - // Handle graceful shutdown - process.on('SIGINT', () => { - console.log('\n\n👋 Goodbye!'); - client.close(); - process.exit(0); - }); - try { - await client.connect(); - } - catch (error) { - console.error('Failed to start client:', error); - process.exit(1); - } - finally { - client.close(); - } -} -// Run if this file is executed directly -main().catch(error => { - console.error('Unhandled error:', error); - process.exit(1); -}); -//# sourceMappingURL=simpleOAuthClient.js.map \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClient.js.map b/dist/esm/examples/client/simpleOAuthClient.js.map deleted file mode 100644 index 9cfa58aacf..0000000000 --- a/dist/esm/examples/client/simpleOAuthClient.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleOAuthClient.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClient.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,YAAY,EAA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AC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;YAAS,CAAC;QACP,MAAM,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;AACL,CAAC;AAED,wCAAwC;AACxC,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,kBAAkB,EAAE,KAAK,CAAC,CAAC;IACzC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClientProvider.d.ts b/dist/esm/examples/client/simpleOAuthClientProvider.d.ts deleted file mode 100644 index 092616cf5c..0000000000 --- a/dist/esm/examples/client/simpleOAuthClientProvider.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { OAuthClientProvider } from '../../client/auth.js'; -import { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from '../../shared/auth.js'; -/** - * In-memory OAuth client provider for demonstration purposes - * In production, you should persist tokens securely - */ -export declare class InMemoryOAuthClientProvider implements OAuthClientProvider { - private readonly _redirectUrl; - private readonly _clientMetadata; - readonly clientMetadataUrl?: string | undefined; - private _clientInformation?; - private _tokens?; - private _codeVerifier?; - constructor(_redirectUrl: string | URL, _clientMetadata: OAuthClientMetadata, onRedirect?: (url: URL) => void, clientMetadataUrl?: string | undefined); - private _onRedirect; - get redirectUrl(): string | URL; - get clientMetadata(): OAuthClientMetadata; - clientInformation(): OAuthClientInformationMixed | undefined; - saveClientInformation(clientInformation: OAuthClientInformationMixed): void; - tokens(): OAuthTokens | undefined; - saveTokens(tokens: OAuthTokens): void; - redirectToAuthorization(authorizationUrl: URL): void; - saveCodeVerifier(codeVerifier: string): void; - codeVerifier(): string; -} -//# sourceMappingURL=simpleOAuthClientProvider.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClientProvider.d.ts.map b/dist/esm/examples/client/simpleOAuthClientProvider.d.ts.map deleted file mode 100644 index 21efe9444a..0000000000 --- a/dist/esm/examples/client/simpleOAuthClientProvider.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleOAuthClientProvider.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClientProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAC3D,OAAO,EAAE,2BAA2B,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAErG;;;GAGG;AACH,qBAAa,2BAA4B,YAAW,mBAAmB;IAM/D,OAAO,CAAC,QAAQ,CAAC,YAAY;IAC7B,OAAO,CAAC,QAAQ,CAAC,eAAe;aAEhB,iBAAiB,CAAC,EAAE,MAAM;IAR9C,OAAO,CAAC,kBAAkB,CAAC,CAA8B;IACzD,OAAO,CAAC,OAAO,CAAC,CAAc;IAC9B,OAAO,CAAC,aAAa,CAAC,CAAS;gBAGV,YAAY,EAAE,MAAM,GAAG,GAAG,EAC1B,eAAe,EAAE,mBAAmB,EACrD,UAAU,CAAC,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,IAAI,EACf,iBAAiB,CAAC,EAAE,MAAM,YAAA;IAS9C,OAAO,CAAC,WAAW,CAAqB;IAExC,IAAI,WAAW,IAAI,MAAM,GAAG,GAAG,CAE9B;IAED,IAAI,cAAc,IAAI,mBAAmB,CAExC;IAED,iBAAiB,IAAI,2BAA2B,GAAG,SAAS;IAI5D,qBAAqB,CAAC,iBAAiB,EAAE,2BAA2B,GAAG,IAAI;IAI3E,MAAM,IAAI,WAAW,GAAG,SAAS;IAIjC,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI;IAIrC,uBAAuB,CAAC,gBAAgB,EAAE,GAAG,GAAG,IAAI;IAIpD,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI;IAI5C,YAAY,IAAI,MAAM;CAMzB"} \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClientProvider.js b/dist/esm/examples/client/simpleOAuthClientProvider.js deleted file mode 100644 index 7c350d1313..0000000000 --- a/dist/esm/examples/client/simpleOAuthClientProvider.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * In-memory OAuth client provider for demonstration purposes - * In production, you should persist tokens securely - */ -export class InMemoryOAuthClientProvider { - constructor(_redirectUrl, _clientMetadata, onRedirect, clientMetadataUrl) { - this._redirectUrl = _redirectUrl; - this._clientMetadata = _clientMetadata; - this.clientMetadataUrl = clientMetadataUrl; - this._onRedirect = - onRedirect || - (url => { - console.log(`Redirect to: ${url.toString()}`); - }); - } - get redirectUrl() { - return this._redirectUrl; - } - get clientMetadata() { - return this._clientMetadata; - } - clientInformation() { - return this._clientInformation; - } - saveClientInformation(clientInformation) { - this._clientInformation = clientInformation; - } - tokens() { - return this._tokens; - } - saveTokens(tokens) { - this._tokens = tokens; - } - redirectToAuthorization(authorizationUrl) { - this._onRedirect(authorizationUrl); - } - saveCodeVerifier(codeVerifier) { - this._codeVerifier = codeVerifier; - } - codeVerifier() { - if (!this._codeVerifier) { - throw new Error('No code verifier saved'); - } - return this._codeVerifier; - } -} -//# sourceMappingURL=simpleOAuthClientProvider.js.map \ No newline at end of file diff --git a/dist/esm/examples/client/simpleOAuthClientProvider.js.map b/dist/esm/examples/client/simpleOAuthClientProvider.js.map deleted file mode 100644 index 88f15cde57..0000000000 --- a/dist/esm/examples/client/simpleOAuthClientProvider.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleOAuthClientProvider.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleOAuthClientProvider.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,MAAM,OAAO,2BAA2B;IAKpC,YACqB,YAA0B,EAC1B,eAAoC,EACrD,UAA+B,EACf,iBAA0B;QAHzB,iBAAY,GAAZ,YAAY,CAAc;QAC1B,oBAAe,GAAf,eAAe,CAAqB;QAErC,sBAAiB,GAAjB,iBAAiB,CAAS;QAE1C,IAAI,CAAC,WAAW;YACZ,UAAU;gBACV,CAAC,GAAG,CAAC,EAAE;oBACH,OAAO,CAAC,GAAG,CAAC,gBAAgB,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;gBAClD,CAAC,CAAC,CAAC;IACX,CAAC;IAID,IAAI,WAAW;QACX,OAAO,IAAI,CAAC,YAAY,CAAC;IAC7B,CAAC;IAED,IAAI,cAAc;QACd,OAAO,IAAI,CAAC,eAAe,CAAC;IAChC,CAAC;IAED,iBAAiB;QACb,OAAO,IAAI,CAAC,kBAAkB,CAAC;IACnC,CAAC;IAED,qBAAqB,CAAC,iBAA8C;QAChE,IAAI,CAAC,kBAAkB,GAAG,iBAAiB,CAAC;IAChD,CAAC;IAED,MAAM;QACF,OAAO,IAAI,CAAC,OAAO,CAAC;IACxB,CAAC;IAED,UAAU,CAAC,MAAmB;QAC1B,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;IAC1B,CAAC;IAED,uBAAuB,CAAC,gBAAqB;QACzC,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC;IACvC,CAAC;IAED,gBAAgB,CAAC,YAAoB;QACjC,IAAI,CAAC,aAAa,GAAG,YAAY,CAAC;IACtC,CAAC;IAED,YAAY;QACR,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,CAAC;YACtB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;QAC9C,CAAC;QACD,OAAO,IAAI,CAAC,aAAa,CAAC;IAC9B,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/examples/client/simpleStreamableHttp.d.ts b/dist/esm/examples/client/simpleStreamableHttp.d.ts deleted file mode 100644 index a20be42ca4..0000000000 --- a/dist/esm/examples/client/simpleStreamableHttp.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=simpleStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/client/simpleStreamableHttp.d.ts.map b/dist/esm/examples/client/simpleStreamableHttp.d.ts.map deleted file mode 100644 index 28406b0c1e..0000000000 --- a/dist/esm/examples/client/simpleStreamableHttp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/simpleStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/client/simpleStreamableHttp.js b/dist/esm/examples/client/simpleStreamableHttp.js deleted file mode 100644 index 6a2effd251..0000000000 --- a/dist/esm/examples/client/simpleStreamableHttp.js +++ /dev/null @@ -1,747 +0,0 @@ -import { Client } from '../../client/index.js'; -import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; -import { createInterface } from 'node:readline'; -import { ListToolsResultSchema, CallToolResultSchema, ListPromptsResultSchema, GetPromptResultSchema, ListResourcesResultSchema, LoggingMessageNotificationSchema, ResourceListChangedNotificationSchema, ElicitRequestSchema, ReadResourceResultSchema, ErrorCode, McpError } from '../../types.js'; -import { getDisplayName } from '../../shared/metadataUtils.js'; -import { Ajv } from 'ajv'; -// Create readline interface for user input -const readline = createInterface({ - input: process.stdin, - output: process.stdout -}); -// Track received notifications for debugging resumability -let notificationCount = 0; -// Global client and transport for interactive commands -let client = null; -let transport = null; -let serverUrl = 'http://localhost:3000/mcp'; -let notificationsToolLastEventId = undefined; -let sessionId = undefined; -async function main() { - console.log('MCP Interactive Client'); - console.log('====================='); - // Connect to server immediately with default settings - await connect(); - // Print help and start the command loop - printHelp(); - commandLoop(); -} -function printHelp() { - console.log('\nAvailable commands:'); - console.log(' connect [url] - Connect to MCP server (default: http://localhost:3000/mcp)'); - console.log(' disconnect - Disconnect from server'); - console.log(' terminate-session - Terminate the current session'); - console.log(' reconnect - Reconnect to the server'); - console.log(' list-tools - List available tools'); - console.log(' call-tool [args] - Call a tool with optional JSON arguments'); - console.log(' greet [name] - Call the greet tool'); - console.log(' multi-greet [name] - Call the multi-greet tool with notifications'); - console.log(' collect-info [type] - Test form elicitation with collect-user-info tool (contact/preferences/feedback)'); - console.log(' start-notifications [interval] [count] - Start periodic notifications'); - console.log(' run-notifications-tool-with-resumability [interval] [count] - Run notification tool with resumability'); - console.log(' list-prompts - List available prompts'); - console.log(' get-prompt [name] [args] - Get a prompt with optional JSON arguments'); - console.log(' list-resources - List available resources'); - console.log(' read-resource - Read a specific resource by URI'); - console.log(' help - Show this help'); - console.log(' quit - Exit the program'); -} -function commandLoop() { - readline.question('\n> ', async (input) => { - var _a; - const args = input.trim().split(/\s+/); - const command = (_a = args[0]) === null || _a === void 0 ? void 0 : _a.toLowerCase(); - try { - switch (command) { - case 'connect': - await connect(args[1]); - break; - case 'disconnect': - await disconnect(); - break; - case 'terminate-session': - await terminateSession(); - break; - case 'reconnect': - await reconnect(); - break; - case 'list-tools': - await listTools(); - break; - case 'call-tool': - if (args.length < 2) { - console.log('Usage: call-tool [args]'); - } - else { - const toolName = args[1]; - let toolArgs = {}; - if (args.length > 2) { - try { - toolArgs = JSON.parse(args.slice(2).join(' ')); - } - catch (_b) { - console.log('Invalid JSON arguments. Using empty args.'); - } - } - await callTool(toolName, toolArgs); - } - break; - case 'greet': - await callGreetTool(args[1] || 'MCP User'); - break; - case 'multi-greet': - await callMultiGreetTool(args[1] || 'MCP User'); - break; - case 'collect-info': - await callCollectInfoTool(args[1] || 'contact'); - break; - case 'start-notifications': { - const interval = args[1] ? parseInt(args[1], 10) : 2000; - const count = args[2] ? parseInt(args[2], 10) : 10; - await startNotifications(interval, count); - break; - } - case 'run-notifications-tool-with-resumability': { - const interval = args[1] ? parseInt(args[1], 10) : 2000; - const count = args[2] ? parseInt(args[2], 10) : 10; - await runNotificationsToolWithResumability(interval, count); - break; - } - case 'list-prompts': - await listPrompts(); - break; - case 'get-prompt': - if (args.length < 2) { - console.log('Usage: get-prompt [args]'); - } - else { - const promptName = args[1]; - let promptArgs = {}; - if (args.length > 2) { - try { - promptArgs = JSON.parse(args.slice(2).join(' ')); - } - catch (_c) { - console.log('Invalid JSON arguments. Using empty args.'); - } - } - await getPrompt(promptName, promptArgs); - } - break; - case 'list-resources': - await listResources(); - break; - case 'read-resource': - if (args.length < 2) { - console.log('Usage: read-resource '); - } - else { - await readResource(args[1]); - } - break; - case 'help': - printHelp(); - break; - case 'quit': - case 'exit': - await cleanup(); - return; - default: - if (command) { - console.log(`Unknown command: ${command}`); - } - break; - } - } - catch (error) { - console.error(`Error executing command: ${error}`); - } - // Continue the command loop - commandLoop(); - }); -} -async function connect(url) { - if (client) { - console.log('Already connected. Disconnect first.'); - return; - } - if (url) { - serverUrl = url; - } - console.log(`Connecting to ${serverUrl}...`); - try { - // Create a new client with form elicitation capability - client = new Client({ - name: 'example-client', - version: '1.0.0' - }, { - capabilities: { - elicitation: { - form: {} - } - } - }); - client.onerror = error => { - console.error('\x1b[31mClient error:', error, '\x1b[0m'); - }; - // Set up elicitation request handler with proper validation - client.setRequestHandler(ElicitRequestSchema, async (request) => { - var _a; - if (request.params.mode !== 'form') { - throw new McpError(ErrorCode.InvalidParams, `Unsupported elicitation mode: ${request.params.mode}`); - } - console.log('\n🔔 Elicitation (form) Request Received:'); - console.log(`Message: ${request.params.message}`); - console.log('Requested Schema:'); - console.log(JSON.stringify(request.params.requestedSchema, null, 2)); - const schema = request.params.requestedSchema; - const properties = schema.properties; - const required = schema.required || []; - // Set up AJV validator for the requested schema - const ajv = new Ajv(); - const validate = ajv.compile(schema); - let attempts = 0; - const maxAttempts = 3; - while (attempts < maxAttempts) { - attempts++; - console.log(`\nPlease provide the following information (attempt ${attempts}/${maxAttempts}):`); - const content = {}; - let inputCancelled = false; - // Collect input for each field - for (const [fieldName, fieldSchema] of Object.entries(properties)) { - const field = fieldSchema; - const isRequired = required.includes(fieldName); - let prompt = `${field.title || fieldName}`; - // Add helpful information to the prompt - if (field.description) { - prompt += ` (${field.description})`; - } - if (field.enum) { - prompt += ` [options: ${field.enum.join(', ')}]`; - } - if (field.type === 'number' || field.type === 'integer') { - if (field.minimum !== undefined && field.maximum !== undefined) { - prompt += ` [${field.minimum}-${field.maximum}]`; - } - else if (field.minimum !== undefined) { - prompt += ` [min: ${field.minimum}]`; - } - else if (field.maximum !== undefined) { - prompt += ` [max: ${field.maximum}]`; - } - } - if (field.type === 'string' && field.format) { - prompt += ` [format: ${field.format}]`; - } - if (isRequired) { - prompt += ' *required*'; - } - if (field.default !== undefined) { - prompt += ` [default: ${field.default}]`; - } - prompt += ': '; - const answer = await new Promise(resolve => { - readline.question(prompt, input => { - resolve(input.trim()); - }); - }); - // Check for cancellation - if (answer.toLowerCase() === 'cancel' || answer.toLowerCase() === 'c') { - inputCancelled = true; - break; - } - // Parse and validate the input - try { - if (answer === '' && field.default !== undefined) { - content[fieldName] = field.default; - } - else if (answer === '' && !isRequired) { - // Skip optional empty fields - continue; - } - else if (answer === '') { - throw new Error(`${fieldName} is required`); - } - else { - // Parse the value based on type - let parsedValue; - if (field.type === 'boolean') { - parsedValue = answer.toLowerCase() === 'true' || answer.toLowerCase() === 'yes' || answer === '1'; - } - else if (field.type === 'number') { - parsedValue = parseFloat(answer); - if (isNaN(parsedValue)) { - throw new Error(`${fieldName} must be a valid number`); - } - } - else if (field.type === 'integer') { - parsedValue = parseInt(answer, 10); - if (isNaN(parsedValue)) { - throw new Error(`${fieldName} must be a valid integer`); - } - } - else if (field.enum) { - if (!field.enum.includes(answer)) { - throw new Error(`${fieldName} must be one of: ${field.enum.join(', ')}`); - } - parsedValue = answer; - } - else { - parsedValue = answer; - } - content[fieldName] = parsedValue; - } - } - catch (error) { - console.log(`❌ Error: ${error}`); - // Continue to next attempt - break; - } - } - if (inputCancelled) { - return { action: 'cancel' }; - } - // If we didn't complete all fields due to an error, try again - if (Object.keys(content).length !== - Object.keys(properties).filter(name => required.includes(name) || content[name] !== undefined).length) { - if (attempts < maxAttempts) { - console.log('Please try again...'); - continue; - } - else { - console.log('Maximum attempts reached. Declining request.'); - return { action: 'decline' }; - } - } - // Validate the complete object against the schema - const isValid = validate(content); - if (!isValid) { - console.log('❌ Validation errors:'); - (_a = validate.errors) === null || _a === void 0 ? void 0 : _a.forEach(error => { - console.log(` - ${error.instancePath || 'root'}: ${error.message}`); - }); - if (attempts < maxAttempts) { - console.log('Please correct the errors and try again...'); - continue; - } - else { - console.log('Maximum attempts reached. Declining request.'); - return { action: 'decline' }; - } - } - // Show the collected data and ask for confirmation - console.log('\n✅ Collected data:'); - console.log(JSON.stringify(content, null, 2)); - const confirmAnswer = await new Promise(resolve => { - readline.question('\nSubmit this information? (yes/no/cancel): ', input => { - resolve(input.trim().toLowerCase()); - }); - }); - if (confirmAnswer === 'yes' || confirmAnswer === 'y') { - return { - action: 'accept', - content - }; - } - else if (confirmAnswer === 'cancel' || confirmAnswer === 'c') { - return { action: 'cancel' }; - } - else if (confirmAnswer === 'no' || confirmAnswer === 'n') { - if (attempts < maxAttempts) { - console.log('Please re-enter the information...'); - continue; - } - else { - return { action: 'decline' }; - } - } - } - console.log('Maximum attempts reached. Declining request.'); - return { action: 'decline' }; - }); - transport = new StreamableHTTPClientTransport(new URL(serverUrl), { - sessionId: sessionId - }); - // Set up notification handlers - client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { - notificationCount++; - console.log(`\nNotification #${notificationCount}: ${notification.params.level} - ${notification.params.data}`); - // Re-display the prompt - process.stdout.write('> '); - }); - client.setNotificationHandler(ResourceListChangedNotificationSchema, async (_) => { - console.log(`\nResource list changed notification received!`); - try { - if (!client) { - console.log('Client disconnected, cannot fetch resources'); - return; - } - const resourcesResult = await client.request({ - method: 'resources/list', - params: {} - }, ListResourcesResultSchema); - console.log('Available resources count:', resourcesResult.resources.length); - } - catch (_a) { - console.log('Failed to list resources after change notification'); - } - // Re-display the prompt - process.stdout.write('> '); - }); - // Connect the client - await client.connect(transport); - sessionId = transport.sessionId; - console.log('Transport created with session ID:', sessionId); - console.log('Connected to MCP server'); - } - catch (error) { - console.error('Failed to connect:', error); - client = null; - transport = null; - } -} -async function disconnect() { - if (!client || !transport) { - console.log('Not connected.'); - return; - } - try { - await transport.close(); - console.log('Disconnected from MCP server'); - client = null; - transport = null; - } - catch (error) { - console.error('Error disconnecting:', error); - } -} -async function terminateSession() { - if (!client || !transport) { - console.log('Not connected.'); - return; - } - try { - console.log('Terminating session with ID:', transport.sessionId); - await transport.terminateSession(); - console.log('Session terminated successfully'); - // Check if sessionId was cleared after termination - if (!transport.sessionId) { - console.log('Session ID has been cleared'); - sessionId = undefined; - // Also close the transport and clear client objects - await transport.close(); - console.log('Transport closed after session termination'); - client = null; - transport = null; - } - else { - console.log('Server responded with 405 Method Not Allowed (session termination not supported)'); - console.log('Session ID is still active:', transport.sessionId); - } - } - catch (error) { - console.error('Error terminating session:', error); - } -} -async function reconnect() { - if (client) { - await disconnect(); - } - await connect(); -} -async function listTools() { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const toolsRequest = { - method: 'tools/list', - params: {} - }; - const toolsResult = await client.request(toolsRequest, ListToolsResultSchema); - console.log('Available tools:'); - if (toolsResult.tools.length === 0) { - console.log(' No tools available'); - } - else { - for (const tool of toolsResult.tools) { - console.log(` - id: ${tool.name}, name: ${getDisplayName(tool)}, description: ${tool.description}`); - } - } - } - catch (error) { - console.log(`Tools not supported by this server (${error})`); - } -} -async function callTool(name, args) { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const request = { - method: 'tools/call', - params: { - name, - arguments: args - } - }; - console.log(`Calling tool '${name}' with args:`, args); - const result = await client.request(request, CallToolResultSchema); - console.log('Tool result:'); - const resourceLinks = []; - result.content.forEach(item => { - if (item.type === 'text') { - console.log(` ${item.text}`); - } - else if (item.type === 'resource_link') { - const resourceLink = item; - resourceLinks.push(resourceLink); - console.log(` 📁 Resource Link: ${resourceLink.name}`); - console.log(` URI: ${resourceLink.uri}`); - if (resourceLink.mimeType) { - console.log(` Type: ${resourceLink.mimeType}`); - } - if (resourceLink.description) { - console.log(` Description: ${resourceLink.description}`); - } - } - else if (item.type === 'resource') { - console.log(` [Embedded Resource: ${item.resource.uri}]`); - } - else if (item.type === 'image') { - console.log(` [Image: ${item.mimeType}]`); - } - else if (item.type === 'audio') { - console.log(` [Audio: ${item.mimeType}]`); - } - else { - console.log(` [Unknown content type]:`, item); - } - }); - // Offer to read resource links - if (resourceLinks.length > 0) { - console.log(`\nFound ${resourceLinks.length} resource link(s). Use 'read-resource ' to read their content.`); - } - } - catch (error) { - console.log(`Error calling tool ${name}: ${error}`); - } -} -async function callGreetTool(name) { - await callTool('greet', { name }); -} -async function callMultiGreetTool(name) { - console.log('Calling multi-greet tool with notifications...'); - await callTool('multi-greet', { name }); -} -async function callCollectInfoTool(infoType) { - console.log(`Testing form elicitation with collect-user-info tool (${infoType})...`); - await callTool('collect-user-info', { infoType }); -} -async function startNotifications(interval, count) { - console.log(`Starting notification stream: interval=${interval}ms, count=${count || 'unlimited'}`); - await callTool('start-notification-stream', { interval, count }); -} -async function runNotificationsToolWithResumability(interval, count) { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - console.log(`Starting notification stream with resumability: interval=${interval}ms, count=${count || 'unlimited'}`); - console.log(`Using resumption token: ${notificationsToolLastEventId || 'none'}`); - const request = { - method: 'tools/call', - params: { - name: 'start-notification-stream', - arguments: { interval, count } - } - }; - const onLastEventIdUpdate = (event) => { - notificationsToolLastEventId = event; - console.log(`Updated resumption token: ${event}`); - }; - const result = await client.request(request, CallToolResultSchema, { - resumptionToken: notificationsToolLastEventId, - onresumptiontoken: onLastEventIdUpdate - }); - console.log('Tool result:'); - result.content.forEach(item => { - if (item.type === 'text') { - console.log(` ${item.text}`); - } - else { - console.log(` ${item.type} content:`, item); - } - }); - } - catch (error) { - console.log(`Error starting notification stream: ${error}`); - } -} -async function listPrompts() { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const promptsRequest = { - method: 'prompts/list', - params: {} - }; - const promptsResult = await client.request(promptsRequest, ListPromptsResultSchema); - console.log('Available prompts:'); - if (promptsResult.prompts.length === 0) { - console.log(' No prompts available'); - } - else { - for (const prompt of promptsResult.prompts) { - console.log(` - id: ${prompt.name}, name: ${getDisplayName(prompt)}, description: ${prompt.description}`); - } - } - } - catch (error) { - console.log(`Prompts not supported by this server (${error})`); - } -} -async function getPrompt(name, args) { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const promptRequest = { - method: 'prompts/get', - params: { - name, - arguments: args - } - }; - const promptResult = await client.request(promptRequest, GetPromptResultSchema); - console.log('Prompt template:'); - promptResult.messages.forEach((msg, index) => { - console.log(` [${index + 1}] ${msg.role}: ${msg.content.type === 'text' ? msg.content.text : JSON.stringify(msg.content)}`); - }); - } - catch (error) { - console.log(`Error getting prompt ${name}: ${error}`); - } -} -async function listResources() { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const resourcesRequest = { - method: 'resources/list', - params: {} - }; - const resourcesResult = await client.request(resourcesRequest, ListResourcesResultSchema); - console.log('Available resources:'); - if (resourcesResult.resources.length === 0) { - console.log(' No resources available'); - } - else { - for (const resource of resourcesResult.resources) { - console.log(` - id: ${resource.name}, name: ${getDisplayName(resource)}, description: ${resource.uri}`); - } - } - } - catch (error) { - console.log(`Resources not supported by this server (${error})`); - } -} -async function readResource(uri) { - if (!client) { - console.log('Not connected to server.'); - return; - } - try { - const request = { - method: 'resources/read', - params: { uri } - }; - console.log(`Reading resource: ${uri}`); - const result = await client.request(request, ReadResourceResultSchema); - console.log('Resource contents:'); - for (const content of result.contents) { - console.log(` URI: ${content.uri}`); - if (content.mimeType) { - console.log(` Type: ${content.mimeType}`); - } - if ('text' in content && typeof content.text === 'string') { - console.log(' Content:'); - console.log(' ---'); - console.log(content.text - .split('\n') - .map((line) => ' ' + line) - .join('\n')); - console.log(' ---'); - } - else if ('blob' in content && typeof content.blob === 'string') { - console.log(` [Binary data: ${content.blob.length} bytes]`); - } - } - } - catch (error) { - console.log(`Error reading resource ${uri}: ${error}`); - } -} -async function cleanup() { - if (client && transport) { - try { - // First try to terminate the session gracefully - if (transport.sessionId) { - try { - console.log('Terminating session before exit...'); - await transport.terminateSession(); - console.log('Session terminated successfully'); - } - catch (error) { - console.error('Error terminating session:', error); - } - } - // Then close the transport - await transport.close(); - } - catch (error) { - console.error('Error closing transport:', error); - } - } - process.stdin.setRawMode(false); - readline.close(); - console.log('\nGoodbye!'); - process.exit(0); -} -// Set up raw mode for keyboard input to capture Escape key -process.stdin.setRawMode(true); -process.stdin.on('data', async (data) => { - // Check for Escape key (27) - if (data.length === 1 && data[0] === 27) { - console.log('\nESC key pressed. Disconnecting from server...'); - // Abort current operation and disconnect from server - if (client && transport) { - await disconnect(); - console.log('Disconnected. Press Enter to continue.'); - } - else { - console.log('Not connected to server.'); - } - // Re-display the prompt - process.stdout.write('> '); - } -}); -// Handle Ctrl+C -process.on('SIGINT', async () => { - console.log('\nReceived SIGINT. Cleaning up...'); - await cleanup(); -}); -// Start the interactive client -main().catch((error) => { - console.error('Error running MCP client:', error); - process.exit(1); -}); -//# sourceMappingURL=simpleStreamableHttp.js.map \ No newline at end of file diff --git a/dist/esm/examples/client/simpleStreamableHttp.js.map b/dist/esm/examples/client/simpleStreamableHttp.js.map deleted file mode 100644 index b5495eb5ba..0000000000 --- a/dist/esm/examples/client/simpleStreamableHttp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/client/simpleStreamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAEH,qBAAqB,EAErB,oBAAoB,EAEpB,uBAAuB,EAEvB,qBAAqB,EAErB,yBAAyB,EACzB,gCAAgC,EAChC,qCAAqC,EACrC,mBAAmB,EAGnB,wBAAwB,EACxB,SAAS,EACT,QAAQ,EACX,MAAM,gBAAgB,CAAC;AACxB,OAA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AC,0BAA0B,CAAC,CAAC;QAC5C,CAAC;QAED,wBAAwB;QACxB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,gBAAgB;AAChB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;IACjD,MAAM,OAAO,EAAE,CAAC;AACpB,CAAC,CAAC,CAAC;AAEH,+BAA+B;AAC/B,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts b/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts deleted file mode 100644 index c2679e6694..0000000000 --- a/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=streamableHttpWithSseFallbackClient.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts.map b/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts.map deleted file mode 100644 index b79ae2a72c..0000000000 --- a/dist/esm/examples/client/streamableHttpWithSseFallbackClient.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"streamableHttpWithSseFallbackClient.d.ts","sourceRoot":"","sources":["../../../../src/examples/client/streamableHttpWithSseFallbackClient.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js b/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js deleted file mode 100644 index 1bea76828d..0000000000 --- a/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js +++ /dev/null @@ -1,166 +0,0 @@ -import { Client } from '../../client/index.js'; -import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; -import { SSEClientTransport } from '../../client/sse.js'; -import { ListToolsResultSchema, CallToolResultSchema, LoggingMessageNotificationSchema } from '../../types.js'; -/** - * Simplified Backwards Compatible MCP Client - * - * This client demonstrates backward compatibility with both: - * 1. Modern servers using Streamable HTTP transport (protocol version 2025-03-26) - * 2. Older servers using HTTP+SSE transport (protocol version 2024-11-05) - * - * Following the MCP specification for backwards compatibility: - * - Attempts to POST an initialize request to the server URL first (modern transport) - * - If that fails with 4xx status, falls back to GET request for SSE stream (older transport) - */ -// Command line args processing -const args = process.argv.slice(2); -const serverUrl = args[0] || 'http://localhost:3000/mcp'; -async function main() { - console.log('MCP Backwards Compatible Client'); - console.log('==============================='); - console.log(`Connecting to server at: ${serverUrl}`); - let client; - let transport; - try { - // Try connecting with automatic transport detection - const connection = await connectWithBackwardsCompatibility(serverUrl); - client = connection.client; - transport = connection.transport; - // Set up notification handler - client.setNotificationHandler(LoggingMessageNotificationSchema, notification => { - console.log(`Notification: ${notification.params.level} - ${notification.params.data}`); - }); - // DEMO WORKFLOW: - // 1. List available tools - console.log('\n=== Listing Available Tools ==='); - await listTools(client); - // 2. Call the notification tool - console.log('\n=== Starting Notification Stream ==='); - await startNotificationTool(client); - // 3. Wait for all notifications (5 seconds) - console.log('\n=== Waiting for all notifications ==='); - await new Promise(resolve => setTimeout(resolve, 5000)); - // 4. Disconnect - console.log('\n=== Disconnecting ==='); - await transport.close(); - console.log('Disconnected from MCP server'); - } - catch (error) { - console.error('Error running client:', error); - process.exit(1); - } -} -/** - * Connect to an MCP server with backwards compatibility - * Following the spec for client backward compatibility - */ -async function connectWithBackwardsCompatibility(url) { - console.log('1. Trying Streamable HTTP transport first...'); - // Step 1: Try Streamable HTTP transport first - const client = new Client({ - name: 'backwards-compatible-client', - version: '1.0.0' - }); - client.onerror = error => { - console.error('Client error:', error); - }; - const baseUrl = new URL(url); - try { - // Create modern transport - const streamableTransport = new StreamableHTTPClientTransport(baseUrl); - await client.connect(streamableTransport); - console.log('Successfully connected using modern Streamable HTTP transport.'); - return { - client, - transport: streamableTransport, - transportType: 'streamable-http' - }; - } - catch (error) { - // Step 2: If transport fails, try the older SSE transport - console.log(`StreamableHttp transport connection failed: ${error}`); - console.log('2. Falling back to deprecated HTTP+SSE transport...'); - try { - // Create SSE transport pointing to /sse endpoint - const sseTransport = new SSEClientTransport(baseUrl); - const sseClient = new Client({ - name: 'backwards-compatible-client', - version: '1.0.0' - }); - await sseClient.connect(sseTransport); - console.log('Successfully connected using deprecated HTTP+SSE transport.'); - return { - client: sseClient, - transport: sseTransport, - transportType: 'sse' - }; - } - catch (sseError) { - console.error(`Failed to connect with either transport method:\n1. Streamable HTTP error: ${error}\n2. SSE error: ${sseError}`); - throw new Error('Could not connect to server with any available transport'); - } - } -} -/** - * List available tools on the server - */ -async function listTools(client) { - try { - const toolsRequest = { - method: 'tools/list', - params: {} - }; - const toolsResult = await client.request(toolsRequest, ListToolsResultSchema); - console.log('Available tools:'); - if (toolsResult.tools.length === 0) { - console.log(' No tools available'); - } - else { - for (const tool of toolsResult.tools) { - console.log(` - ${tool.name}: ${tool.description}`); - } - } - } - catch (error) { - console.log(`Tools not supported by this server: ${error}`); - } -} -/** - * Start a notification stream by calling the notification tool - */ -async function startNotificationTool(client) { - try { - // Call the notification tool using reasonable defaults - const request = { - method: 'tools/call', - params: { - name: 'start-notification-stream', - arguments: { - interval: 1000, // 1 second between notifications - count: 5 // Send 5 notifications - } - } - }; - console.log('Calling notification tool...'); - const result = await client.request(request, CallToolResultSchema); - console.log('Tool result:'); - result.content.forEach(item => { - if (item.type === 'text') { - console.log(` ${item.text}`); - } - else { - console.log(` ${item.type} content:`, item); - } - }); - } - catch (error) { - console.log(`Error calling notification tool: ${error}`); - } -} -// Start the client -main().catch((error) => { - console.error('Error running MCP client:', error); - process.exit(1); -}); -//# sourceMappingURL=streamableHttpWithSseFallbackClient.js.map \ No newline at end of file diff --git a/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js.map b/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js.map deleted file mode 100644 index 0d9399dc90..0000000000 --- a/dist/esm/examples/client/streamableHttpWithSseFallbackClient.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"streamableHttpWithSseFallbackClient.js","sourceRoot":"","sources":["../../../../src/examples/client/streamableHttpWithSseFallbackClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAC/C,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,EAEH,qBAAqB,EAErB,oBAAoB,EACpB,gCAAgC,EACnC,MAAM,gBAAgB,CAAC;AAExB;;;;;;;;;;GAUG;AAEH,+BAA+B;AAC/B,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;AACnC,MAAM,SAAS,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,2BAA2B,CAAC;AAEzD,KAAK,UAAU,IAAI;IACf,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,CAAC,4BAA4B,SAAS,EAAE,CAAC,CAAC;IAErD,IAAI,MAAc,CAAC;IACnB,IAAI,SAA6D,CAAC;IAElE,IAAI,CAAC;QACD,oDAAoD;QACpD,MAAM,UAAU,GAAG,MAAM,iCAAiC,CAAC,SAAS,CAAC,CAAC;QACtE,MAAM,GAAG,UAAU,CAAC,MAAM,CAAC;QAC3B,SAAS,GAAG,UAAU,CAAC,SAAS,CAAC;QAEjC,8BAA8B;QAC9B,MAAM,CAAC,sBAAsB,CAAC,gC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AC1B,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gBACvB,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;YAClC,CAAC;iBAAM,CAAC;gBACJ,OAAO,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,IAAI,WAAW,EAAE,IAAI,CAAC,CAAC;YACjD,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACb,OAAO,CAAC,GAAG,CAAC,oCAAoC,KAAK,EAAE,CAAC,CAAC;IAC7D,CAAC;AACL,CAAC;AAED,mBAAmB;AACnB,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC5B,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;IAClD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts b/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts deleted file mode 100644 index 218aeac8b2..0000000000 --- a/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { AuthorizationParams, OAuthServerProvider } from '../../server/auth/provider.js'; -import { OAuthRegisteredClientsStore } from '../../server/auth/clients.js'; -import { OAuthClientInformationFull, OAuthMetadata, OAuthTokens } from '../../shared/auth.js'; -import { Response } from 'express'; -import { AuthInfo } from '../../server/auth/types.js'; -export declare class DemoInMemoryClientsStore implements OAuthRegisteredClientsStore { - private clients; - getClient(clientId: string): Promise<{ - redirect_uris: string[]; - client_id: string; - token_endpoint_auth_method?: string | undefined; - grant_types?: string[] | undefined; - response_types?: string[] | undefined; - client_name?: string | undefined; - client_uri?: string | undefined; - logo_uri?: string | undefined; - scope?: string | undefined; - contacts?: string[] | undefined; - tos_uri?: string | undefined; - policy_uri?: string | undefined; - jwks_uri?: string | undefined; - jwks?: any; - software_id?: string | undefined; - software_version?: string | undefined; - software_statement?: string | undefined; - client_secret?: string | undefined; - client_id_issued_at?: number | undefined; - client_secret_expires_at?: number | undefined; - } | undefined>; - registerClient(clientMetadata: OAuthClientInformationFull): Promise<{ - redirect_uris: string[]; - client_id: string; - token_endpoint_auth_method?: string | undefined; - grant_types?: string[] | undefined; - response_types?: string[] | undefined; - client_name?: string | undefined; - client_uri?: string | undefined; - logo_uri?: string | undefined; - scope?: string | undefined; - contacts?: string[] | undefined; - tos_uri?: string | undefined; - policy_uri?: string | undefined; - jwks_uri?: string | undefined; - jwks?: any; - software_id?: string | undefined; - software_version?: string | undefined; - software_statement?: string | undefined; - client_secret?: string | undefined; - client_id_issued_at?: number | undefined; - client_secret_expires_at?: number | undefined; - }>; -} -/** - * 🚨 DEMO ONLY - NOT FOR PRODUCTION - * - * This example demonstrates MCP OAuth flow but lacks some of the features required for production use, - * for example: - * - Persistent token storage - * - Rate limiting - */ -export declare class DemoInMemoryAuthProvider implements OAuthServerProvider { - private validateResource?; - clientsStore: DemoInMemoryClientsStore; - private codes; - private tokens; - constructor(validateResource?: ((resource?: URL) => boolean) | undefined); - authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; - challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise; - exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, _codeVerifier?: string): Promise; - exchangeRefreshToken(_client: OAuthClientInformationFull, _refreshToken: string, _scopes?: string[], _resource?: URL): Promise; - verifyAccessToken(token: string): Promise; -} -export declare const setupAuthServer: ({ authServerUrl, mcpServerUrl, strictResource }: { - authServerUrl: URL; - mcpServerUrl: URL; - strictResource: boolean; -}) => OAuthMetadata; -//# sourceMappingURL=demoInMemoryOAuthProvider.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts.map b/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts.map deleted file mode 100644 index 8a4a43fe8d..0000000000 --- a/dist/esm/examples/server/demoInMemoryOAuthProvider.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"demoInMemoryOAuthProvider.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/demoInMemoryOAuthProvider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACzF,OAAO,EAAE,2BAA2B,EAAE,MAAM,8BAA8B,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAC9F,OAAgB,EAAW,QAAQ,EAAE,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,MAAM,4BAA4B,CAAC;AAKtD,qBAAa,wBAAyB,YAAW,2BAA2B;IACxE,OAAO,CAAC,OAAO,CAAiD;IAE1D,SAAS,CAAC,QAAQ,EAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;IAI1B,cAAc,CAAC,cAAc,EAAE,0BAA0B;;;;;;;;;;;;;;;;;;;;;;CAIlE;AAED;;;;;;;GAOG;AACH,qBAAa,wBAAyB,YAAW,mBAAmB;IAWpD,OAAO,CAAC,gBAAgB,CAAC;IAVrC,YAAY,2BAAkC;IAC9C,OAAO,CAAC,KAAK,CAMT;IACJ,OAAO,CAAC,MAAM,CAA+B;gBAEzB,gBAAgB,CAAC,GAAE,CAAC,QAAQ,CAAC,EAAE,GAAG,KAAK,OAAO,aAAA;IAE5D,SAAS,CAAC,MAAM,EAAE,0BAA0B,EAAE,MAAM,EAAE,mBAAmB,EAAE,GAAG,EAAE,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;IAwCxG,6BAA6B,CAAC,MAAM,EAAE,0BAA0B,EAAE,iBAAiB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAU7G,yBAAyB,CAC3B,MAAM,EAAE,0BAA0B,EAClC,iBAAiB,EAAE,MAAM,EAGzB,aAAa,CAAC,EAAE,MAAM,GACvB,OAAO,CAAC,WAAW,CAAC;IAoCjB,oBAAoB,CACtB,OAAO,EAAE,0BAA0B,EACnC,aAAa,EAAE,MAAM,EACrB,OAAO,CAAC,EAAE,MAAM,EAAE,EAClB,SAAS,CAAC,EAAE,GAAG,GAChB,OAAO,CAAC,WAAW,CAAC;IAIjB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;CAc5D;AAED,eAAO,MAAM,eAAe,oDAIzB;IACC,aAAa,EAAE,GAAG,CAAC;IACnB,YAAY,EAAE,GAAG,CAAC;IAClB,cAAc,EAAE,OAAO,CAAC;CAC3B,KAAG,aA+EH,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/demoInMemoryOAuthProvider.js b/dist/esm/examples/server/demoInMemoryOAuthProvider.js deleted file mode 100644 index 45bde7043d..0000000000 --- a/dist/esm/examples/server/demoInMemoryOAuthProvider.js +++ /dev/null @@ -1,196 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import express from 'express'; -import { createOAuthMetadata, mcpAuthRouter } from '../../server/auth/router.js'; -import { resourceUrlFromServerUrl } from '../../shared/auth-utils.js'; -import { InvalidRequestError } from '../../server/auth/errors.js'; -export class DemoInMemoryClientsStore { - constructor() { - this.clients = new Map(); - } - async getClient(clientId) { - return this.clients.get(clientId); - } - async registerClient(clientMetadata) { - this.clients.set(clientMetadata.client_id, clientMetadata); - return clientMetadata; - } -} -/** - * 🚨 DEMO ONLY - NOT FOR PRODUCTION - * - * This example demonstrates MCP OAuth flow but lacks some of the features required for production use, - * for example: - * - Persistent token storage - * - Rate limiting - */ -export class DemoInMemoryAuthProvider { - constructor(validateResource) { - this.validateResource = validateResource; - this.clientsStore = new DemoInMemoryClientsStore(); - this.codes = new Map(); - this.tokens = new Map(); - } - async authorize(client, params, res) { - const code = randomUUID(); - const searchParams = new URLSearchParams({ - code - }); - if (params.state !== undefined) { - searchParams.set('state', params.state); - } - this.codes.set(code, { - client, - params - }); - // Simulate a user login - // Set a secure HTTP-only session cookie with authorization info - if (res.cookie) { - const authCookieData = { - userId: 'demo_user', - name: 'Demo User', - timestamp: Date.now() - }; - res.cookie('demo_session', JSON.stringify(authCookieData), { - httpOnly: true, - secure: false, // In production, this should be true - sameSite: 'lax', - maxAge: 24 * 60 * 60 * 1000, // 24 hours - for demo purposes - path: '/' // Available to all routes - }); - } - if (!client.redirect_uris.includes(params.redirectUri)) { - throw new InvalidRequestError('Unregistered redirect_uri'); - } - const targetUrl = new URL(params.redirectUri); - targetUrl.search = searchParams.toString(); - res.redirect(targetUrl.toString()); - } - async challengeForAuthorizationCode(client, authorizationCode) { - // Store the challenge with the code data - const codeData = this.codes.get(authorizationCode); - if (!codeData) { - throw new Error('Invalid authorization code'); - } - return codeData.params.codeChallenge; - } - async exchangeAuthorizationCode(client, authorizationCode, - // Note: code verifier is checked in token.ts by default - // it's unused here for that reason. - _codeVerifier) { - const codeData = this.codes.get(authorizationCode); - if (!codeData) { - throw new Error('Invalid authorization code'); - } - if (codeData.client.client_id !== client.client_id) { - throw new Error(`Authorization code was not issued to this client, ${codeData.client.client_id} != ${client.client_id}`); - } - if (this.validateResource && !this.validateResource(codeData.params.resource)) { - throw new Error(`Invalid resource: ${codeData.params.resource}`); - } - this.codes.delete(authorizationCode); - const token = randomUUID(); - const tokenData = { - token, - clientId: client.client_id, - scopes: codeData.params.scopes || [], - expiresAt: Date.now() + 3600000, // 1 hour - resource: codeData.params.resource, - type: 'access' - }; - this.tokens.set(token, tokenData); - return { - access_token: token, - token_type: 'bearer', - expires_in: 3600, - scope: (codeData.params.scopes || []).join(' ') - }; - } - async exchangeRefreshToken(_client, _refreshToken, _scopes, _resource) { - throw new Error('Not implemented for example demo'); - } - async verifyAccessToken(token) { - const tokenData = this.tokens.get(token); - if (!tokenData || !tokenData.expiresAt || tokenData.expiresAt < Date.now()) { - throw new Error('Invalid or expired token'); - } - return { - token, - clientId: tokenData.clientId, - scopes: tokenData.scopes, - expiresAt: Math.floor(tokenData.expiresAt / 1000), - resource: tokenData.resource - }; - } -} -export const setupAuthServer = ({ authServerUrl, mcpServerUrl, strictResource }) => { - // Create separate auth server app - // NOTE: This is a separate app on a separate port to illustrate - // how to separate an OAuth Authorization Server from a Resource - // server in the SDK. The SDK is not intended to be provide a standalone - // authorization server. - const validateResource = strictResource - ? (resource) => { - if (!resource) - return false; - const expectedResource = resourceUrlFromServerUrl(mcpServerUrl); - return resource.toString() === expectedResource.toString(); - } - : undefined; - const provider = new DemoInMemoryAuthProvider(validateResource); - const authApp = express(); - authApp.use(express.json()); - // For introspection requests - authApp.use(express.urlencoded()); - // Add OAuth routes to the auth server - // NOTE: this will also add a protected resource metadata route, - // but it won't be used, so leave it. - authApp.use(mcpAuthRouter({ - provider, - issuerUrl: authServerUrl, - scopesSupported: ['mcp:tools'] - })); - authApp.post('/introspect', async (req, res) => { - try { - const { token } = req.body; - if (!token) { - res.status(400).json({ error: 'Token is required' }); - return; - } - const tokenInfo = await provider.verifyAccessToken(token); - res.json({ - active: true, - client_id: tokenInfo.clientId, - scope: tokenInfo.scopes.join(' '), - exp: tokenInfo.expiresAt, - aud: tokenInfo.resource - }); - return; - } - catch (error) { - res.status(401).json({ - active: false, - error: 'Unauthorized', - error_description: `Invalid token: ${error}` - }); - } - }); - const auth_port = authServerUrl.port; - // Start the auth server - authApp.listen(auth_port, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`OAuth Authorization Server listening on port ${auth_port}`); - }); - // Note: we could fetch this from the server, but then we end up - // with some top level async which gets annoying. - const oauthMetadata = createOAuthMetadata({ - provider, - issuerUrl: authServerUrl, - scopesSupported: ['mcp:tools'] - }); - oauthMetadata.introspection_endpoint = new URL('/introspect', authServerUrl).href; - return oauthMetadata; -}; -//# sourceMappingURL=demoInMemoryOAuthProvider.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/demoInMemoryOAuthProvider.js.map b/dist/esm/examples/server/demoInMemoryOAuthProvider.js.map deleted file mode 100644 index 80fcc5502d..0000000000 --- a/dist/esm/examples/server/demoInMemoryOAuthProvider.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"demoInMemoryOAuthProvider.js","sourceRoot":"","sources":["../../../../src/examples/server/demoInMemoryOAuthProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAIzC,OAAO,OAA8B,MAAM,SAAS,CAAC;AAErD,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,6BAA6B,CAAC;AACjF,OAAO,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAC;AACtE,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAElE,MAAM,OAAO,wBAAwB;IAArC;QACY,YAAO,GAAG,IAAI,GAAG,EAAsC,CAAC;IAUpE,CAAC;IARG,KAAK,CAAC,SAAS,CAAC,QAAgB;QAC5B,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACtC,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,cAA0C;QAC3D,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC;QAC3D,OAAO,cAAc,CAAC;IAC1B,CAAC;CACJ;AAED;;;;;;;GAOG;AACH,MAAM,OAAO,wBAAwB;IAWjC,YAAoB,gBAA8C;QAA9C,qBAAgB,GAAhB,gBAAgB,CAA8B;QAVlE,iBAAY,GAAG,IAAI,wBAAwB,EAAE,CAAC;QACtC,UAAK,GAAG,IAAI,GAAG,EAMpB,CAAC;QACI,WAAM,GAAG,IAAI,GAAG,EAAoB,CAAC;IAEwB,CAAC;IAEtE,KAAK,CAAC,SAAS,CAAC,MAAkC,EAAE,MAA2B,EAAE,GAAa;QAC1F,MAAM,IAAI,GAAG,UAAU,EAAE,CAAC;QAE1B,M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I;gBACZ,SAAS,EAAE,SAAS,CAAC,QAAQ;gBAC7B,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC;gBACjC,GAAG,EAAE,SAAS,CAAC,SAAS;gBACxB,GAAG,EAAE,SAAS,CAAC,QAAQ;aAC1B,CAAC,CAAC;YACH,OAAO;QACX,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;gBACjB,MAAM,EAAE,KAAK;gBACb,KAAK,EAAE,cAAc;gBACrB,iBAAiB,EAAE,kBAAkB,KAAK,EAAE;aAC/C,CAAC,CAAC;QACP,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,MAAM,SAAS,GAAG,aAAa,CAAC,IAAI,CAAC;IACrC,wBAAwB;IACxB,OAAO,CAAC,MAAM,CAAC,SAAS,EAAE,KAAK,CAAC,EAAE;QAC9B,IAAI,KAAK,EAAE,CAAC;YACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;YAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QACpB,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,gDAAgD,SAAS,EAAE,CAAC,CAAC;IAC7E,CAAC,CAAC,CAAC;IAEH,gEAAgE;IAChE,iDAAiD;IACjD,MAAM,aAAa,GAAkB,mBAAmB,CAAC;QACrD,QAAQ;QACR,SAAS,EAAE,aAAa;QACxB,eAAe,EAAE,CAAC,WAAW,CAAC;KACjC,CAAC,CAAC;IAEH,aAAa,CAAC,sBAAsB,GAAG,IAAI,GAAG,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC,IAAI,CAAC;IAElF,OAAO,aAAa,CAAC;AACzB,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationFormExample.d.ts b/dist/esm/examples/server/elicitationFormExample.d.ts deleted file mode 100644 index e4b736e0f2..0000000000 --- a/dist/esm/examples/server/elicitationFormExample.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=elicitationFormExample.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationFormExample.d.ts.map b/dist/esm/examples/server/elicitationFormExample.d.ts.map deleted file mode 100644 index c569df428d..0000000000 --- a/dist/esm/examples/server/elicitationFormExample.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"elicitationFormExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/elicitationFormExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationFormExample.js b/dist/esm/examples/server/elicitationFormExample.js deleted file mode 100644 index 1a651166dc..0000000000 --- a/dist/esm/examples/server/elicitationFormExample.js +++ /dev/null @@ -1,436 +0,0 @@ -// Run with: npx tsx src/examples/server/elicitationFormExample.ts -// -// This example demonstrates how to use form elicitation to collect structured user input -// with JSON Schema validation via a local HTTP server with SSE streaming. -// Form elicitation allows servers to request *non-sensitive* user input through the client -// with schema-based validation. -// Note: See also elicitationUrlExample.ts for an example of using URL elicitation -// to collect *sensitive* user input via a browser. -import { randomUUID } from 'node:crypto'; -import cors from 'cors'; -import express from 'express'; -import { McpServer } from '../../server/mcp.js'; -import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; -import { isInitializeRequest } from '../../types.js'; -// Create MCP server - it will automatically use AjvJsonSchemaValidator with sensible defaults -// The validator supports format validation (email, date, etc.) if ajv-formats is installed -const mcpServer = new McpServer({ - name: 'form-elicitation-example-server', - version: '1.0.0' -}, { - capabilities: {} -}); -/** - * Example 1: Simple user registration tool - * Collects username, email, and password from the user - */ -mcpServer.registerTool('register_user', { - description: 'Register a new user account by collecting their information', - inputSchema: {} -}, async () => { - try { - // Request user information through form elicitation - const result = await mcpServer.server.elicitInput({ - mode: 'form', - message: 'Please provide your registration information:', - requestedSchema: { - type: 'object', - properties: { - username: { - type: 'string', - title: 'Username', - description: 'Your desired username (3-20 characters)', - minLength: 3, - maxLength: 20 - }, - email: { - type: 'string', - title: 'Email', - description: 'Your email address', - format: 'email' - }, - password: { - type: 'string', - title: 'Password', - description: 'Your password (min 8 characters)', - minLength: 8 - }, - newsletter: { - type: 'boolean', - title: 'Newsletter', - description: 'Subscribe to newsletter?', - default: false - } - }, - required: ['username', 'email', 'password'] - } - }); - // Handle the different possible actions - if (result.action === 'accept' && result.content) { - const { username, email, newsletter } = result.content; - return { - content: [ - { - type: 'text', - text: `Registration successful!\n\nUsername: ${username}\nEmail: ${email}\nNewsletter: ${newsletter ? 'Yes' : 'No'}` - } - ] - }; - } - else if (result.action === 'decline') { - return { - content: [ - { - type: 'text', - text: 'Registration cancelled by user.' - } - ] - }; - } - else { - return { - content: [ - { - type: 'text', - text: 'Registration was cancelled.' - } - ] - }; - } - } - catch (error) { - return { - content: [ - { - type: 'text', - text: `Registration failed: ${error instanceof Error ? error.message : String(error)}` - } - ], - isError: true - }; - } -}); -/** - * Example 2: Multi-step workflow with multiple form elicitation requests - * Demonstrates how to collect information in multiple steps - */ -mcpServer.registerTool('create_event', { - description: 'Create a calendar event by collecting event details', - inputSchema: {} -}, async () => { - try { - // Step 1: Collect basic event information - const basicInfo = await mcpServer.server.elicitInput({ - mode: 'form', - message: 'Step 1: Enter basic event information', - requestedSchema: { - type: 'object', - properties: { - title: { - type: 'string', - title: 'Event Title', - description: 'Name of the event', - minLength: 1 - }, - description: { - type: 'string', - title: 'Description', - description: 'Event description (optional)' - } - }, - required: ['title'] - } - }); - if (basicInfo.action !== 'accept' || !basicInfo.content) { - return { - content: [{ type: 'text', text: 'Event creation cancelled.' }] - }; - } - // Step 2: Collect date and time - const dateTime = await mcpServer.server.elicitInput({ - mode: 'form', - message: 'Step 2: Enter date and time', - requestedSchema: { - type: 'object', - properties: { - date: { - type: 'string', - title: 'Date', - description: 'Event date', - format: 'date' - }, - startTime: { - type: 'string', - title: 'Start Time', - description: 'Event start time (HH:MM)' - }, - duration: { - type: 'integer', - title: 'Duration', - description: 'Duration in minutes', - minimum: 15, - maximum: 480 - } - }, - required: ['date', 'startTime', 'duration'] - } - }); - if (dateTime.action !== 'accept' || !dateTime.content) { - return { - content: [{ type: 'text', text: 'Event creation cancelled.' }] - }; - } - // Combine all collected information - const event = { - ...basicInfo.content, - ...dateTime.content - }; - return { - content: [ - { - type: 'text', - text: `Event created successfully!\n\n${JSON.stringify(event, null, 2)}` - } - ] - }; - } - catch (error) { - return { - content: [ - { - type: 'text', - text: `Event creation failed: ${error instanceof Error ? error.message : String(error)}` - } - ], - isError: true - }; - } -}); -/** - * Example 3: Collecting address information - * Demonstrates validation with patterns and optional fields - */ -mcpServer.registerTool('update_shipping_address', { - description: 'Update shipping address with validation', - inputSchema: {} -}, async () => { - try { - const result = await mcpServer.server.elicitInput({ - mode: 'form', - message: 'Please provide your shipping address:', - requestedSchema: { - type: 'object', - properties: { - name: { - type: 'string', - title: 'Full Name', - description: 'Recipient name', - minLength: 1 - }, - street: { - type: 'string', - title: 'Street Address', - minLength: 1 - }, - city: { - type: 'string', - title: 'City', - minLength: 1 - }, - state: { - type: 'string', - title: 'State/Province', - minLength: 2, - maxLength: 2 - }, - zipCode: { - type: 'string', - title: 'ZIP/Postal Code', - description: '5-digit ZIP code' - }, - phone: { - type: 'string', - title: 'Phone Number (optional)', - description: 'Contact phone number' - } - }, - required: ['name', 'street', 'city', 'state', 'zipCode'] - } - }); - if (result.action === 'accept' && result.content) { - return { - content: [ - { - type: 'text', - text: `Address updated successfully!\n\n${JSON.stringify(result.content, null, 2)}` - } - ] - }; - } - else if (result.action === 'decline') { - return { - content: [{ type: 'text', text: 'Address update cancelled by user.' }] - }; - } - else { - return { - content: [{ type: 'text', text: 'Address update was cancelled.' }] - }; - } - } - catch (error) { - return { - content: [ - { - type: 'text', - text: `Address update failed: ${error instanceof Error ? error.message : String(error)}` - } - ], - isError: true - }; - } -}); -async function main() { - const PORT = process.env.PORT ? parseInt(process.env.PORT, 10) : 3000; - const app = express(); - app.use(express.json()); - // Allow CORS for all domains, expose the Mcp-Session-Id header - app.use(cors({ - origin: '*', - exposedHeaders: ['Mcp-Session-Id'] - })); - // Map to store transports by session ID - const transports = {}; - // MCP POST endpoint - const mcpPostHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (sessionId) { - console.log(`Received MCP request for session: ${sessionId}`); - } - try { - let transport; - if (sessionId && transports[sessionId]) { - // Reuse existing transport for this session - transport = transports[sessionId]; - } - else if (!sessionId && isInitializeRequest(req.body)) { - // New initialization request - create new transport - transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => randomUUID(), - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - console.log(`Session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - } - }); - // Set up onclose handler to clean up transport when closed - transport.onclose = () => { - const sid = transport.sessionId; - if (sid && transports[sid]) { - console.log(`Transport closed for session ${sid}, removing from transports map`); - delete transports[sid]; - } - }; - // Connect the transport to the MCP server BEFORE handling the request - await mcpServer.connect(transport); - await transport.handleRequest(req, res, req.body); - return; - } - else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - // Handle the request with existing transport - await transport.handleRequest(req, res, req.body); - } - catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } - }; - app.post('/mcp', mcpPostHandler); - // Handle GET requests for SSE streams - const mcpGetHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - console.log(`Establishing SSE stream for session ${sessionId}`); - const transport = transports[sessionId]; - await transport.handleRequest(req, res); - }; - app.get('/mcp', mcpGetHandler); - // Handle DELETE requests for session termination - const mcpDeleteHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - console.log(`Received session termination request for session ${sessionId}`); - try { - const transport = transports[sessionId]; - await transport.handleRequest(req, res); - } - catch (error) { - console.error('Error handling session termination:', error); - if (!res.headersSent) { - res.status(500).send('Error processing session termination'); - } - } - }; - app.delete('/mcp', mcpDeleteHandler); - // Start listening - app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`Form elicitation example server is running on http://localhost:${PORT}/mcp`); - console.log('Available tools:'); - console.log(' - register_user: Collect user registration information'); - console.log(' - create_event: Multi-step event creation'); - console.log(' - update_shipping_address: Collect and validate address'); - console.log('\nConnect your MCP client to this server using the HTTP transport.'); - }); - // Handle server shutdown - process.on('SIGINT', async () => { - console.log('Shutting down server...'); - // Close all active transports to properly clean up resources - for (const sessionId in transports) { - try { - console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId].close(); - delete transports[sessionId]; - } - catch (error) { - console.error(`Error closing transport for session ${sessionId}:`, error); - } - } - console.log('Server shutdown complete'); - process.exit(0); - }); -} -main().catch(error => { - console.error('Server error:', error); - process.exit(1); -}); -//# sourceMappingURL=elicitationFormExample.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationFormExample.js.map b/dist/esm/examples/server/elicitationFormExample.js.map deleted file mode 100644 index 0a486154e0..0000000000 --- a/dist/esm/examples/server/elicitationFormExample.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"elicitationFormExample.js","sourceRoot":"","sources":["../../../../src/examples/server/elicitationFormExample.ts"],"names":[],"mappings":"AAAA,kEAAkE;AAClE,EAAE;AACF,yFAAyF;AACzF,0EAA0E;AAC1E,2FAA2F;AAC3F,gCAAgC;AAChC,kFAAkF;AAClF,mDAAmD;AAEnD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,OAAwC,MAAM,SAAS,CAAC;AAC/D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AkB,CAAC,CAAC;QAChC,OAAO,CAAC,GAAG,CAAC,0DAA0D,CAAC,CAAC;QACxE,OAAO,CAAC,GAAG,CAAC,6CAA6C,CAAC,CAAC;QAC3D,OAAO,CAAC,GAAG,CAAC,2DAA2D,CAAC,CAAC;QACzE,OAAO,CAAC,GAAG,CAAC,oEAAoE,CAAC,CAAC;IACtF,CAAC,CAAC,CAAC;IAEH,yBAAyB;IACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;QAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;QAEvC,6DAA6D;QAC7D,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;YACjC,IAAI,CAAC;gBACD,OAAO,CAAC,GAAG,CAAC,iCAAiC,SAAS,EAAE,CAAC,CAAC;gBAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;gBACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;YACjC,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;YAC9E,CAAC;QACL,CAAC;QACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;QACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC,CAAC,CAAC;AACP,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationUrlExample.d.ts b/dist/esm/examples/server/elicitationUrlExample.d.ts deleted file mode 100644 index 611f6eba22..0000000000 --- a/dist/esm/examples/server/elicitationUrlExample.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=elicitationUrlExample.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationUrlExample.d.ts.map b/dist/esm/examples/server/elicitationUrlExample.d.ts.map deleted file mode 100644 index 04acd6664d..0000000000 --- a/dist/esm/examples/server/elicitationUrlExample.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"elicitationUrlExample.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/elicitationUrlExample.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationUrlExample.js b/dist/esm/examples/server/elicitationUrlExample.js deleted file mode 100644 index c40b3084b0..0000000000 --- a/dist/esm/examples/server/elicitationUrlExample.js +++ /dev/null @@ -1,650 +0,0 @@ -// Run with: npx tsx src/examples/server/elicitationUrlExample.ts -// -// This example demonstrates how to use URL elicitation to securely collect -// *sensitive* user input in a remote (HTTP) server. -// URL elicitation allows servers to prompt the end-user to open a URL in their browser -// to collect sensitive information. -// Note: See also elicitationFormExample.ts for an example of using form (not URL) elicitation -// to collect *non-sensitive* user input with a structured schema. -import express from 'express'; -import { randomUUID } from 'node:crypto'; -import { z } from 'zod'; -import { McpServer } from '../../server/mcp.js'; -import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; -import { getOAuthProtectedResourceMetadataUrl, mcpAuthMetadataRouter } from '../../server/auth/router.js'; -import { requireBearerAuth } from '../../server/auth/middleware/bearerAuth.js'; -import { UrlElicitationRequiredError, isInitializeRequest } from '../../types.js'; -import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; -import { setupAuthServer } from './demoInMemoryOAuthProvider.js'; -import { checkResourceAllowed } from '../../shared/auth-utils.js'; -import cors from 'cors'; -// Create an MCP server with implementation details -const getServer = () => { - const mcpServer = new McpServer({ - name: 'url-elicitation-http-server', - version: '1.0.0' - }, { - capabilities: { logging: {} } - }); - mcpServer.registerTool('payment-confirm', { - description: 'A tool that confirms a payment directly with a user', - inputSchema: { - cartId: z.string().describe('The ID of the cart to confirm') - } - }, async ({ cartId }, extra) => { - /* - In a real world scenario, there would be some logic here to check if the user has the provided cartId. - For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to confirm payment) - */ - const sessionId = extra.sessionId; - if (!sessionId) { - throw new Error('Expected a Session ID'); - } - // Create and track the elicitation - const elicitationId = generateTrackedElicitation(sessionId, elicitationId => mcpServer.server.createElicitationCompletionNotifier(elicitationId)); - throw new UrlElicitationRequiredError([ - { - mode: 'url', - message: 'This tool requires a payment confirmation. Open the link to confirm payment!', - url: `http://localhost:${MCP_PORT}/confirm-payment?session=${sessionId}&elicitation=${elicitationId}&cartId=${encodeURIComponent(cartId)}`, - elicitationId - } - ]); - }); - mcpServer.registerTool('third-party-auth', { - description: 'A demo tool that requires third-party OAuth credentials', - inputSchema: { - param1: z.string().describe('First parameter') - } - }, async (_, extra) => { - /* - In a real world scenario, there would be some logic here to check if we already have a valid access token for the user. - Auth info (with a subject or `sub` claim) can be typically be found in `extra.authInfo`. - If we do, we can just return the result of the tool call. - If we don't, we can throw an ElicitationRequiredError to request the user to authenticate. - For the purposes of this example, we'll throw an error (-> elicits the client to open a URL to authenticate). - */ - const sessionId = extra.sessionId; - if (!sessionId) { - throw new Error('Expected a Session ID'); - } - // Create and track the elicitation - const elicitationId = generateTrackedElicitation(sessionId, elicitationId => mcpServer.server.createElicitationCompletionNotifier(elicitationId)); - // Simulate OAuth callback and token exchange after 5 seconds - // In a real app, this would be called from your OAuth callback handler - setTimeout(() => { - console.log(`Simulating OAuth token received for elicitation ${elicitationId}`); - completeURLElicitation(elicitationId); - }, 5000); - throw new UrlElicitationRequiredError([ - { - mode: 'url', - message: 'This tool requires access to your example.com account. Open the link to authenticate!', - url: 'https://www.example.com/oauth/authorize', - elicitationId - } - ]); - }); - return mcpServer; -}; -const elicitationsMap = new Map(); -// Clean up old elicitations after 1 hour to prevent memory leaks -const ELICITATION_TTL_MS = 60 * 60 * 1000; // 1 hour -const CLEANUP_INTERVAL_MS = 10 * 60 * 1000; // 10 minutes -function cleanupOldElicitations() { - const now = new Date(); - for (const [id, metadata] of elicitationsMap.entries()) { - if (now.getTime() - metadata.createdAt.getTime() > ELICITATION_TTL_MS) { - elicitationsMap.delete(id); - console.log(`Cleaned up expired elicitation: ${id}`); - } - } -} -setInterval(cleanupOldElicitations, CLEANUP_INTERVAL_MS); -/** - * Elicitation IDs must be unique strings within the MCP session - * UUIDs are used in this example for simplicity - */ -function generateElicitationId() { - return randomUUID(); -} -/** - * Helper function to create and track a new elicitation. - */ -function generateTrackedElicitation(sessionId, createCompletionNotifier) { - const elicitationId = generateElicitationId(); - // Create a Promise and its resolver for tracking completion - let completeResolver; - const completedPromise = new Promise(resolve => { - completeResolver = resolve; - }); - const completionNotifier = createCompletionNotifier ? createCompletionNotifier(elicitationId) : undefined; - // Store the elicitation in our map - elicitationsMap.set(elicitationId, { - status: 'pending', - completedPromise, - completeResolver: completeResolver, - createdAt: new Date(), - sessionId, - completionNotifier - }); - return elicitationId; -} -/** - * Helper function to complete an elicitation. - */ -function completeURLElicitation(elicitationId) { - const elicitation = elicitationsMap.get(elicitationId); - if (!elicitation) { - console.warn(`Attempted to complete unknown elicitation: ${elicitationId}`); - return; - } - if (elicitation.status === 'complete') { - console.warn(`Elicitation already complete: ${elicitationId}`); - return; - } - // Update metadata - elicitation.status = 'complete'; - // Send completion notification to the client - if (elicitation.completionNotifier) { - console.log(`Sending notifications/elicitation/complete notification for elicitation ${elicitationId}`); - elicitation.completionNotifier().catch(error => { - console.error(`Failed to send completion notification for elicitation ${elicitationId}:`, error); - }); - } - // Resolve the promise to unblock any waiting code - elicitation.completeResolver(); -} -const MCP_PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; -const AUTH_PORT = process.env.MCP_AUTH_PORT ? parseInt(process.env.MCP_AUTH_PORT, 10) : 3001; -const app = express(); -app.use(express.json()); -// Allow CORS all domains, expose the Mcp-Session-Id header -app.use(cors({ - origin: '*', // Allow all origins - exposedHeaders: ['Mcp-Session-Id'], - credentials: true // Allow cookies to be sent cross-origin -})); -// Set up OAuth (required for this example) -let authMiddleware = null; -// Create auth middleware for MCP endpoints -const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`); -const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); -const oauthMetadata = setupAuthServer({ authServerUrl, mcpServerUrl, strictResource: true }); -const tokenVerifier = { - verifyAccessToken: async (token) => { - const endpoint = oauthMetadata.introspection_endpoint; - if (!endpoint) { - throw new Error('No token verification endpoint available in metadata'); - } - const response = await fetch(endpoint, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: new URLSearchParams({ - token: token - }).toString() - }); - if (!response.ok) { - throw new Error(`Invalid or expired token: ${await response.text()}`); - } - const data = await response.json(); - if (!data.aud) { - throw new Error(`Resource Indicator (RFC8707) missing`); - } - if (!checkResourceAllowed({ requestedResource: data.aud, configuredResource: mcpServerUrl })) { - throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); - } - // Convert the response to AuthInfo format - return { - token, - clientId: data.client_id, - scopes: data.scope ? data.scope.split(' ') : [], - expiresAt: data.exp - }; - } -}; -// Add metadata routes to the main MCP server -app.use(mcpAuthMetadataRouter({ - oauthMetadata, - resourceServerUrl: mcpServerUrl, - scopesSupported: ['mcp:tools'], - resourceName: 'MCP Demo Server' -})); -authMiddleware = requireBearerAuth({ - verifier: tokenVerifier, - requiredScopes: [], - resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl) -}); -/** - * API Key Form Handling - * - * Many servers today require an API key to operate, but there's no scalable way to do this dynamically for remote servers within MCP protocol. - * URL-mode elicitation enables the server to host a simple form and get the secret data securely from the user without involving the LLM or client. - **/ -async function sendApiKeyElicitation(sessionId, sender, createCompletionNotifier) { - if (!sessionId) { - console.error('No session ID provided'); - throw new Error('Expected a Session ID to track elicitation'); - } - console.log('🔑 URL elicitation demo: Requesting API key from client...'); - const elicitationId = generateTrackedElicitation(sessionId, createCompletionNotifier); - try { - const result = await sender({ - mode: 'url', - message: 'Please provide your API key to authenticate with this server', - // Host the form on the same server. In a real app, you might coordinate passing these state variables differently. - url: `http://localhost:${MCP_PORT}/api-key-form?session=${sessionId}&elicitation=${elicitationId}`, - elicitationId - }); - switch (result.action) { - case 'accept': - console.log('🔑 URL elicitation demo: Client accepted the API key elicitation (now pending form submission)'); - // Wait for the API key to be submitted via the form - // The form submission will complete the elicitation - break; - default: - console.log('🔑 URL elicitation demo: Client declined to provide an API key'); - // In a real app, this might close the connection, but for the demo, we'll continue - break; - } - } - catch (error) { - console.error('Error during API key elicitation:', error); - } -} -// API Key Form endpoint - serves a simple HTML form -app.get('/api-key-form', (req, res) => { - const mcpSessionId = req.query.session; - const elicitationId = req.query.elicitation; - if (!mcpSessionId || !elicitationId) { - res.status(400).send('

Error

Missing required parameters

'); - return; - } - // Check for user session cookie - // In production, this is often handled by some user auth middleware to ensure the user has a valid session - // This session is different from the MCP session. - // This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in. - const userSession = getUserSessionCookie(req.headers.cookie); - if (!userSession) { - res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); - return; - } - // Serve a simple HTML form - res.send(` - - - - Submit Your API Key - - - -

API Key Required

-
✓ Logged in as: ${userSession.name}
-
- - - - -
-
This is a demo showing how a server can securely elicit sensitive data from a user using a URL.
- - - `); -}); -// Handle API key form submission -app.post('/api-key-form', express.urlencoded(), (req, res) => { - const { session: sessionId, apiKey, elicitation: elicitationId } = req.body; - if (!sessionId || !apiKey || !elicitationId) { - res.status(400).send('

Error

Missing required parameters

'); - return; - } - // Check for user session cookie here too - const userSession = getUserSessionCookie(req.headers.cookie); - if (!userSession) { - res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); - return; - } - // A real app might store this API key to be used later for the user. - console.log(`🔑 Received API key \x1b[32m${apiKey}\x1b[0m for session ${sessionId}`); - // If we have an elicitationId, complete the elicitation - completeURLElicitation(elicitationId); - // Send a success response - res.send(` - - - - Success - - - -
-

Success ✓

-

API key received.

-
-

You can close this window and return to your MCP client.

- - - `); -}); -// Helper to get the user session from the demo_session cookie -function getUserSessionCookie(cookieHeader) { - if (!cookieHeader) - return null; - const cookies = cookieHeader.split(';'); - for (const cookie of cookies) { - const [name, value] = cookie.trim().split('='); - if (name === 'demo_session' && value) { - try { - return JSON.parse(decodeURIComponent(value)); - } - catch (error) { - console.error('Failed to parse demo_session cookie:', error); - return null; - } - } - } - return null; -} -/** - * Payment Confirmation Form Handling - * - * This demonstrates how a server can use URL-mode elicitation to get user confirmation - * for sensitive operations like payment processing. - **/ -// Payment Confirmation Form endpoint - serves a simple HTML form -app.get('/confirm-payment', (req, res) => { - const mcpSessionId = req.query.session; - const elicitationId = req.query.elicitation; - const cartId = req.query.cartId; - if (!mcpSessionId || !elicitationId) { - res.status(400).send('

Error

Missing required parameters

'); - return; - } - // Check for user session cookie - // In production, this is often handled by some user auth middleware to ensure the user has a valid session - // This session is different from the MCP session. - // This userSession is the cookie that the MCP Server's Authorization Server sets for the user when they log in. - const userSession = getUserSessionCookie(req.headers.cookie); - if (!userSession) { - res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); - return; - } - // Serve a simple HTML form - res.send(` - - - - Confirm Payment - - - -

Confirm Payment

-
✓ Logged in as: ${userSession.name}
- ${cartId ? `
Cart ID: ${cartId}
` : ''} -
- ⚠️ Please review your order before confirming. -
-
- - - ${cartId ? `` : ''} - - -
-
This is a demo showing how a server can securely get user confirmation for sensitive operations using URL-mode elicitation.
- - - `); -}); -// Handle Payment Confirmation form submission -app.post('/confirm-payment', express.urlencoded(), (req, res) => { - const { session: sessionId, elicitation: elicitationId, cartId, action } = req.body; - if (!sessionId || !elicitationId) { - res.status(400).send('

Error

Missing required parameters

'); - return; - } - // Check for user session cookie here too - const userSession = getUserSessionCookie(req.headers.cookie); - if (!userSession) { - res.status(401).send('

Error

Unauthorized - please reconnect to login again

'); - return; - } - if (action === 'confirm') { - // A real app would process the payment here - console.log(`💳 Payment confirmed for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`); - // Complete the elicitation - completeURLElicitation(elicitationId); - // Send a success response - res.send(` - - - - Payment Confirmed - - - -
-

Payment Confirmed ✓

-

Your payment has been successfully processed.

- ${cartId ? `

Cart ID: ${cartId}

` : ''} -
-

You can close this window and return to your MCP client.

- - - `); - } - else if (action === 'cancel') { - console.log(`💳 Payment cancelled for cart ${cartId || 'unknown'} by user ${userSession.name} (session ${sessionId})`); - // The client will still receive a notifications/elicitation/complete notification, - // which indicates that the out-of-band interaction is complete (but not necessarily successful) - completeURLElicitation(elicitationId); - res.send(` - - - - Payment Cancelled - - - -
-

Payment Cancelled

-

Your payment has been cancelled.

-
-

You can close this window and return to your MCP client.

- - - `); - } - else { - res.status(400).send('

Error

Invalid action

'); - } -}); -// Map to store transports by session ID -const transports = {}; -const sessionsNeedingElicitation = {}; -// MCP POST endpoint -const mcpPostHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - console.debug(`Received MCP POST for session: ${sessionId || 'unknown'}`); - try { - let transport; - if (sessionId && transports[sessionId]) { - // Reuse existing transport - transport = transports[sessionId]; - } - else if (!sessionId && isInitializeRequest(req.body)) { - const server = getServer(); - // New initialization request - const eventStore = new InMemoryEventStore(); - transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => randomUUID(), - eventStore, // Enable resumability - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - // This avoids race conditions where requests might come in before the session is stored - console.log(`Session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - sessionsNeedingElicitation[sessionId] = { - elicitationSender: params => server.server.elicitInput(params), - createCompletionNotifier: elicitationId => server.server.createElicitationCompletionNotifier(elicitationId) - }; - } - }); - // Set up onclose handler to clean up transport when closed - transport.onclose = () => { - const sid = transport.sessionId; - if (sid && transports[sid]) { - console.log(`Transport closed for session ${sid}, removing from transports map`); - delete transports[sid]; - delete sessionsNeedingElicitation[sid]; - } - }; - // Connect the transport to the MCP server BEFORE handling the request - // so responses can flow back through the same transport - await server.connect(transport); - await transport.handleRequest(req, res, req.body); - return; // Already handled - } - else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - // Handle the request with existing transport - no need to reconnect - // The existing transport is already connected to the server - await transport.handleRequest(req, res, req.body); - } - catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}; -// Set up routes with auth middleware -app.post('/mcp', authMiddleware, mcpPostHandler); -// Handle GET requests for SSE streams (using built-in support from StreamableHTTP) -const mcpGetHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - // Check for Last-Event-ID header for resumability - const lastEventId = req.headers['last-event-id']; - if (lastEventId) { - console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`); - } - else { - console.log(`Establishing new SSE stream for session ${sessionId}`); - } - const transport = transports[sessionId]; - await transport.handleRequest(req, res); - if (sessionsNeedingElicitation[sessionId]) { - const { elicitationSender, createCompletionNotifier } = sessionsNeedingElicitation[sessionId]; - // Send an elicitation request to the client in the background - sendApiKeyElicitation(sessionId, elicitationSender, createCompletionNotifier) - .then(() => { - // Only delete on successful send for this demo - delete sessionsNeedingElicitation[sessionId]; - console.log(`🔑 URL elicitation demo: Finished sending API key elicitation request for session ${sessionId}`); - }) - .catch(error => { - console.error('Error sending API key elicitation:', error); - // Keep in map to potentially retry on next reconnect - }); - } -}; -// Set up GET route with conditional auth middleware -app.get('/mcp', authMiddleware, mcpGetHandler); -// Handle DELETE requests for session termination (according to MCP spec) -const mcpDeleteHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - console.log(`Received session termination request for session ${sessionId}`); - try { - const transport = transports[sessionId]; - await transport.handleRequest(req, res); - } - catch (error) { - console.error('Error handling session termination:', error); - if (!res.headersSent) { - res.status(500).send('Error processing session termination'); - } - } -}; -// Set up DELETE route with auth middleware -app.delete('/mcp', authMiddleware, mcpDeleteHandler); -app.listen(MCP_PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`MCP Streamable HTTP Server listening on port ${MCP_PORT}`); -}); -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - // Close all active transports to properly clean up resources - for (const sessionId in transports) { - try { - console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId].close(); - delete transports[sessionId]; - delete sessionsNeedingElicitation[sessionId]; - } - catch (error) { - console.error(`Error closing transport for session ${sessionId}:`, error); - } - } - console.log('Server shutdown complete'); - process.exit(0); -}); -//# sourceMappingURL=elicitationUrlExample.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/elicitationUrlExample.js.map b/dist/esm/examples/server/elicitationUrlExample.js.map deleted file mode 100644 index bb8d75b8fd..0000000000 --- a/dist/esm/examples/server/elicitationUrlExample.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"elicitationUrlExample.js","sourceRoot":"","sources":["../../../../src/examples/server/elicitationUrlExample.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,EAAE;AACF,2EAA2E;AAC3E,oDAAoD;AACpD,uFAAuF;AACvF,oCAAoC;AACpC,8FAA8F;AAC9F,kEAAkE;AAElE,OAAO,OAA8B,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,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AC;YAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;YAC7B,OAAO,0BAA0B,CAAC,SAAS,CAAC,CAAC;QACjD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts b/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts deleted file mode 100644 index 477fa6bae7..0000000000 --- a/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=jsonResponseStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts.map b/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts.map deleted file mode 100644 index ee8117ee2e..0000000000 --- a/dist/esm/examples/server/jsonResponseStreamableHttp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"jsonResponseStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/jsonResponseStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/jsonResponseStreamableHttp.js b/dist/esm/examples/server/jsonResponseStreamableHttp.js deleted file mode 100644 index f9bd04d87b..0000000000 --- a/dist/esm/examples/server/jsonResponseStreamableHttp.js +++ /dev/null @@ -1,147 +0,0 @@ -import express from 'express'; -import { randomUUID } from 'node:crypto'; -import { McpServer } from '../../server/mcp.js'; -import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; -import * as z from 'zod/v4'; -import { isInitializeRequest } from '../../types.js'; -import cors from 'cors'; -// Create an MCP server with implementation details -const getServer = () => { - const server = new McpServer({ - name: 'json-response-streamable-http-server', - version: '1.0.0' - }, { - capabilities: { - logging: {} - } - }); - // Register a simple tool that returns a greeting - server.tool('greet', 'A simple greeting tool', { - name: z.string().describe('Name to greet') - }, async ({ name }) => { - return { - content: [ - { - type: 'text', - text: `Hello, ${name}!` - } - ] - }; - }); - // Register a tool that sends multiple greetings with notifications - server.tool('multi-greet', 'A tool that sends different greetings with delays between them', { - name: z.string().describe('Name to greet') - }, async ({ name }, extra) => { - const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); - await server.sendLoggingMessage({ - level: 'debug', - data: `Starting multi-greet for ${name}` - }, extra.sessionId); - await sleep(1000); // Wait 1 second before first greeting - await server.sendLoggingMessage({ - level: 'info', - data: `Sending first greeting to ${name}` - }, extra.sessionId); - await sleep(1000); // Wait another second before second greeting - await server.sendLoggingMessage({ - level: 'info', - data: `Sending second greeting to ${name}` - }, extra.sessionId); - return { - content: [ - { - type: 'text', - text: `Good morning, ${name}!` - } - ] - }; - }); - return server; -}; -const app = express(); -app.use(express.json()); -// Configure CORS to expose Mcp-Session-Id header for browser-based clients -app.use(cors({ - origin: '*', // Allow all origins - adjust as needed for production - exposedHeaders: ['Mcp-Session-Id'] -})); -// Map to store transports by session ID -const transports = {}; -app.post('/mcp', async (req, res) => { - console.log('Received MCP request:', req.body); - try { - // Check for existing session ID - const sessionId = req.headers['mcp-session-id']; - let transport; - if (sessionId && transports[sessionId]) { - // Reuse existing transport - transport = transports[sessionId]; - } - else if (!sessionId && isInitializeRequest(req.body)) { - // New initialization request - use JSON response mode - transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => randomUUID(), - enableJsonResponse: true, // Enable JSON response mode - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - // This avoids race conditions where requests might come in before the session is stored - console.log(`Session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - } - }); - // Connect the transport to the MCP server BEFORE handling the request - const server = getServer(); - await server.connect(transport); - await transport.handleRequest(req, res, req.body); - return; // Already handled - } - else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - // Handle the request with existing transport - no need to reconnect - await transport.handleRequest(req, res, req.body); - } - catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}); -// Handle GET requests for SSE streams according to spec -app.get('/mcp', async (req, res) => { - // Since this is a very simple example, we don't support GET requests for this server - // The spec requires returning 405 Method Not Allowed in this case - res.status(405).set('Allow', 'POST').send('Method Not Allowed'); -}); -// Start the server -const PORT = 3000; -app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`MCP Streamable HTTP Server listening on port ${PORT}`); -}); -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - process.exit(0); -}); -//# sourceMappingURL=jsonResponseStreamableHttp.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/jsonResponseStreamableHttp.js.map b/dist/esm/examples/server/jsonResponseStreamableHttp.js.map deleted file mode 100644 index 67ae23baa7..0000000000 --- a/dist/esm/examples/server/jsonResponseStreamableHttp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"jsonResponseStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/jsonResponseStreamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,OAA8B,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,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GAAG,CAAC,CAAC,IAAI,CAAC;gBACjB,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE;oBACH,IAAI,EAAE,CAAC,KAAK;oBACZ,OAAO,EAAE,uBAAuB;iBACnC;gBACD,EAAE,EAAE,IAAI;aACX,CAAC,CAAC;QACP,CAAC;IACL,CAAC;AACL,CAAC,CAAC,CAAC;AAEH,wDAAwD;AACxD,GAAG,CAAC,GAAG,CAAC,MAAM,EAAE,KAAK,EAAE,GAAY,EAAE,GAAa,EAAE,EAAE;IAClD,qFAAqF;IACrF,kEAAkE;IAClE,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;AACpE,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,gDAAgD,IAAI,EAAE,CAAC,CAAC;AACxE,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/mcpServerOutputSchema.d.ts b/dist/esm/examples/server/mcpServerOutputSchema.d.ts deleted file mode 100644 index a6cb497473..0000000000 --- a/dist/esm/examples/server/mcpServerOutputSchema.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env node -/** - * Example MCP server using the high-level McpServer API with outputSchema - * This demonstrates how to easily create tools with structured output - */ -export {}; -//# sourceMappingURL=mcpServerOutputSchema.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/mcpServerOutputSchema.d.ts.map b/dist/esm/examples/server/mcpServerOutputSchema.d.ts.map deleted file mode 100644 index bd3abdcc26..0000000000 --- a/dist/esm/examples/server/mcpServerOutputSchema.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"mcpServerOutputSchema.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/mcpServerOutputSchema.ts"],"names":[],"mappings":";AACA;;;GAGG"} \ No newline at end of file diff --git a/dist/esm/examples/server/mcpServerOutputSchema.js b/dist/esm/examples/server/mcpServerOutputSchema.js deleted file mode 100644 index 17b52b73e5..0000000000 --- a/dist/esm/examples/server/mcpServerOutputSchema.js +++ /dev/null @@ -1,70 +0,0 @@ -#!/usr/bin/env node -/** - * Example MCP server using the high-level McpServer API with outputSchema - * This demonstrates how to easily create tools with structured output - */ -import { McpServer } from '../../server/mcp.js'; -import { StdioServerTransport } from '../../server/stdio.js'; -import * as z from 'zod/v4'; -const server = new McpServer({ - name: 'mcp-output-schema-high-level-example', - version: '1.0.0' -}); -// Define a tool with structured output - Weather data -server.registerTool('get_weather', { - description: 'Get weather information for a city', - inputSchema: { - city: z.string().describe('City name'), - country: z.string().describe('Country code (e.g., US, UK)') - }, - outputSchema: { - temperature: z.object({ - celsius: z.number(), - fahrenheit: z.number() - }), - conditions: z.enum(['sunny', 'cloudy', 'rainy', 'stormy', 'snowy']), - humidity: z.number().min(0).max(100), - wind: z.object({ - speed_kmh: z.number(), - direction: z.string() - }) - } -}, async ({ city, country }) => { - // Parameters are available but not used in this example - void city; - void country; - // Simulate weather API call - const temp_c = Math.round((Math.random() * 35 - 5) * 10) / 10; - const conditions = ['sunny', 'cloudy', 'rainy', 'stormy', 'snowy'][Math.floor(Math.random() * 5)]; - const structuredContent = { - temperature: { - celsius: temp_c, - fahrenheit: Math.round(((temp_c * 9) / 5 + 32) * 10) / 10 - }, - conditions, - humidity: Math.round(Math.random() * 100), - wind: { - speed_kmh: Math.round(Math.random() * 50), - direction: ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'][Math.floor(Math.random() * 8)] - } - }; - return { - content: [ - { - type: 'text', - text: JSON.stringify(structuredContent, null, 2) - } - ], - structuredContent - }; -}); -async function main() { - const transport = new StdioServerTransport(); - await server.connect(transport); - console.error('High-level Output Schema Example Server running on stdio'); -} -main().catch(error => { - console.error('Server error:', error); - process.exit(1); -}); -//# sourceMappingURL=mcpServerOutputSchema.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/mcpServerOutputSchema.js.map b/dist/esm/examples/server/mcpServerOutputSchema.js.map deleted file mode 100644 index b932b856b6..0000000000 --- a/dist/esm/examples/server/mcpServerOutputSchema.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"mcpServerOutputSchema.js","sourceRoot":"","sources":["../../../../src/examples/server/mcpServerOutputSchema.ts"],"names":[],"mappings":";AACA;;;GAGG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC;IACzB,IAAI,EAAE,sCAAsC;IAC5C,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,sDAAsD;AACtD,MAAM,CAAC,YAAY,CACf,aAAa,EACb;IACI,WAAW,EAAE,oCAAoC;IACjD,WAAW,EAAE;QACT,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,WAAW,CAAC;QACtC,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,6BAA6B,CAAC;KAC9D;IACD,YAAY,EAAE;QACV,WAAW,EAAE,CA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AAG,GAAG,CAAC;QACzC,IAAI,EAAE;YACF,SAAS,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC;YACzC,SAAS,EAAE,CAAC,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,CAAC;SACzF;KACJ,CAAC;IAEF,OAAO;QACH,OAAO,EAAE;YACL;gBACI,IAAI,EAAE,MAAM;gBACZ,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,iBAAiB,EAAE,IAAI,EAAE,CAAC,CAAC;aACnD;SACJ;QACD,iBAAiB;KACpB,CAAC;AACN,CAAC,CACJ,CAAC;AAEF,KAAK,UAAU,IAAI;IACf,MAAM,SAAS,GAAG,IAAI,oBAAoB,EAAE,CAAC;IAC7C,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAChC,OAAO,CAAC,KAAK,CAAC,0DAA0D,CAAC,CAAC;AAC9E,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/simpleSseServer.d.ts b/dist/esm/examples/server/simpleSseServer.d.ts deleted file mode 100644 index 4269b7814f..0000000000 --- a/dist/esm/examples/server/simpleSseServer.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=simpleSseServer.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/simpleSseServer.d.ts.map b/dist/esm/examples/server/simpleSseServer.d.ts.map deleted file mode 100644 index 08a1b45021..0000000000 --- a/dist/esm/examples/server/simpleSseServer.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleSseServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleSseServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/simpleSseServer.js b/dist/esm/examples/server/simpleSseServer.js deleted file mode 100644 index 21e8ef96ba..0000000000 --- a/dist/esm/examples/server/simpleSseServer.js +++ /dev/null @@ -1,141 +0,0 @@ -import express from 'express'; -import { McpServer } from '../../server/mcp.js'; -import { SSEServerTransport } from '../../server/sse.js'; -import * as z from 'zod/v4'; -/** - * This example server demonstrates the deprecated HTTP+SSE transport - * (protocol version 2024-11-05). It mainly used for testing backward compatible clients. - * - * The server exposes two endpoints: - * - /mcp: For establishing the SSE stream (GET) - * - /messages: For receiving client messages (POST) - * - */ -// Create an MCP server instance -const getServer = () => { - const server = new McpServer({ - name: 'simple-sse-server', - version: '1.0.0' - }, { capabilities: { logging: {} } }); - server.tool('start-notification-stream', 'Starts sending periodic notifications', { - interval: z.number().describe('Interval in milliseconds between notifications').default(1000), - count: z.number().describe('Number of notifications to send').default(10) - }, async ({ interval, count }, extra) => { - const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); - let counter = 0; - // Send the initial notification - await server.sendLoggingMessage({ - level: 'info', - data: `Starting notification stream with ${count} messages every ${interval}ms` - }, extra.sessionId); - // Send periodic notifications - while (counter < count) { - counter++; - await sleep(interval); - try { - await server.sendLoggingMessage({ - level: 'info', - data: `Notification #${counter} at ${new Date().toISOString()}` - }, extra.sessionId); - } - catch (error) { - console.error('Error sending notification:', error); - } - } - return { - content: [ - { - type: 'text', - text: `Completed sending ${count} notifications every ${interval}ms` - } - ] - }; - }); - return server; -}; -const app = express(); -app.use(express.json()); -// Store transports by session ID -const transports = {}; -// SSE endpoint for establishing the stream -app.get('/mcp', async (req, res) => { - console.log('Received GET request to /sse (establishing SSE stream)'); - try { - // Create a new SSE transport for the client - // The endpoint for POST messages is '/messages' - const transport = new SSEServerTransport('/messages', res); - // Store the transport by session ID - const sessionId = transport.sessionId; - transports[sessionId] = transport; - // Set up onclose handler to clean up transport when closed - transport.onclose = () => { - console.log(`SSE transport closed for session ${sessionId}`); - delete transports[sessionId]; - }; - // Connect the transport to the MCP server - const server = getServer(); - await server.connect(transport); - console.log(`Established SSE stream with session ID: ${sessionId}`); - } - catch (error) { - console.error('Error establishing SSE stream:', error); - if (!res.headersSent) { - res.status(500).send('Error establishing SSE stream'); - } - } -}); -// Messages endpoint for receiving client JSON-RPC requests -app.post('/messages', async (req, res) => { - console.log('Received POST request to /messages'); - // Extract session ID from URL query parameter - // In the SSE protocol, this is added by the client based on the endpoint event - const sessionId = req.query.sessionId; - if (!sessionId) { - console.error('No session ID provided in request URL'); - res.status(400).send('Missing sessionId parameter'); - return; - } - const transport = transports[sessionId]; - if (!transport) { - console.error(`No active transport found for session ID: ${sessionId}`); - res.status(404).send('Session not found'); - return; - } - try { - // Handle the POST message with the transport - await transport.handlePostMessage(req, res, req.body); - } - catch (error) { - console.error('Error handling request:', error); - if (!res.headersSent) { - res.status(500).send('Error handling request'); - } - } -}); -// Start the server -const PORT = 3000; -app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`Simple SSE Server (deprecated protocol version 2024-11-05) listening on port ${PORT}`); -}); -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - // Close all active transports to properly clean up resources - for (const sessionId in transports) { - try { - console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId].close(); - delete transports[sessionId]; - } - catch (error) { - console.error(`Error closing transport for session ${sessionId}:`, error); - } - } - console.log('Server shutdown complete'); - process.exit(0); -}); -//# sourceMappingURL=simpleSseServer.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/simpleSseServer.js.map b/dist/esm/examples/server/simpleSseServer.js.map deleted file mode 100644 index 4ac49a2326..0000000000 --- a/dist/esm/examples/server/simpleSseServer.js.map +++ /dev/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C;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts b/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts deleted file mode 100644 index 0aa4ad2439..0000000000 --- a/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=simpleStatelessStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts.map b/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts.map deleted file mode 100644 index 92deb06ecb..0000000000 --- a/dist/esm/examples/server/simpleStatelessStreamableHttp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleStatelessStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleStatelessStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStatelessStreamableHttp.js b/dist/esm/examples/server/simpleStatelessStreamableHttp.js deleted file mode 100644 index d9e24a1d0a..0000000000 --- a/dist/esm/examples/server/simpleStatelessStreamableHttp.js +++ /dev/null @@ -1,142 +0,0 @@ -import express from 'express'; -import { McpServer } from '../../server/mcp.js'; -import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; -import * as z from 'zod/v4'; -import cors from 'cors'; -const getServer = () => { - // Create an MCP server with implementation details - const server = new McpServer({ - name: 'stateless-streamable-http-server', - version: '1.0.0' - }, { capabilities: { logging: {} } }); - // Register a simple prompt - server.prompt('greeting-template', 'A simple greeting prompt template', { - name: z.string().describe('Name to include in greeting') - }, async ({ name }) => { - return { - messages: [ - { - role: 'user', - content: { - type: 'text', - text: `Please greet ${name} in a friendly manner.` - } - } - ] - }; - }); - // Register a tool specifically for testing resumability - server.tool('start-notification-stream', 'Starts sending periodic notifications for testing resumability', { - interval: z.number().describe('Interval in milliseconds between notifications').default(100), - count: z.number().describe('Number of notifications to send (0 for 100)').default(10) - }, async ({ interval, count }, extra) => { - const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); - let counter = 0; - while (count === 0 || counter < count) { - counter++; - try { - await server.sendLoggingMessage({ - level: 'info', - data: `Periodic notification #${counter} at ${new Date().toISOString()}` - }, extra.sessionId); - } - catch (error) { - console.error('Error sending notification:', error); - } - // Wait for the specified interval - await sleep(interval); - } - return { - content: [ - { - type: 'text', - text: `Started sending periodic notifications every ${interval}ms` - } - ] - }; - }); - // Create a simple resource at a fixed URI - server.resource('greeting-resource', 'https://example.com/greetings/default', { mimeType: 'text/plain' }, async () => { - return { - contents: [ - { - uri: 'https://example.com/greetings/default', - text: 'Hello, world!' - } - ] - }; - }); - return server; -}; -const app = express(); -app.use(express.json()); -// Configure CORS to expose Mcp-Session-Id header for browser-based clients -app.use(cors({ - origin: '*', // Allow all origins - adjust as needed for production - exposedHeaders: ['Mcp-Session-Id'] -})); -app.post('/mcp', async (req, res) => { - const server = getServer(); - try { - const transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: undefined - }); - await server.connect(transport); - await transport.handleRequest(req, res, req.body); - res.on('close', () => { - console.log('Request closed'); - transport.close(); - server.close(); - }); - } - catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}); -app.get('/mcp', async (req, res) => { - console.log('Received GET MCP request'); - res.writeHead(405).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Method not allowed.' - }, - id: null - })); -}); -app.delete('/mcp', async (req, res) => { - console.log('Received DELETE MCP request'); - res.writeHead(405).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Method not allowed.' - }, - id: null - })); -}); -// Start the server -const PORT = 3000; -app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`MCP Stateless Streamable HTTP Server listening on port ${PORT}`); -}); -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - process.exit(0); -}); -//# sourceMappingURL=simpleStatelessStreamableHttp.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStatelessStreamableHttp.js.map b/dist/esm/examples/server/simpleStatelessStreamableHttp.js.map deleted file mode 100644 index 4963fadc1b..0000000000 --- a/dist/esm/examples/server/simpleStatelessStreamableHttp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleStatelessStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleStatelessStreamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,OAA8B,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,mDAAmD;IACnD,MAAM,MAAM,GAAG,IAAI,SAAS,CACxB;QACI,IAAI,EAAE,kCAAkC;QACxC,OAAO,EAAE,OAAO;KACnB,EACD,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,CACpC,CAAC;IAEF,2BAA2B;IAC3B,MAAM,CAAC,MAAM,CACT,mBAAmB,EACnB,mCAAmC,EACnC;QACI,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,6BAA6B,CAAC;KAC3D,EACD,KAAK,EAAE,EAAE,IAAI,EAAE,EAA4B,EAAE;QACzC,OAAO;YAC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C;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0DAA0D,IAAI,EAAE,CAAC,CAAC;AAClF,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStreamableHttp.d.ts b/dist/esm/examples/server/simpleStreamableHttp.d.ts deleted file mode 100644 index a20be42ca4..0000000000 --- a/dist/esm/examples/server/simpleStreamableHttp.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=simpleStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStreamableHttp.d.ts.map b/dist/esm/examples/server/simpleStreamableHttp.d.ts.map deleted file mode 100644 index e3cf042241..0000000000 --- a/dist/esm/examples/server/simpleStreamableHttp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/simpleStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStreamableHttp.js b/dist/esm/examples/server/simpleStreamableHttp.js deleted file mode 100644 index 0af6b16b6b..0000000000 --- a/dist/esm/examples/server/simpleStreamableHttp.js +++ /dev/null @@ -1,583 +0,0 @@ -import express from 'express'; -import { randomUUID } from 'node:crypto'; -import * as z from 'zod/v4'; -import { McpServer } from '../../server/mcp.js'; -import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; -import { getOAuthProtectedResourceMetadataUrl, mcpAuthMetadataRouter } from '../../server/auth/router.js'; -import { requireBearerAuth } from '../../server/auth/middleware/bearerAuth.js'; -import { isInitializeRequest } from '../../types.js'; -import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; -import { setupAuthServer } from './demoInMemoryOAuthProvider.js'; -import { checkResourceAllowed } from '../../shared/auth-utils.js'; -import cors from 'cors'; -// Check for OAuth flag -const useOAuth = process.argv.includes('--oauth'); -const strictOAuth = process.argv.includes('--oauth-strict'); -// Create an MCP server with implementation details -const getServer = () => { - const server = new McpServer({ - name: 'simple-streamable-http-server', - version: '1.0.0', - icons: [{ src: './mcp.svg', sizes: ['512x512'], mimeType: 'image/svg+xml' }], - websiteUrl: 'https://github.com/modelcontextprotocol/typescript-sdk' - }, { capabilities: { logging: {} } }); - // Register a simple tool that returns a greeting - server.registerTool('greet', { - title: 'Greeting Tool', // Display name for UI - description: 'A simple greeting tool', - inputSchema: { - name: z.string().describe('Name to greet') - } - }, async ({ name }) => { - return { - content: [ - { - type: 'text', - text: `Hello, ${name}!` - } - ] - }; - }); - // Register a tool that sends multiple greetings with notifications (with annotations) - server.tool('multi-greet', 'A tool that sends different greetings with delays between them', { - name: z.string().describe('Name to greet') - }, { - title: 'Multiple Greeting Tool', - readOnlyHint: true, - openWorldHint: false - }, async ({ name }, extra) => { - const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); - await server.sendLoggingMessage({ - level: 'debug', - data: `Starting multi-greet for ${name}` - }, extra.sessionId); - await sleep(1000); // Wait 1 second before first greeting - await server.sendLoggingMessage({ - level: 'info', - data: `Sending first greeting to ${name}` - }, extra.sessionId); - await sleep(1000); // Wait another second before second greeting - await server.sendLoggingMessage({ - level: 'info', - data: `Sending second greeting to ${name}` - }, extra.sessionId); - return { - content: [ - { - type: 'text', - text: `Good morning, ${name}!` - } - ] - }; - }); - // Register a tool that demonstrates form elicitation (user input collection with a schema) - // This creates a closure that captures the server instance - server.tool('collect-user-info', 'A tool that collects user information through form elicitation', { - infoType: z.enum(['contact', 'preferences', 'feedback']).describe('Type of information to collect') - }, async ({ infoType }) => { - let message; - let requestedSchema; - switch (infoType) { - case 'contact': - message = 'Please provide your contact information'; - requestedSchema = { - type: 'object', - properties: { - name: { - type: 'string', - title: 'Full Name', - description: 'Your full name' - }, - email: { - type: 'string', - title: 'Email Address', - description: 'Your email address', - format: 'email' - }, - phone: { - type: 'string', - title: 'Phone Number', - description: 'Your phone number (optional)' - } - }, - required: ['name', 'email'] - }; - break; - case 'preferences': - message = 'Please set your preferences'; - requestedSchema = { - type: 'object', - properties: { - theme: { - type: 'string', - title: 'Theme', - description: 'Choose your preferred theme', - enum: ['light', 'dark', 'auto'], - enumNames: ['Light', 'Dark', 'Auto'] - }, - notifications: { - type: 'boolean', - title: 'Enable Notifications', - description: 'Would you like to receive notifications?', - default: true - }, - frequency: { - type: 'string', - title: 'Notification Frequency', - description: 'How often would you like notifications?', - enum: ['daily', 'weekly', 'monthly'], - enumNames: ['Daily', 'Weekly', 'Monthly'] - } - }, - required: ['theme'] - }; - break; - case 'feedback': - message = 'Please provide your feedback'; - requestedSchema = { - type: 'object', - properties: { - rating: { - type: 'integer', - title: 'Rating', - description: 'Rate your experience (1-5)', - minimum: 1, - maximum: 5 - }, - comments: { - type: 'string', - title: 'Comments', - description: 'Additional comments (optional)', - maxLength: 500 - }, - recommend: { - type: 'boolean', - title: 'Would you recommend this?', - description: 'Would you recommend this to others?' - } - }, - required: ['rating', 'recommend'] - }; - break; - default: - throw new Error(`Unknown info type: ${infoType}`); - } - try { - // Use the underlying server instance to elicit input from the client - const result = await server.server.elicitInput({ - mode: 'form', - message, - requestedSchema - }); - if (result.action === 'accept') { - return { - content: [ - { - type: 'text', - text: `Thank you! Collected ${infoType} information: ${JSON.stringify(result.content, null, 2)}` - } - ] - }; - } - else if (result.action === 'decline') { - return { - content: [ - { - type: 'text', - text: `No information was collected. User declined ${infoType} information request.` - } - ] - }; - } - else { - return { - content: [ - { - type: 'text', - text: `Information collection was cancelled by the user.` - } - ] - }; - } - } - catch (error) { - return { - content: [ - { - type: 'text', - text: `Error collecting ${infoType} information: ${error}` - } - ] - }; - } - }); - // Register a simple prompt with title - server.registerPrompt('greeting-template', { - title: 'Greeting Template', // Display name for UI - description: 'A simple greeting prompt template', - argsSchema: { - name: z.string().describe('Name to include in greeting') - } - }, async ({ name }) => { - return { - messages: [ - { - role: 'user', - content: { - type: 'text', - text: `Please greet ${name} in a friendly manner.` - } - } - ] - }; - }); - // Register a tool specifically for testing resumability - server.tool('start-notification-stream', 'Starts sending periodic notifications for testing resumability', { - interval: z.number().describe('Interval in milliseconds between notifications').default(100), - count: z.number().describe('Number of notifications to send (0 for 100)').default(50) - }, async ({ interval, count }, extra) => { - const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); - let counter = 0; - while (count === 0 || counter < count) { - counter++; - try { - await server.sendLoggingMessage({ - level: 'info', - data: `Periodic notification #${counter} at ${new Date().toISOString()}` - }, extra.sessionId); - } - catch (error) { - console.error('Error sending notification:', error); - } - // Wait for the specified interval - await sleep(interval); - } - return { - content: [ - { - type: 'text', - text: `Started sending periodic notifications every ${interval}ms` - } - ] - }; - }); - // Create a simple resource at a fixed URI - server.registerResource('greeting-resource', 'https://example.com/greetings/default', { - title: 'Default Greeting', // Display name for UI - description: 'A simple greeting resource', - mimeType: 'text/plain' - }, async () => { - return { - contents: [ - { - uri: 'https://example.com/greetings/default', - text: 'Hello, world!' - } - ] - }; - }); - // Create additional resources for ResourceLink demonstration - server.registerResource('example-file-1', 'file:///example/file1.txt', { - title: 'Example File 1', - description: 'First example file for ResourceLink demonstration', - mimeType: 'text/plain' - }, async () => { - return { - contents: [ - { - uri: 'file:///example/file1.txt', - text: 'This is the content of file 1' - } - ] - }; - }); - server.registerResource('example-file-2', 'file:///example/file2.txt', { - title: 'Example File 2', - description: 'Second example file for ResourceLink demonstration', - mimeType: 'text/plain' - }, async () => { - return { - contents: [ - { - uri: 'file:///example/file2.txt', - text: 'This is the content of file 2' - } - ] - }; - }); - // Register a tool that returns ResourceLinks - server.registerTool('list-files', { - title: 'List Files with ResourceLinks', - description: 'Returns a list of files as ResourceLinks without embedding their content', - inputSchema: { - includeDescriptions: z.boolean().optional().describe('Whether to include descriptions in the resource links') - } - }, async ({ includeDescriptions = true }) => { - const resourceLinks = [ - { - type: 'resource_link', - uri: 'https://example.com/greetings/default', - name: 'Default Greeting', - mimeType: 'text/plain', - ...(includeDescriptions && { description: 'A simple greeting resource' }) - }, - { - type: 'resource_link', - uri: 'file:///example/file1.txt', - name: 'Example File 1', - mimeType: 'text/plain', - ...(includeDescriptions && { description: 'First example file for ResourceLink demonstration' }) - }, - { - type: 'resource_link', - uri: 'file:///example/file2.txt', - name: 'Example File 2', - mimeType: 'text/plain', - ...(includeDescriptions && { description: 'Second example file for ResourceLink demonstration' }) - } - ]; - return { - content: [ - { - type: 'text', - text: 'Here are the available files as resource links:' - }, - ...resourceLinks, - { - type: 'text', - text: '\nYou can read any of these resources using their URI.' - } - ] - }; - }); - return server; -}; -const MCP_PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; -const AUTH_PORT = process.env.MCP_AUTH_PORT ? parseInt(process.env.MCP_AUTH_PORT, 10) : 3001; -const app = express(); -app.use(express.json()); -// Allow CORS all domains, expose the Mcp-Session-Id header -app.use(cors({ - origin: '*', // Allow all origins - exposedHeaders: ['Mcp-Session-Id'] -})); -// Set up OAuth if enabled -let authMiddleware = null; -if (useOAuth) { - // Create auth middleware for MCP endpoints - const mcpServerUrl = new URL(`http://localhost:${MCP_PORT}/mcp`); - const authServerUrl = new URL(`http://localhost:${AUTH_PORT}`); - const oauthMetadata = setupAuthServer({ authServerUrl, mcpServerUrl, strictResource: strictOAuth }); - const tokenVerifier = { - verifyAccessToken: async (token) => { - const endpoint = oauthMetadata.introspection_endpoint; - if (!endpoint) { - throw new Error('No token verification endpoint available in metadata'); - } - const response = await fetch(endpoint, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: new URLSearchParams({ - token: token - }).toString() - }); - if (!response.ok) { - throw new Error(`Invalid or expired token: ${await response.text()}`); - } - const data = await response.json(); - if (strictOAuth) { - if (!data.aud) { - throw new Error(`Resource Indicator (RFC8707) missing`); - } - if (!checkResourceAllowed({ requestedResource: data.aud, configuredResource: mcpServerUrl })) { - throw new Error(`Expected resource indicator ${mcpServerUrl}, got: ${data.aud}`); - } - } - // Convert the response to AuthInfo format - return { - token, - clientId: data.client_id, - scopes: data.scope ? data.scope.split(' ') : [], - expiresAt: data.exp - }; - } - }; - // Add metadata routes to the main MCP server - app.use(mcpAuthMetadataRouter({ - oauthMetadata, - resourceServerUrl: mcpServerUrl, - scopesSupported: ['mcp:tools'], - resourceName: 'MCP Demo Server' - })); - authMiddleware = requireBearerAuth({ - verifier: tokenVerifier, - requiredScopes: [], - resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl) - }); -} -// Map to store transports by session ID -const transports = {}; -// MCP POST endpoint with optional auth -const mcpPostHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (sessionId) { - console.log(`Received MCP request for session: ${sessionId}`); - } - else { - console.log('Request body:', req.body); - } - if (useOAuth && req.auth) { - console.log('Authenticated user:', req.auth); - } - try { - let transport; - if (sessionId && transports[sessionId]) { - // Reuse existing transport - transport = transports[sessionId]; - } - else if (!sessionId && isInitializeRequest(req.body)) { - // New initialization request - const eventStore = new InMemoryEventStore(); - transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => randomUUID(), - eventStore, // Enable resumability - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - // This avoids race conditions where requests might come in before the session is stored - console.log(`Session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - } - }); - // Set up onclose handler to clean up transport when closed - transport.onclose = () => { - const sid = transport.sessionId; - if (sid && transports[sid]) { - console.log(`Transport closed for session ${sid}, removing from transports map`); - delete transports[sid]; - } - }; - // Connect the transport to the MCP server BEFORE handling the request - // so responses can flow back through the same transport - const server = getServer(); - await server.connect(transport); - await transport.handleRequest(req, res, req.body); - return; // Already handled - } - else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - // Handle the request with existing transport - no need to reconnect - // The existing transport is already connected to the server - await transport.handleRequest(req, res, req.body); - } - catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}; -// Set up routes with conditional auth middleware -if (useOAuth && authMiddleware) { - app.post('/mcp', authMiddleware, mcpPostHandler); -} -else { - app.post('/mcp', mcpPostHandler); -} -// Handle GET requests for SSE streams (using built-in support from StreamableHTTP) -const mcpGetHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - if (useOAuth && req.auth) { - console.log('Authenticated SSE connection from user:', req.auth); - } - // Check for Last-Event-ID header for resumability - const lastEventId = req.headers['last-event-id']; - if (lastEventId) { - console.log(`Client reconnecting with Last-Event-ID: ${lastEventId}`); - } - else { - console.log(`Establishing new SSE stream for session ${sessionId}`); - } - const transport = transports[sessionId]; - await transport.handleRequest(req, res); -}; -// Set up GET route with conditional auth middleware -if (useOAuth && authMiddleware) { - app.get('/mcp', authMiddleware, mcpGetHandler); -} -else { - app.get('/mcp', mcpGetHandler); -} -// Handle DELETE requests for session termination (according to MCP spec) -const mcpDeleteHandler = async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - console.log(`Received session termination request for session ${sessionId}`); - try { - const transport = transports[sessionId]; - await transport.handleRequest(req, res); - } - catch (error) { - console.error('Error handling session termination:', error); - if (!res.headersSent) { - res.status(500).send('Error processing session termination'); - } - } -}; -// Set up DELETE route with conditional auth middleware -if (useOAuth && authMiddleware) { - app.delete('/mcp', authMiddleware, mcpDeleteHandler); -} -else { - app.delete('/mcp', mcpDeleteHandler); -} -app.listen(MCP_PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`MCP Streamable HTTP Server listening on port ${MCP_PORT}`); -}); -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - // Close all active transports to properly clean up resources - for (const sessionId in transports) { - try { - console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId].close(); - delete transports[sessionId]; - } - catch (error) { - console.error(`Error closing transport for session ${sessionId}:`, error); - } - } - console.log('Server shutdown complete'); - process.exit(0); -}); -//# sourceMappingURL=simpleStreamableHttp.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/simpleStreamableHttp.js.map b/dist/esm/examples/server/simpleStreamableHttp.js.map deleted file mode 100644 index 56b80e5293..0000000000 --- a/dist/esm/examples/server/simpleStreamableHttp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"simpleStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/simpleStreamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,OAA8B,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,oCAAoC,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAC1G,OAAO,EAAE,iBAAiB,EAAE,MAAM,4CAA4C,CAAC;AAC/E,OAAO,EAGH,mBAAmB,EAItB,MAAM,gBAAgB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BAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IAEvC,6DAA6D;IAC7D,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACjC,IAAI,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,iCAAiC,SAAS,EAAE,CAAC,CAAC;YAC1D,MAAM,UAAU,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,CAAC;YACpC,OAAO,UAAU,CAAC,SAAS,CAAC,CAAC;QACjC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,OAAO,CAAC,KAAK,CAAC,uCAAuC,SAAS,GAAG,EAAE,KAAK,CAAC,CAAC;QAC9E,CAAC;IACL,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts b/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts deleted file mode 100644 index c536d0c80e..0000000000 --- a/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=sseAndStreamableHttpCompatibleServer.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map b/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map deleted file mode 100644 index fb982c84a6..0000000000 --- a/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"sseAndStreamableHttpCompatibleServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/sseAndStreamableHttpCompatibleServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js b/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js deleted file mode 100644 index 3385fac2db..0000000000 --- a/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js +++ /dev/null @@ -1,235 +0,0 @@ -import express from 'express'; -import { randomUUID } from 'node:crypto'; -import { McpServer } from '../../server/mcp.js'; -import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; -import { SSEServerTransport } from '../../server/sse.js'; -import * as z from 'zod/v4'; -import { isInitializeRequest } from '../../types.js'; -import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; -import cors from 'cors'; -/** - * This example server demonstrates backwards compatibility with both: - * 1. The deprecated HTTP+SSE transport (protocol version 2024-11-05) - * 2. The Streamable HTTP transport (protocol version 2025-03-26) - * - * It maintains a single MCP server instance but exposes two transport options: - * - /mcp: The new Streamable HTTP endpoint (supports GET/POST/DELETE) - * - /sse: The deprecated SSE endpoint for older clients (GET to establish stream) - * - /messages: The deprecated POST endpoint for older clients (POST to send messages) - */ -const getServer = () => { - const server = new McpServer({ - name: 'backwards-compatible-server', - version: '1.0.0' - }, { capabilities: { logging: {} } }); - // Register a simple tool that sends notifications over time - server.tool('start-notification-stream', 'Starts sending periodic notifications for testing resumability', { - interval: z.number().describe('Interval in milliseconds between notifications').default(100), - count: z.number().describe('Number of notifications to send (0 for 100)').default(50) - }, async ({ interval, count }, extra) => { - const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms)); - let counter = 0; - while (count === 0 || counter < count) { - counter++; - try { - await server.sendLoggingMessage({ - level: 'info', - data: `Periodic notification #${counter} at ${new Date().toISOString()}` - }, extra.sessionId); - } - catch (error) { - console.error('Error sending notification:', error); - } - // Wait for the specified interval - await sleep(interval); - } - return { - content: [ - { - type: 'text', - text: `Started sending periodic notifications every ${interval}ms` - } - ] - }; - }); - return server; -}; -// Create Express application -const app = express(); -app.use(express.json()); -// Configure CORS to expose Mcp-Session-Id header for browser-based clients -app.use(cors({ - origin: '*', // Allow all origins - adjust as needed for production - exposedHeaders: ['Mcp-Session-Id'] -})); -// Store transports by session ID -const transports = {}; -//============================================================================= -// STREAMABLE HTTP TRANSPORT (PROTOCOL VERSION 2025-03-26) -//============================================================================= -// Handle all MCP Streamable HTTP requests (GET, POST, DELETE) on a single endpoint -app.all('/mcp', async (req, res) => { - console.log(`Received ${req.method} request to /mcp`); - try { - // Check for existing session ID - const sessionId = req.headers['mcp-session-id']; - let transport; - if (sessionId && transports[sessionId]) { - // Check if the transport is of the correct type - const existingTransport = transports[sessionId]; - if (existingTransport instanceof StreamableHTTPServerTransport) { - // Reuse existing transport - transport = existingTransport; - } - else { - // Transport exists but is not a StreamableHTTPServerTransport (could be SSEServerTransport) - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: Session exists but uses a different transport protocol' - }, - id: null - }); - return; - } - } - else if (!sessionId && req.method === 'POST' && isInitializeRequest(req.body)) { - const eventStore = new InMemoryEventStore(); - transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => randomUUID(), - eventStore, // Enable resumability - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - console.log(`StreamableHTTP session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - } - }); - // Set up onclose handler to clean up transport when closed - transport.onclose = () => { - const sid = transport.sessionId; - if (sid && transports[sid]) { - console.log(`Transport closed for session ${sid}, removing from transports map`); - delete transports[sid]; - } - }; - // Connect the transport to the MCP server - const server = getServer(); - await server.connect(transport); - } - else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - // Handle the request with the transport - await transport.handleRequest(req, res, req.body); - } - catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}); -//============================================================================= -// DEPRECATED HTTP+SSE TRANSPORT (PROTOCOL VERSION 2024-11-05) -//============================================================================= -app.get('/sse', async (req, res) => { - console.log('Received GET request to /sse (deprecated SSE transport)'); - const transport = new SSEServerTransport('/messages', res); - transports[transport.sessionId] = transport; - res.on('close', () => { - delete transports[transport.sessionId]; - }); - const server = getServer(); - await server.connect(transport); -}); -app.post('/messages', async (req, res) => { - const sessionId = req.query.sessionId; - let transport; - const existingTransport = transports[sessionId]; - if (existingTransport instanceof SSEServerTransport) { - // Reuse existing transport - transport = existingTransport; - } - else { - // Transport exists but is not a SSEServerTransport (could be StreamableHTTPServerTransport) - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: Session exists but uses a different transport protocol' - }, - id: null - }); - return; - } - if (transport) { - await transport.handlePostMessage(req, res, req.body); - } - else { - res.status(400).send('No transport found for sessionId'); - } -}); -// Start the server -const PORT = 3000; -app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`Backwards compatible MCP server listening on port ${PORT}`); - console.log(` -============================================== -SUPPORTED TRANSPORT OPTIONS: - -1. Streamable Http(Protocol version: 2025-03-26) - Endpoint: /mcp - Methods: GET, POST, DELETE - Usage: - - Initialize with POST to /mcp - - Establish SSE stream with GET to /mcp - - Send requests with POST to /mcp - - Terminate session with DELETE to /mcp - -2. Http + SSE (Protocol version: 2024-11-05) - Endpoints: /sse (GET) and /messages (POST) - Usage: - - Establish SSE stream with GET to /sse - - Send requests with POST to /messages?sessionId= -============================================== -`); -}); -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - // Close all active transports to properly clean up resources - for (const sessionId in transports) { - try { - console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId].close(); - delete transports[sessionId]; - } - catch (error) { - console.error(`Error closing transport for session ${sessionId}:`, error); - } - } - console.log('Server shutdown complete'); - process.exit(0); -}); -//# sourceMappingURL=sseAndStreamableHttpCompatibleServer.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js.map b/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js.map deleted file mode 100644 index f854fbcd6b..0000000000 --- a/dist/esm/examples/server/sseAndStreamableHttpCompatibleServer.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"sseAndStreamableHttpCompatibleServer.js","sourceRoot":"","sources":["../../../../src/examples/server/sseAndStreamableHttpCompatibleServer.ts"],"names":[],"mappings":"AAAA,OAAO,OAA8B,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AACzD,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAkB,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,IAAI,MAAM,MAAM,CAAC;AAExB;;;;;;;;;GASG;AAEH,MAAM,SAAS,GAAG,GAAG,EAAE;IACnB,MAAM,MAAM,GAAG,IAAI,SAAS,CACxB;QACI,IAAI,EAAE,6BAA6B;QACnC,OAAO,EAAE,OAAO;KACnB,EACD,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,EAAE,CACpC,CAAC;IAEF,4DAA4D;IAC5D,MAAM,CAAC,IAAI,CACP,2BAA2B,EAC3B,gEAAgE,EAChE;QACI,QAAQ,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,gDAAgD,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC;QAC5F,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,6CAA6C,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC;KACxF,EACD,KAA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C;IACD,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;IACxC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts b/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts deleted file mode 100644 index 4df17831b7..0000000000 --- a/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=standaloneSseWithGetStreamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map b/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map deleted file mode 100644 index df60dc51b0..0000000000 --- a/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"standaloneSseWithGetStreamableHttp.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/standaloneSseWithGetStreamableHttp.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js b/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js deleted file mode 100644 index b67302c968..0000000000 --- a/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js +++ /dev/null @@ -1,111 +0,0 @@ -import express from 'express'; -import { randomUUID } from 'node:crypto'; -import { McpServer } from '../../server/mcp.js'; -import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; -import { isInitializeRequest } from '../../types.js'; -// Create an MCP server with implementation details -const server = new McpServer({ - name: 'resource-list-changed-notification-server', - version: '1.0.0' -}); -// Store transports by session ID to send notifications -const transports = {}; -const addResource = (name, content) => { - const uri = `https://mcp-example.com/dynamic/${encodeURIComponent(name)}`; - server.resource(name, uri, { mimeType: 'text/plain', description: `Dynamic resource: ${name}` }, async () => { - return { - contents: [{ uri, text: content }] - }; - }); -}; -addResource('example-resource', 'Initial content for example-resource'); -const resourceChangeInterval = setInterval(() => { - const name = randomUUID(); - addResource(name, `Content for ${name}`); -}, 5000); // Change resources every 5 seconds for testing -const app = express(); -app.use(express.json()); -app.post('/mcp', async (req, res) => { - console.log('Received MCP request:', req.body); - try { - // Check for existing session ID - const sessionId = req.headers['mcp-session-id']; - let transport; - if (sessionId && transports[sessionId]) { - // Reuse existing transport - transport = transports[sessionId]; - } - else if (!sessionId && isInitializeRequest(req.body)) { - // New initialization request - transport = new StreamableHTTPServerTransport({ - sessionIdGenerator: () => randomUUID(), - onsessioninitialized: sessionId => { - // Store the transport by session ID when session is initialized - // This avoids race conditions where requests might come in before the session is stored - console.log(`Session initialized with ID: ${sessionId}`); - transports[sessionId] = transport; - } - }); - // Connect the transport to the MCP server - await server.connect(transport); - // Handle the request - the onsessioninitialized callback will store the transport - await transport.handleRequest(req, res, req.body); - return; // Already handled - } - else { - // Invalid request - no session ID or not initialization request - res.status(400).json({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: No valid session ID provided' - }, - id: null - }); - return; - } - // Handle the request with existing transport - await transport.handleRequest(req, res, req.body); - } - catch (error) { - console.error('Error handling MCP request:', error); - if (!res.headersSent) { - res.status(500).json({ - jsonrpc: '2.0', - error: { - code: -32603, - message: 'Internal server error' - }, - id: null - }); - } - } -}); -// Handle GET requests for SSE streams (now using built-in support from StreamableHTTP) -app.get('/mcp', async (req, res) => { - const sessionId = req.headers['mcp-session-id']; - if (!sessionId || !transports[sessionId]) { - res.status(400).send('Invalid or missing session ID'); - return; - } - console.log(`Establishing SSE stream for session ${sessionId}`); - const transport = transports[sessionId]; - await transport.handleRequest(req, res); -}); -// Start the server -const PORT = 3000; -app.listen(PORT, error => { - if (error) { - console.error('Failed to start server:', error); - process.exit(1); - } - console.log(`Server listening on port ${PORT}`); -}); -// Handle server shutdown -process.on('SIGINT', async () => { - console.log('Shutting down server...'); - clearInterval(resourceChangeInterval); - await server.close(); - process.exit(0); -}); -//# sourceMappingURL=standaloneSseWithGetStreamableHttp.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js.map b/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js.map deleted file mode 100644 index 8caa419a85..0000000000 --- a/dist/esm/examples/server/standaloneSseWithGetStreamableHttp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"standaloneSseWithGetStreamableHttp.js","sourceRoot":"","sources":["../../../../src/examples/server/standaloneSseWithGetStreamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,OAA8B,MAAM,SAAS,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,mBAAmB,EAAsB,MAAM,gBAAgB,CAAC;AAEzE,mDAAmD;AACnD,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC;IACzB,IAAI,EAAE,2CAA2C;IACjD,OAAO,EAAE,OAAO;CACnB,CAAC,CAAC;AAEH,uDAAuD;AACvD,MAAM,UAAU,GAA2D,EAAE,CAAC;AAE9E,MAAM,WAAW,GAAG,CAAC,IAAY,EAAE,OAAe,EAAE,EAAE;IAClD,MAAM,GAAG,GAAG,mCAAmC,kBAAkB,CAAC,IAAI,CAAC,EAAE,CAAC;IAC1E,MAAM,CAAC,QAAQ,CACX,IAAI,EACJ,GAAG,EACH,EAAE,QAAQ,EAAE,YAAY,EAAE,WAAW,EAAE,qBAAqB,IAAI,EAAE,EAAE,EACpE,KAAK,IAAiC,EAAE;QACpC,OAAO;YACH,QAAQ,EAAE,CAAC,EAAE,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;SACrC,CAAC;IACN,CAAC,CACJ,CAAC;AACN,CAAC,CAAC;AAEF,WAAW,CAAC,kBAAkB,EAAE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CAAC;QACtD,OAAO;IACX,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,uCAAuC,SAAS,EAAE,CAAC,CAAC;IAChE,MAAM,SAAS,GAAG,UAAU,CAAC,SAAS,CAAC,CAAC;IACxC,MAAM,SAAS,CAAC,aAAa,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AAC5C,CAAC,CAAC,CAAC;AAEH,mBAAmB;AACnB,MAAM,IAAI,GAAG,IAAI,CAAC;AAClB,GAAG,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,EAAE;IACrB,IAAI,KAAK,EAAE,CAAC;QACR,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,KAAK,CAAC,CAAC;QAChD,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACpB,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,4BAA4B,IAAI,EAAE,CAAC,CAAC;AACpD,CAAC,CAAC,CAAC;AAEH,yBAAyB;AACzB,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,IAAI,EAAE;IAC5B,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;IACvC,aAAa,CAAC,sBAAsB,CAAC,CAAC;IACtC,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;IACrB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/server/toolWithSampleServer.d.ts b/dist/esm/examples/server/toolWithSampleServer.d.ts deleted file mode 100644 index acc24b6a53..0000000000 --- a/dist/esm/examples/server/toolWithSampleServer.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=toolWithSampleServer.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/server/toolWithSampleServer.d.ts.map b/dist/esm/examples/server/toolWithSampleServer.d.ts.map deleted file mode 100644 index bd0cebcf19..0000000000 --- a/dist/esm/examples/server/toolWithSampleServer.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"toolWithSampleServer.d.ts","sourceRoot":"","sources":["../../../../src/examples/server/toolWithSampleServer.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/examples/server/toolWithSampleServer.js b/dist/esm/examples/server/toolWithSampleServer.js deleted file mode 100644 index 326a288cd5..0000000000 --- a/dist/esm/examples/server/toolWithSampleServer.js +++ /dev/null @@ -1,46 +0,0 @@ -// Run with: npx tsx src/examples/server/toolWithSampleServer.ts -import { McpServer } from '../../server/mcp.js'; -import { StdioServerTransport } from '../../server/stdio.js'; -import * as z from 'zod/v4'; -const mcpServer = new McpServer({ - name: 'tools-with-sample-server', - version: '1.0.0' -}); -// Tool that uses LLM sampling to summarize any text -mcpServer.registerTool('summarize', { - description: 'Summarize any text using an LLM', - inputSchema: { - text: z.string().describe('Text to summarize') - } -}, async ({ text }) => { - // Call the LLM through MCP sampling - const response = await mcpServer.server.createMessage({ - messages: [ - { - role: 'user', - content: { - type: 'text', - text: `Please summarize the following text concisely:\n\n${text}` - } - } - ], - maxTokens: 500 - }); - const contents = Array.isArray(response.content) ? response.content : [response.content]; - return { - content: contents.map(content => ({ - type: 'text', - text: content.type === 'text' ? content.text : 'Unable to generate summary' - })) - }; -}); -async function main() { - const transport = new StdioServerTransport(); - await mcpServer.connect(transport); - console.log('MCP server is running...'); -} -main().catch(error => { - console.error('Server error:', error); - process.exit(1); -}); -//# sourceMappingURL=toolWithSampleServer.js.map \ No newline at end of file diff --git a/dist/esm/examples/server/toolWithSampleServer.js.map b/dist/esm/examples/server/toolWithSampleServer.js.map deleted file mode 100644 index f4fb4337eb..0000000000 --- a/dist/esm/examples/server/toolWithSampleServer.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"toolWithSampleServer.js","sourceRoot":"","sources":["../../../../src/examples/server/toolWithSampleServer.ts"],"names":[],"mappings":"AAAA,gEAAgE;AAEhE,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CA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;IAC7C,MAAM,SAAS,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IACnC,OAAO,CAAC,GAAG,CAAC,0BAA0B,CAAC,CAAC;AAC5C,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE;IACjB,OAAO,CAAC,KAAK,CAAC,eAAe,EAAE,KAAK,CAAC,CAAC;IACtC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/examples/shared/inMemoryEventStore.d.ts b/dist/esm/examples/shared/inMemoryEventStore.d.ts deleted file mode 100644 index 26ff38cf93..0000000000 --- a/dist/esm/examples/shared/inMemoryEventStore.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { JSONRPCMessage } from '../../types.js'; -import { EventStore } from '../../server/streamableHttp.js'; -/** - * Simple in-memory implementation of the EventStore interface for resumability - * This is primarily intended for examples and testing, not for production use - * where a persistent storage solution would be more appropriate. - */ -export declare class InMemoryEventStore implements EventStore { - private events; - /** - * Generates a unique event ID for a given stream ID - */ - private generateEventId; - /** - * Extracts the stream ID from an event ID - */ - private getStreamIdFromEventId; - /** - * Stores an event with a generated event ID - * Implements EventStore.storeEvent - */ - storeEvent(streamId: string, message: JSONRPCMessage): Promise; - /** - * Replays events that occurred after a specific event ID - * Implements EventStore.replayEventsAfter - */ - replayEventsAfter(lastEventId: string, { send }: { - send: (eventId: string, message: JSONRPCMessage) => Promise; - }): Promise; -} -//# sourceMappingURL=inMemoryEventStore.d.ts.map \ No newline at end of file diff --git a/dist/esm/examples/shared/inMemoryEventStore.d.ts.map b/dist/esm/examples/shared/inMemoryEventStore.d.ts.map deleted file mode 100644 index a67ee6cd17..0000000000 --- a/dist/esm/examples/shared/inMemoryEventStore.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inMemoryEventStore.d.ts","sourceRoot":"","sources":["../../../../src/examples/shared/inMemoryEventStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,gCAAgC,CAAC;AAE5D;;;;GAIG;AACH,qBAAa,kBAAmB,YAAW,UAAU;IACjD,OAAO,CAAC,MAAM,CAAyE;IAEvF;;OAEG;IACH,OAAO,CAAC,eAAe;IAIvB;;OAEG;IACH,OAAO,CAAC,sBAAsB;IAK9B;;;OAGG;IACG,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,MAAM,CAAC;IAM5E;;;OAGG;IACG,iBAAiB,CACnB,WAAW,EAAE,MAAM,EACnB,EAAE,IAAI,EAAE,EAAE;QAAE,IAAI,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;KAAE,GAChF,OAAO,CAAC,MAAM,CAAC;CAkCrB"} \ No newline at end of file diff --git a/dist/esm/examples/shared/inMemoryEventStore.js b/dist/esm/examples/shared/inMemoryEventStore.js deleted file mode 100644 index 35f6dbb7c3..0000000000 --- a/dist/esm/examples/shared/inMemoryEventStore.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Simple in-memory implementation of the EventStore interface for resumability - * This is primarily intended for examples and testing, not for production use - * where a persistent storage solution would be more appropriate. - */ -export class InMemoryEventStore { - constructor() { - this.events = new Map(); - } - /** - * Generates a unique event ID for a given stream ID - */ - generateEventId(streamId) { - return `${streamId}_${Date.now()}_${Math.random().toString(36).substring(2, 10)}`; - } - /** - * Extracts the stream ID from an event ID - */ - getStreamIdFromEventId(eventId) { - const parts = eventId.split('_'); - return parts.length > 0 ? parts[0] : ''; - } - /** - * Stores an event with a generated event ID - * Implements EventStore.storeEvent - */ - async storeEvent(streamId, message) { - const eventId = this.generateEventId(streamId); - this.events.set(eventId, { streamId, message }); - return eventId; - } - /** - * Replays events that occurred after a specific event ID - * Implements EventStore.replayEventsAfter - */ - async replayEventsAfter(lastEventId, { send }) { - if (!lastEventId || !this.events.has(lastEventId)) { - return ''; - } - // Extract the stream ID from the event ID - const streamId = this.getStreamIdFromEventId(lastEventId); - if (!streamId) { - return ''; - } - let foundLastEvent = false; - // Sort events by eventId for chronological ordering - const sortedEvents = [...this.events.entries()].sort((a, b) => a[0].localeCompare(b[0])); - for (const [eventId, { streamId: eventStreamId, message }] of sortedEvents) { - // Only include events from the same stream - if (eventStreamId !== streamId) { - continue; - } - // Start sending events after we find the lastEventId - if (eventId === lastEventId) { - foundLastEvent = true; - continue; - } - if (foundLastEvent) { - await send(eventId, message); - } - } - return streamId; - } -} -//# sourceMappingURL=inMemoryEventStore.js.map \ No newline at end of file diff --git a/dist/esm/examples/shared/inMemoryEventStore.js.map b/dist/esm/examples/shared/inMemoryEventStore.js.map deleted file mode 100644 index b9e6af66aa..0000000000 --- a/dist/esm/examples/shared/inMemoryEventStore.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inMemoryEventStore.js","sourceRoot":"","sources":["../../../../src/examples/shared/inMemoryEventStore.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,MAAM,OAAO,kBAAkB;IAA/B;QACY,WAAM,GAA+D,IAAI,GAAG,EAAE,CAAC;IAoE3F,CAAC;IAlEG;;OAEG;IACK,eAAe,CAAC,QAAgB;QACpC,OAAO,GAAG,QAAQ,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC;IACtF,CAAC;IAED;;OAEG;IACK,sBAAsB,CAAC,OAAe;QAC1C,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACjC,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,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AAC;YAED,IAAI,cAAc,EAAE,CAAC;gBACjB,MAAM,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACjC,CAAC;QACL,CAAC;QACD,OAAO,QAAQ,CAAC;IACpB,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/inMemory.d.ts b/dist/esm/inMemory.d.ts deleted file mode 100644 index 32a931a863..0000000000 --- a/dist/esm/inMemory.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { Transport } from './shared/transport.js'; -import { JSONRPCMessage, RequestId } from './types.js'; -import { AuthInfo } from './server/auth/types.js'; -/** - * In-memory transport for creating clients and servers that talk to each other within the same process. - */ -export declare class InMemoryTransport implements Transport { - private _otherTransport?; - private _messageQueue; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage, extra?: { - authInfo?: AuthInfo; - }) => void; - sessionId?: string; - /** - * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a Client and one to a Server. - */ - static createLinkedPair(): [InMemoryTransport, InMemoryTransport]; - start(): Promise; - close(): Promise; - /** - * Sends a message with optional auth info. - * This is useful for testing authentication scenarios. - */ - send(message: JSONRPCMessage, options?: { - relatedRequestId?: RequestId; - authInfo?: AuthInfo; - }): Promise; -} -//# sourceMappingURL=inMemory.d.ts.map \ No newline at end of file diff --git a/dist/esm/inMemory.d.ts.map b/dist/esm/inMemory.d.ts.map deleted file mode 100644 index 46bc74be17..0000000000 --- a/dist/esm/inMemory.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inMemory.d.ts","sourceRoot":"","sources":["../../src/inMemory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AACvD,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAOlD;;GAEG;AACH,qBAAa,iBAAkB,YAAW,SAAS;IAC/C,OAAO,CAAC,eAAe,CAAC,CAAoB;IAC5C,OAAO,CAAC,aAAa,CAAuB;IAE5C,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,KAAK,CAAC,EAAE;QAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,KAAK,IAAI,CAAC;IAC/E,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;OAEG;IACH,MAAM,CAAC,gBAAgB,IAAI,CAAC,iBAAiB,EAAE,iBAAiB,CAAC;IAQ3D,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAQtB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAO5B;;;OAGG;IACG,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,SAAS,CAAC;QAAC,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAWtH"} \ No newline at end of file diff --git a/dist/esm/inMemory.js b/dist/esm/inMemory.js deleted file mode 100644 index 930bbff511..0000000000 --- a/dist/esm/inMemory.js +++ /dev/null @@ -1,49 +0,0 @@ -/** - * In-memory transport for creating clients and servers that talk to each other within the same process. - */ -export class InMemoryTransport { - constructor() { - this._messageQueue = []; - } - /** - * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a Client and one to a Server. - */ - static createLinkedPair() { - const clientTransport = new InMemoryTransport(); - const serverTransport = new InMemoryTransport(); - clientTransport._otherTransport = serverTransport; - serverTransport._otherTransport = clientTransport; - return [clientTransport, serverTransport]; - } - async start() { - var _a; - // Process any messages that were queued before start was called - while (this._messageQueue.length > 0) { - const queuedMessage = this._messageQueue.shift(); - (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, queuedMessage.message, queuedMessage.extra); - } - } - async close() { - var _a; - const other = this._otherTransport; - this._otherTransport = undefined; - await (other === null || other === void 0 ? void 0 : other.close()); - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - } - /** - * Sends a message with optional auth info. - * This is useful for testing authentication scenarios. - */ - async send(message, options) { - if (!this._otherTransport) { - throw new Error('Not connected'); - } - if (this._otherTransport.onmessage) { - this._otherTransport.onmessage(message, { authInfo: options === null || options === void 0 ? void 0 : options.authInfo }); - } - else { - this._otherTransport._messageQueue.push({ message, extra: { authInfo: options === null || options === void 0 ? void 0 : options.authInfo } }); - } - } -} -//# sourceMappingURL=inMemory.js.map \ No newline at end of file diff --git a/dist/esm/inMemory.js.map b/dist/esm/inMemory.js.map deleted file mode 100644 index f001ce163b..0000000000 --- a/dist/esm/inMemory.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"inMemory.js","sourceRoot":"","sources":["../../src/inMemory.ts"],"names":[],"mappings":"AASA;;GAEG;AACH,MAAM,OAAO,iBAAiB;IAA9B;QAEY,kBAAa,GAAoB,EAAE,CAAC;IAgDhD,CAAC;IAzCG;;OAEG;IACH,MAAM,CAAC,gBAAgB;QACnB,MAAM,eAAe,GAAG,IAAI,iBAAiB,EAAE,CAAC;QAChD,MAAM,eAAe,GAAG,IAAI,iBAAiB,EAAE,CAAC;QAChD,eAAe,CAAC,eAAe,GAAG,eAAe,CAAC;QAClD,eAAe,CAAC,eAAe,GAAG,eAAe,CAAC;QAClD,OAAO,CAAC,eAAe,EAAE,eAAe,CAAC,CAAC;IAC9C,CAAC;IAED,KAAK,CAAC,KAAK;;QACP,gEAAgE;QAChE,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACnC,MAAM,aAAa,GAAG,IAAI,CAAC,aAAa,CAAC,KAAK,EAAG,CAAC;YAClD,MAAA,IAAI,CAAC,SAAS,qDAAG,aAAa,CAAC,OAAO,EAAE,aAAa,CAAC,KAAK,CAAC,CAAC;QACjE,CAAC;IACL,CAAC;IAED,KAAK,CAAC,KAAK;;QACP,MAAM,KAAK,GAAG,IAAI,CAAC,eAAe,CAAC;QACnC,IAAI,CAAC,eAAe,GAAG,SAAS,CAAC;QACjC,MAAM,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,KAAK,EAAE,CAAA,CAAC;QACrB,MAAA,IAAI,CAAC,OAAO,oDAAI,CAAC;IACrB,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,IAAI,CAAC,OAAuB,EAAE,OAA+D;QAC/F,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,CAAC;YACxB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;QACrC,CAAC;QAED,IAAI,IAAI,CAAC,eAAe,CAAC,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,EAAE,CAAC,CAAC;QAC7E,CAAC;aAAM,CAAC;YACJ,IAAI,CAAC,eAAe,CAAC,aAAa,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,EAAE,EAAE,CAAC,CAAC;QACjG,CAAC;IACL,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/package.json b/dist/esm/package.json deleted file mode 100644 index 6990891ff3..0000000000 --- a/dist/esm/package.json +++ /dev/null @@ -1 +0,0 @@ -{"type": "module"} diff --git a/dist/esm/server/auth/clients.d.ts b/dist/esm/server/auth/clients.d.ts deleted file mode 100644 index be6899a198..0000000000 --- a/dist/esm/server/auth/clients.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { OAuthClientInformationFull } from '../../shared/auth.js'; -/** - * Stores information about registered OAuth clients for this server. - */ -export interface OAuthRegisteredClientsStore { - /** - * Returns information about a registered client, based on its ID. - */ - getClient(clientId: string): OAuthClientInformationFull | undefined | Promise; - /** - * Registers a new client with the server. The client ID and secret will be automatically generated by the library. A modified version of the client information can be returned to reflect specific values enforced by the server. - * - * NOTE: Implementations should NOT delete expired client secrets in-place. Auth middleware provided by this library will automatically check the `client_secret_expires_at` field and reject requests with expired secrets. Any custom logic for authenticating clients should check the `client_secret_expires_at` field as well. - * - * If unimplemented, dynamic client registration is unsupported. - */ - registerClient?(client: Omit): OAuthClientInformationFull | Promise; -} -//# sourceMappingURL=clients.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/clients.d.ts.map b/dist/esm/server/auth/clients.d.ts.map deleted file mode 100644 index ab3851db35..0000000000 --- a/dist/esm/server/auth/clients.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"clients.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/clients.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAElE;;GAEG;AACH,MAAM,WAAW,2BAA2B;IACxC;;OAEG;IACH,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,0BAA0B,GAAG,SAAS,GAAG,OAAO,CAAC,0BAA0B,GAAG,SAAS,CAAC,CAAC;IAEtH;;;;;;OAMG;IACH,cAAc,CAAC,CACX,MAAM,EAAE,IAAI,CAAC,0BAA0B,EAAE,WAAW,GAAG,qBAAqB,CAAC,GAC9E,0BAA0B,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAAC;CACvE"} \ No newline at end of file diff --git a/dist/esm/server/auth/clients.js b/dist/esm/server/auth/clients.js deleted file mode 100644 index 6181a5709d..0000000000 --- a/dist/esm/server/auth/clients.js +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=clients.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/clients.js.map b/dist/esm/server/auth/clients.js.map deleted file mode 100644 index 0210104422..0000000000 --- a/dist/esm/server/auth/clients.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"clients.js","sourceRoot":"","sources":["../../../../src/server/auth/clients.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/server/auth/errors.d.ts b/dist/esm/server/auth/errors.d.ts deleted file mode 100644 index b487760fc2..0000000000 --- a/dist/esm/server/auth/errors.d.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { OAuthErrorResponse } from '../../shared/auth.js'; -/** - * Base class for all OAuth errors - */ -export declare class OAuthError extends Error { - readonly errorUri?: string | undefined; - static errorCode: string; - constructor(message: string, errorUri?: string | undefined); - /** - * Converts the error to a standard OAuth error response object - */ - toResponseObject(): OAuthErrorResponse; - get errorCode(): string; -} -/** - * Invalid request error - The request is missing a required parameter, - * includes an invalid parameter value, includes a parameter more than once, - * or is otherwise malformed. - */ -export declare class InvalidRequestError extends OAuthError { - static errorCode: string; -} -/** - * Invalid client error - Client authentication failed (e.g., unknown client, no client - * authentication included, or unsupported authentication method). - */ -export declare class InvalidClientError extends OAuthError { - static errorCode: string; -} -/** - * Invalid grant error - The provided authorization grant or refresh token is - * invalid, expired, revoked, does not match the redirection URI used in the - * authorization request, or was issued to another client. - */ -export declare class InvalidGrantError extends OAuthError { - static errorCode: string; -} -/** - * Unauthorized client error - The authenticated client is not authorized to use - * this authorization grant type. - */ -export declare class UnauthorizedClientError extends OAuthError { - static errorCode: string; -} -/** - * Unsupported grant type error - The authorization grant type is not supported - * by the authorization server. - */ -export declare class UnsupportedGrantTypeError extends OAuthError { - static errorCode: string; -} -/** - * Invalid scope error - The requested scope is invalid, unknown, malformed, or - * exceeds the scope granted by the resource owner. - */ -export declare class InvalidScopeError extends OAuthError { - static errorCode: string; -} -/** - * Access denied error - The resource owner or authorization server denied the request. - */ -export declare class AccessDeniedError extends OAuthError { - static errorCode: string; -} -/** - * Server error - The authorization server encountered an unexpected condition - * that prevented it from fulfilling the request. - */ -export declare class ServerError extends OAuthError { - static errorCode: string; -} -/** - * Temporarily unavailable error - The authorization server is currently unable to - * handle the request due to a temporary overloading or maintenance of the server. - */ -export declare class TemporarilyUnavailableError extends OAuthError { - static errorCode: string; -} -/** - * Unsupported response type error - The authorization server does not support - * obtaining an authorization code using this method. - */ -export declare class UnsupportedResponseTypeError extends OAuthError { - static errorCode: string; -} -/** - * Unsupported token type error - The authorization server does not support - * the requested token type. - */ -export declare class UnsupportedTokenTypeError extends OAuthError { - static errorCode: string; -} -/** - * Invalid token error - The access token provided is expired, revoked, malformed, - * or invalid for other reasons. - */ -export declare class InvalidTokenError extends OAuthError { - static errorCode: string; -} -/** - * Method not allowed error - The HTTP method used is not allowed for this endpoint. - * (Custom, non-standard error) - */ -export declare class MethodNotAllowedError extends OAuthError { - static errorCode: string; -} -/** - * Too many requests error - Rate limit exceeded. - * (Custom, non-standard error based on RFC 6585) - */ -export declare class TooManyRequestsError extends OAuthError { - static errorCode: string; -} -/** - * Invalid client metadata error - The client metadata is invalid. - * (Custom error for dynamic client registration - RFC 7591) - */ -export declare class InvalidClientMetadataError extends OAuthError { - static errorCode: string; -} -/** - * Insufficient scope error - The request requires higher privileges than provided by the access token. - */ -export declare class InsufficientScopeError extends OAuthError { - static errorCode: string; -} -/** - * A utility class for defining one-off error codes - */ -export declare class CustomOAuthError extends OAuthError { - private readonly customErrorCode; - constructor(customErrorCode: string, message: string, errorUri?: string); - get errorCode(): string; -} -/** - * A full list of all OAuthErrors, enabling parsing from error responses - */ -export declare const OAUTH_ERRORS: { - readonly [x: string]: typeof InvalidRequestError; -}; -//# sourceMappingURL=errors.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/errors.d.ts.map b/dist/esm/server/auth/errors.d.ts.map deleted file mode 100644 index 5141085c26..0000000000 --- a/dist/esm/server/auth/errors.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAE1D;;G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,UAAU;IAC7C,MAAM,CAAC,SAAS,SAAmB;CACtC;AAED;;;GAGG;AACH,qBAAa,qBAAsB,SAAQ,UAAU;IACjD,MAAM,CAAC,SAAS,SAAwB;CAC3C;AAED;;;GAGG;AACH,qBAAa,oBAAqB,SAAQ,UAAU;IAChD,MAAM,CAAC,SAAS,SAAuB;CAC1C;AAED;;;GAGG;AACH,qBAAa,0BAA2B,SAAQ,UAAU;IACtD,MAAM,CAAC,SAAS,SAA6B;CAChD;AAED;;GAEG;AACH,qBAAa,sBAAuB,SAAQ,UAAU;IAClD,MAAM,CAAC,SAAS,SAAwB;CAC3C;AAED;;GAEG;AACH,qBAAa,gBAAiB,SAAQ,UAAU;IAExC,OAAO,CAAC,QAAQ,CAAC,eAAe;gBAAf,eAAe,EAAE,MAAM,EACxC,OAAO,EAAE,MAAM,EACf,QAAQ,CAAC,EAAE,MAAM;IAKrB,IAAI,SAAS,IAAI,MAAM,CAEtB;CACJ;AAED;;GAEG;AACH,eAAO,MAAM,YAAY;;CAiBf,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/errors.js b/dist/esm/server/auth/errors.js deleted file mode 100644 index e5dcdbe051..0000000000 --- a/dist/esm/server/auth/errors.js +++ /dev/null @@ -1,172 +0,0 @@ -/** - * Base class for all OAuth errors - */ -export class OAuthError extends Error { - constructor(message, errorUri) { - super(message); - this.errorUri = errorUri; - this.name = this.constructor.name; - } - /** - * Converts the error to a standard OAuth error response object - */ - toResponseObject() { - const response = { - error: this.errorCode, - error_description: this.message - }; - if (this.errorUri) { - response.error_uri = this.errorUri; - } - return response; - } - get errorCode() { - return this.constructor.errorCode; - } -} -/** - * Invalid request error - The request is missing a required parameter, - * includes an invalid parameter value, includes a parameter more than once, - * or is otherwise malformed. - */ -export class InvalidRequestError extends OAuthError { -} -InvalidRequestError.errorCode = 'invalid_request'; -/** - * Invalid client error - Client authentication failed (e.g., unknown client, no client - * authentication included, or unsupported authentication method). - */ -export class InvalidClientError extends OAuthError { -} -InvalidClientError.errorCode = 'invalid_client'; -/** - * Invalid grant error - The provided authorization grant or refresh token is - * invalid, expired, revoked, does not match the redirection URI used in the - * authorization request, or was issued to another client. - */ -export class InvalidGrantError extends OAuthError { -} -InvalidGrantError.errorCode = 'invalid_grant'; -/** - * Unauthorized client error - The authenticated client is not authorized to use - * this authorization grant type. - */ -export class UnauthorizedClientError extends OAuthError { -} -UnauthorizedClientError.errorCode = 'unauthorized_client'; -/** - * Unsupported grant type error - The authorization grant type is not supported - * by the authorization server. - */ -export class UnsupportedGrantTypeError extends OAuthError { -} -UnsupportedGrantTypeError.errorCode = 'unsupported_grant_type'; -/** - * Invalid scope error - The requested scope is invalid, unknown, malformed, or - * exceeds the scope granted by the resource owner. - */ -export class InvalidScopeError extends OAuthError { -} -InvalidScopeError.errorCode = 'invalid_scope'; -/** - * Access denied error - The resource owner or authorization server denied the request. - */ -export class AccessDeniedError extends OAuthError { -} -AccessDeniedError.errorCode = 'access_denied'; -/** - * Server error - The authorization server encountered an unexpected condition - * that prevented it from fulfilling the request. - */ -export class ServerError extends OAuthError { -} -ServerError.errorCode = 'server_error'; -/** - * Temporarily unavailable error - The authorization server is currently unable to - * handle the request due to a temporary overloading or maintenance of the server. - */ -export class TemporarilyUnavailableError extends OAuthError { -} -TemporarilyUnavailableError.errorCode = 'temporarily_unavailable'; -/** - * Unsupported response type error - The authorization server does not support - * obtaining an authorization code using this method. - */ -export class UnsupportedResponseTypeError extends OAuthError { -} -UnsupportedResponseTypeError.errorCode = 'unsupported_response_type'; -/** - * Unsupported token type error - The authorization server does not support - * the requested token type. - */ -export class UnsupportedTokenTypeError extends OAuthError { -} -UnsupportedTokenTypeError.errorCode = 'unsupported_token_type'; -/** - * Invalid token error - The access token provided is expired, revoked, malformed, - * or invalid for other reasons. - */ -export class InvalidTokenError extends OAuthError { -} -InvalidTokenError.errorCode = 'invalid_token'; -/** - * Method not allowed error - The HTTP method used is not allowed for this endpoint. - * (Custom, non-standard error) - */ -export class MethodNotAllowedError extends OAuthError { -} -MethodNotAllowedError.errorCode = 'method_not_allowed'; -/** - * Too many requests error - Rate limit exceeded. - * (Custom, non-standard error based on RFC 6585) - */ -export class TooManyRequestsError extends OAuthError { -} -TooManyRequestsError.errorCode = 'too_many_requests'; -/** - * Invalid client metadata error - The client metadata is invalid. - * (Custom error for dynamic client registration - RFC 7591) - */ -export class InvalidClientMetadataError extends OAuthError { -} -InvalidClientMetadataError.errorCode = 'invalid_client_metadata'; -/** - * Insufficient scope error - The request requires higher privileges than provided by the access token. - */ -export class InsufficientScopeError extends OAuthError { -} -InsufficientScopeError.errorCode = 'insufficient_scope'; -/** - * A utility class for defining one-off error codes - */ -export class CustomOAuthError extends OAuthError { - constructor(customErrorCode, message, errorUri) { - super(message, errorUri); - this.customErrorCode = customErrorCode; - } - get errorCode() { - return this.customErrorCode; - } -} -/** - * A full list of all OAuthErrors, enabling parsing from error responses - */ -export const OAUTH_ERRORS = { - [InvalidRequestError.errorCode]: InvalidRequestError, - [InvalidClientError.errorCode]: InvalidClientError, - [InvalidGrantError.errorCode]: InvalidGrantError, - [UnauthorizedClientError.errorCode]: UnauthorizedClientError, - [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError, - [InvalidScopeError.errorCode]: InvalidScopeError, - [AccessDeniedError.errorCode]: AccessDeniedError, - [ServerError.errorCode]: ServerError, - [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError, - [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError, - [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError, - [InvalidTokenError.errorCode]: InvalidTokenError, - [MethodNotAllowedError.errorCode]: MethodNotAllowedError, - [TooManyRequestsError.errorCode]: TooManyRequestsError, - [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError, - [InsufficientScopeError.errorCode]: InsufficientScopeError -}; -//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/errors.js.map b/dist/esm/server/auth/errors.js.map deleted file mode 100644 index 374731d279..0000000000 --- a/dist/esm/server/auth/errors.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"errors.js","sourceRoot":"","sources":["../../../../src/server/auth/errors.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,OAAO,UAAW,SAAQ,KAAK;IAGjC,YACI,OAAe,EACC,QAAiB;QAEjC,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,aAAQ,GAAR,QAAQ,CAAS;QAGjC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;IACtC,CAAC;IAED;;OAEG;IACH,gBAAgB;QACZ,MAAM,QAAQ,GAAuB;YACjC,KAAK,EAAE,IAAI,CAAC,SAAS;YACrB,iBAAiB,EAAE,IAAI,CAAC,OAAO;SAClC,CAAC;QAEF,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAChB,QAAQ,CAAC,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC;QACvC,CAAC;QAED,OAAO,QAAQ,CAAC;IACpB,CAAC;IAED,IAAI,SAAS;QACT,OAAQ,IAAI,CAAC,WAAiC,CAAC,SAAS,CAAC;IAC7D,CAAC;CACJ;AAED;;;;GAIG;AACH,MAAM,OAAO,mBAAoB,SAAQ,UAAU;;AACxC,6BAAS,GAAG,iBAAiB,CAAC;AAGzC;;;GAGG;AACH,MAAM,OAAO,kBAAmB,SAAQ,UAAU;;AACvC,4BAAS,GAAG,gBAAgB,CAAC;AAGxC;;;;GAIG;AACH,MAAM,OAAO,iBAAkB,SAAQ,UAAU;;AACtC,2BAAS,GAAG,eAAe,CAAC;AAGvC;;;GAGG;AACH,MAAM,OAAO,uBAAwB,SAAQ,UAAU;;AAC5C,iCAAS,GAAG,qBAAqB,CAAC;AAG7C;;;GAGG;AACH,MAAM,OAAO,yBAA0B,SAAQ,UAAU;;AAC9C,mCAAS,GAAG,wBAAwB,CAAC;AAGhD;;;GAGG;AACH,MAAM,OAAO,iBAAkB,SAAQ,U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ACxB,CAAC,mBAAmB,CAAC,SAAS,CAAC,EAAE,mBAAmB;IACpD,CAAC,kBAAkB,CAAC,SAAS,CAAC,EAAE,kBAAkB;IAClD,CAAC,iBAAiB,CAAC,SAAS,CAAC,EAAE,iBAAiB;IAChD,CAAC,uBAAuB,CAAC,SAAS,CAAC,EAAE,uBAAuB;IAC5D,CAAC,yBAAyB,CAAC,SAAS,CAAC,EAAE,yBAAyB;IAChE,CAAC,iBAAiB,CAAC,SAAS,CAAC,EAAE,iBAAiB;IAChD,CAAC,iBAAiB,CAAC,SAAS,CAAC,EAAE,iBAAiB;IAChD,CAAC,WAAW,CAAC,SAAS,CAAC,EAAE,WAAW;IACpC,CAAC,2BAA2B,CAAC,SAAS,CAAC,EAAE,2BAA2B;IACpE,CAAC,4BAA4B,CAAC,SAAS,CAAC,EAAE,4BAA4B;IACtE,CAAC,yBAAyB,CAAC,SAAS,CAAC,EAAE,yBAAyB;IAChE,CAAC,iBAAiB,CAAC,SAAS,CAAC,EAAE,iBAAiB;IAChD,CAAC,qBAAqB,CAAC,SAAS,CAAC,EAAE,qBAAqB;IACxD,CAAC,oBAAoB,CAAC,SAAS,CAAC,EAAE,oBAAoB;IACtD,CAAC,0BAA0B,CAAC,SAAS,CAAC,EAAE,0BAA0B;IAClE,CAAC,sBAAsB,CAAC,SAAS,CAAC,EAAE,sBAAsB;CACpD,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/authorize.d.ts b/dist/esm/server/auth/handlers/authorize.d.ts deleted file mode 100644 index 38e9829bd2..0000000000 --- a/dist/esm/server/auth/handlers/authorize.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { RequestHandler } from 'express'; -import { OAuthServerProvider } from '../provider.js'; -import { Options as RateLimitOptions } from 'express-rate-limit'; -export type AuthorizationHandlerOptions = { - provider: OAuthServerProvider; - /** - * Rate limiting configuration for the authorization endpoint. - * Set to false to disable rate limiting for this endpoint. - */ - rateLimit?: Partial | false; -}; -export declare function authorizationHandler({ provider, rateLimit: rateLimitConfig }: AuthorizationHandlerOptions): RequestHandler; -//# sourceMappingURL=authorize.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/authorize.d.ts.map b/dist/esm/server/auth/handlers/authorize.d.ts.map deleted file mode 100644 index b067988349..0000000000 --- a/dist/esm/server/auth/handlers/authorize.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"authorize.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/authorize.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAGzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,2BAA2B,GAAG;IACtC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAqBF,wBAAgB,oBAAoB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,2BAA2B,GAAG,cAAc,CAgH1H"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/authorize.js b/dist/esm/server/auth/handlers/authorize.js deleted file mode 100644 index e29f09438e..0000000000 --- a/dist/esm/server/auth/handlers/authorize.js +++ /dev/null @@ -1,138 +0,0 @@ -import * as z from 'zod/v4'; -import express from 'express'; -import { rateLimit } from 'express-rate-limit'; -import { allowedMethods } from '../middleware/allowedMethods.js'; -import { InvalidRequestError, InvalidClientError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; -// Parameters that must be validated in order to issue redirects. -const ClientAuthorizationParamsSchema = z.object({ - client_id: z.string(), - redirect_uri: z - .string() - .optional() - .refine(value => value === undefined || URL.canParse(value), { message: 'redirect_uri must be a valid URL' }) -}); -// Parameters that must be validated for a successful authorization request. Failure can be reported to the redirect URI. -const RequestAuthorizationParamsSchema = z.object({ - response_type: z.literal('code'), - code_challenge: z.string(), - code_challenge_method: z.literal('S256'), - scope: z.string().optional(), - state: z.string().optional(), - resource: z.string().url().optional() -}); -export function authorizationHandler({ provider, rateLimit: rateLimitConfig }) { - // Create a router to apply middleware - const router = express.Router(); - router.use(allowedMethods(['GET', 'POST'])); - router.use(express.urlencoded({ extended: false })); - // Apply rate limiting unless explicitly disabled - if (rateLimitConfig !== false) { - router.use(rateLimit({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 100, // 100 requests per windowMs - standardHeaders: true, - legacyHeaders: false, - message: new TooManyRequestsError('You have exceeded the rate limit for authorization requests').toResponseObject(), - ...rateLimitConfig - })); - } - router.all('/', async (req, res) => { - res.setHeader('Cache-Control', 'no-store'); - // In the authorization flow, errors are split into two categories: - // 1. Pre-redirect errors (direct response with 400) - // 2. Post-redirect errors (redirect with error parameters) - // Phase 1: Validate client_id and redirect_uri. Any errors here must be direct responses. - let client_id, redirect_uri, client; - try { - const result = ClientAuthorizationParamsSchema.safeParse(req.method === 'POST' ? req.body : req.query); - if (!result.success) { - throw new InvalidRequestError(result.error.message); - } - client_id = result.data.client_id; - redirect_uri = result.data.redirect_uri; - client = await provider.clientsStore.getClient(client_id); - if (!client) { - throw new InvalidClientError('Invalid client_id'); - } - if (redirect_uri !== undefined) { - if (!client.redirect_uris.includes(redirect_uri)) { - throw new InvalidRequestError('Unregistered redirect_uri'); - } - } - else if (client.redirect_uris.length === 1) { - redirect_uri = client.redirect_uris[0]; - } - else { - throw new InvalidRequestError('redirect_uri must be specified when client has multiple registered URIs'); - } - } - catch (error) { - // Pre-redirect errors - return direct response - // - // These don't need to be JSON encoded, as they'll be displayed in a user - // agent, but OTOH they all represent exceptional situations (arguably, - // "programmer error"), so presenting a nice HTML page doesn't help the - // user anyway. - if (error instanceof OAuthError) { - const status = error instanceof ServerError ? 500 : 400; - res.status(status).json(error.toResponseObject()); - } - else { - const serverError = new ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - return; - } - // Phase 2: Validate other parameters. Any errors here should go into redirect responses. - let state; - try { - // Parse and validate authorization parameters - const parseResult = RequestAuthorizationParamsSchema.safeParse(req.method === 'POST' ? req.body : req.query); - if (!parseResult.success) { - throw new InvalidRequestError(parseResult.error.message); - } - const { scope, code_challenge, resource } = parseResult.data; - state = parseResult.data.state; - // Validate scopes - let requestedScopes = []; - if (scope !== undefined) { - requestedScopes = scope.split(' '); - } - // All validation passed, proceed with authorization - await provider.authorize(client, { - state, - scopes: requestedScopes, - redirectUri: redirect_uri, - codeChallenge: code_challenge, - resource: resource ? new URL(resource) : undefined - }, res); - } - catch (error) { - // Post-redirect errors - redirect with error parameters - if (error instanceof OAuthError) { - res.redirect(302, createErrorRedirect(redirect_uri, error, state)); - } - else { - const serverError = new ServerError('Internal Server Error'); - res.redirect(302, createErrorRedirect(redirect_uri, serverError, state)); - } - } - }); - return router; -} -/** - * Helper function to create redirect URL with error parameters - */ -function createErrorRedirect(redirectUri, error, state) { - const errorUrl = new URL(redirectUri); - errorUrl.searchParams.set('error', error.errorCode); - errorUrl.searchParams.set('error_description', error.message); - if (error.errorUri) { - errorUrl.searchParams.set('error_uri', error.errorUri); - } - if (state) { - errorUrl.searchParams.set('state', state); - } - return errorUrl.href; -} -//# sourceMappingURL=authorize.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/authorize.js.map b/dist/esm/server/auth/handlers/authorize.js.map deleted file mode 100644 index 6911f9a386..0000000000 --- a/dist/esm/server/auth/handlers/authorize.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"authorize.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/authorize.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,OAAO,MAAM,SAAS,CAAC;AAE9B,OAAO,EAAE,SAAS,EAA+B,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EA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C;AAClB,CAAC;AAED;;GAEG;AACH,SAAS,mBAAmB,CAAC,WAAmB,EAAE,KAAiB,EAAE,KAAc;IAC/E,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,WAAW,CAAC,CAAC;IACtC,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC;IACpD,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,mBAAmB,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC;IAC9D,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;QACjB,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,WAAW,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC;IAC3D,CAAC;IACD,IAAI,KAAK,EAAE,CAAC;QACR,QAAQ,CAAC,YAAY,CAAC,GAAG,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC9C,CAAC;IACD,OAAO,QAAQ,CAAC,IAAI,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/metadata.d.ts b/dist/esm/server/auth/handlers/metadata.d.ts deleted file mode 100644 index 4d03286170..0000000000 --- a/dist/esm/server/auth/handlers/metadata.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import { RequestHandler } from 'express'; -import { OAuthMetadata, OAuthProtectedResourceMetadata } from '../../../shared/auth.js'; -export declare function metadataHandler(metadata: OAuthMetadata | OAuthProtectedResourceMetadata): RequestHandler; -//# sourceMappingURL=metadata.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/metadata.d.ts.map b/dist/esm/server/auth/handlers/metadata.d.ts.map deleted file mode 100644 index 55e3a50dc1..0000000000 --- a/dist/esm/server/auth/handlers/metadata.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"metadata.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/metadata.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,8BAA8B,EAAE,MAAM,yBAAyB,CAAC;AAIxF,wBAAgB,eAAe,CAAC,QAAQ,EAAE,aAAa,GAAG,8BAA8B,GAAG,cAAc,CAaxG"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/metadata.js b/dist/esm/server/auth/handlers/metadata.js deleted file mode 100644 index 94dadb709e..0000000000 --- a/dist/esm/server/auth/handlers/metadata.js +++ /dev/null @@ -1,15 +0,0 @@ -import express from 'express'; -import cors from 'cors'; -import { allowedMethods } from '../middleware/allowedMethods.js'; -export function metadataHandler(metadata) { - // Nested router so we can configure middleware and restrict HTTP method - const router = express.Router(); - // Configure CORS to allow any origin, to make accessible to web-based MCP clients - router.use(cors()); - router.use(allowedMethods(['GET', 'OPTIONS'])); - router.get('/', (req, res) => { - res.status(200).json(metadata); - }); - return router; -} -//# sourceMappingURL=metadata.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/metadata.js.map b/dist/esm/server/auth/handlers/metadata.js.map deleted file mode 100644 index 625ed947d2..0000000000 --- a/dist/esm/server/auth/handlers/metadata.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/metadata.ts"],"names":[],"mappings":"AAAA,OAAO,OAA2B,MAAM,SAAS,CAAC;AAElD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AAEjE,MAAM,UAAU,eAAe,CAAC,QAAwD;IACpF,wEAAwE;IACxE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;IAEhC,kFAAkF;IAClF,MAAM,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;IAEnB,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC;IAC/C,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;QACzB,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACnC,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/register.d.ts b/dist/esm/server/auth/handlers/register.d.ts deleted file mode 100644 index e9add28458..0000000000 --- a/dist/esm/server/auth/handlers/register.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { RequestHandler } from 'express'; -import { OAuthRegisteredClientsStore } from '../clients.js'; -import { Options as RateLimitOptions } from 'express-rate-limit'; -export type ClientRegistrationHandlerOptions = { - /** - * A store used to save information about dynamically registered OAuth clients. - */ - clientsStore: OAuthRegisteredClientsStore; - /** - * The number of seconds after which to expire issued client secrets, or 0 to prevent expiration of client secrets (not recommended). - * - * If not set, defaults to 30 days. - */ - clientSecretExpirySeconds?: number; - /** - * Rate limiting configuration for the client registration endpoint. - * Set to false to disable rate limiting for this endpoint. - * Registration endpoints are particularly sensitive to abuse and should be rate limited. - */ - rateLimit?: Partial | false; - /** - * Whether to generate a client ID before calling the client registration endpoint. - * - * If not set, defaults to true. - */ - clientIdGeneration?: boolean; -}; -export declare function clientRegistrationHandler({ clientsStore, clientSecretExpirySeconds, rateLimit: rateLimitConfig, clientIdGeneration }: ClientRegistrationHandlerOptions): RequestHandler; -//# sourceMappingURL=register.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/register.d.ts.map b/dist/esm/server/auth/handlers/register.d.ts.map deleted file mode 100644 index a38ebdb89e..0000000000 --- a/dist/esm/server/auth/handlers/register.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"register.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/register.ts"],"names":[],"mappings":"AAAA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAIlD,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,gCAAgC,GAAG;IAC3C;;OAEG;IACH,YAAY,EAAE,2BAA2B,CAAC;IAE1C;;;;OAIG;IACH,yBAAyB,CAAC,EAAE,MAAM,CAAC;IAEnC;;;;OAIG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;IAE9C;;;;OAIG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAChC,CAAC;AAIF,wBAAgB,yBAAyB,CAAC,EACtC,YAAY,EACZ,yBAAgE,EAChE,SAAS,EAAE,eAAe,EAC1B,kBAAyB,EAC5B,EAAE,gCAAgC,GAAG,cAAc,CA0EnD"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/register.js b/dist/esm/server/auth/handlers/register.js deleted file mode 100644 index ef6c44d518..0000000000 --- a/dist/esm/server/auth/handlers/register.js +++ /dev/null @@ -1,71 +0,0 @@ -import express from 'express'; -import { OAuthClientMetadataSchema } from '../../../shared/auth.js'; -import crypto from 'node:crypto'; -import cors from 'cors'; -import { rateLimit } from 'express-rate-limit'; -import { allowedMethods } from '../middleware/allowedMethods.js'; -import { InvalidClientMetadataError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; -const DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS = 30 * 24 * 60 * 60; // 30 days -export function clientRegistrationHandler({ clientsStore, clientSecretExpirySeconds = DEFAULT_CLIENT_SECRET_EXPIRY_SECONDS, rateLimit: rateLimitConfig, clientIdGeneration = true }) { - if (!clientsStore.registerClient) { - throw new Error('Client registration store does not support registering clients'); - } - // Nested router so we can configure middleware and restrict HTTP method - const router = express.Router(); - // Configure CORS to allow any origin, to make accessible to web-based MCP clients - router.use(cors()); - router.use(allowedMethods(['POST'])); - router.use(express.json()); - // Apply rate limiting unless explicitly disabled - stricter limits for registration - if (rateLimitConfig !== false) { - router.use(rateLimit({ - windowMs: 60 * 60 * 1000, // 1 hour - max: 20, // 20 requests per hour - stricter as registration is sensitive - standardHeaders: true, - legacyHeaders: false, - message: new TooManyRequestsError('You have exceeded the rate limit for client registration requests').toResponseObject(), - ...rateLimitConfig - })); - } - router.post('/', async (req, res) => { - res.setHeader('Cache-Control', 'no-store'); - try { - const parseResult = OAuthClientMetadataSchema.safeParse(req.body); - if (!parseResult.success) { - throw new InvalidClientMetadataError(parseResult.error.message); - } - const clientMetadata = parseResult.data; - const isPublicClient = clientMetadata.token_endpoint_auth_method === 'none'; - // Generate client credentials - const clientSecret = isPublicClient ? undefined : crypto.randomBytes(32).toString('hex'); - const clientIdIssuedAt = Math.floor(Date.now() / 1000); - // Calculate client secret expiry time - const clientsDoExpire = clientSecretExpirySeconds > 0; - const secretExpiryTime = clientsDoExpire ? clientIdIssuedAt + clientSecretExpirySeconds : 0; - const clientSecretExpiresAt = isPublicClient ? undefined : secretExpiryTime; - let clientInfo = { - ...clientMetadata, - client_secret: clientSecret, - client_secret_expires_at: clientSecretExpiresAt - }; - if (clientIdGeneration) { - clientInfo.client_id = crypto.randomUUID(); - clientInfo.client_id_issued_at = clientIdIssuedAt; - } - clientInfo = await clientsStore.registerClient(clientInfo); - res.status(201).json(clientInfo); - } - catch (error) { - if (error instanceof OAuthError) { - const status = error instanceof ServerError ? 500 : 400; - res.status(status).json(error.toResponseObject()); - } - else { - const serverError = new ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - } - }); - return router; -} -//# sourceMappingURL=register.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/register.js.map b/dist/esm/server/auth/handlers/register.js.map deleted file mode 100644 index 3f4c082f04..0000000000 --- a/dist/esm/server/auth/handlers/register.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"register.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/register.ts"],"names":[],"mappings":"AAAA,OAA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AAI,kBAAkB,EAAE,CAAC;gBACrB,UAAU,CAAC,SAAS,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;gBAC3C,UAAU,CAAC,mBAAmB,GAAG,gBAAgB,CAAC;YACtD,CAAC;YAED,UAAU,GAAG,MAAM,YAAY,CAAC,cAAe,CAAC,UAAU,CAAC,CAAC;YAC5D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;QACrC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,KAAK,YAAY,UAAU,EAAE,CAAC;gBAC9B,MAAM,MAAM,GAAG,KAAK,YAAY,WAAW,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;gBACxD,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,WAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/revoke.d.ts b/dist/esm/server/auth/handlers/revoke.d.ts deleted file mode 100644 index 2be32bb3ca..0000000000 --- a/dist/esm/server/auth/handlers/revoke.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { OAuthServerProvider } from '../provider.js'; -import { RequestHandler } from 'express'; -import { Options as RateLimitOptions } from 'express-rate-limit'; -export type RevocationHandlerOptions = { - provider: OAuthServerProvider; - /** - * Rate limiting configuration for the token revocation endpoint. - * Set to false to disable rate limiting for this endpoint. - */ - rateLimit?: Partial | false; -}; -export declare function revocationHandler({ provider, rateLimit: rateLimitConfig }: RevocationHandlerOptions): RequestHandler; -//# sourceMappingURL=revoke.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/revoke.d.ts.map b/dist/esm/server/auth/handlers/revoke.d.ts.map deleted file mode 100644 index fb13cf19fe..0000000000 --- a/dist/esm/server/auth/handlers/revoke.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"revoke.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/revoke.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAIlD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAI5E,MAAM,MAAM,wBAAwB,GAAG;IACnC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAEF,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,wBAAwB,GAAG,cAAc,CA4DpH"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/revoke.js b/dist/esm/server/auth/handlers/revoke.js deleted file mode 100644 index 68f5284dd4..0000000000 --- a/dist/esm/server/auth/handlers/revoke.js +++ /dev/null @@ -1,59 +0,0 @@ -import express from 'express'; -import cors from 'cors'; -import { authenticateClient } from '../middleware/clientAuth.js'; -import { OAuthTokenRevocationRequestSchema } from '../../../shared/auth.js'; -import { rateLimit } from 'express-rate-limit'; -import { allowedMethods } from '../middleware/allowedMethods.js'; -import { InvalidRequestError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; -export function revocationHandler({ provider, rateLimit: rateLimitConfig }) { - if (!provider.revokeToken) { - throw new Error('Auth provider does not support revoking tokens'); - } - // Nested router so we can configure middleware and restrict HTTP method - const router = express.Router(); - // Configure CORS to allow any origin, to make accessible to web-based MCP clients - router.use(cors()); - router.use(allowedMethods(['POST'])); - router.use(express.urlencoded({ extended: false })); - // Apply rate limiting unless explicitly disabled - if (rateLimitConfig !== false) { - router.use(rateLimit({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 50, // 50 requests per windowMs - standardHeaders: true, - legacyHeaders: false, - message: new TooManyRequestsError('You have exceeded the rate limit for token revocation requests').toResponseObject(), - ...rateLimitConfig - })); - } - // Authenticate and extract client details - router.use(authenticateClient({ clientsStore: provider.clientsStore })); - router.post('/', async (req, res) => { - res.setHeader('Cache-Control', 'no-store'); - try { - const parseResult = OAuthTokenRevocationRequestSchema.safeParse(req.body); - if (!parseResult.success) { - throw new InvalidRequestError(parseResult.error.message); - } - const client = req.client; - if (!client) { - // This should never happen - throw new ServerError('Internal Server Error'); - } - await provider.revokeToken(client, parseResult.data); - res.status(200).json({}); - } - catch (error) { - if (error instanceof OAuthError) { - const status = error instanceof ServerError ? 500 : 400; - res.status(status).json(error.toResponseObject()); - } - else { - const serverError = new ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - } - }); - return router; -} -//# sourceMappingURL=revoke.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/revoke.js.map b/dist/esm/server/auth/handlers/revoke.js.map deleted file mode 100644 index e1a0b1db98..0000000000 --- a/dist/esm/server/auth/handlers/revoke.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"revoke.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/revoke.ts"],"names":[],"mappings":"AACA,OAAO,OAA2B,MAAM,SAAS,CAAC;AAClD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,iCAAiC,EAAE,MAAM,yBAAyB,CAAC;AAC5E,OAAO,EAAE,SAAS,EAA+B,MAAM,oBAAoB,CAAC;AAC5E,OAAO,E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 100644 index 24d1c8783b..0000000000 --- a/dist/esm/server/auth/handlers/token.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { RequestHandler } from 'express'; -import { OAuthServerProvider } from '../provider.js'; -import { Options as RateLimitOptions } from 'express-rate-limit'; -export type TokenHandlerOptions = { - provider: OAuthServerProvider; - /** - * Rate limiting configuration for the token endpoint. - * Set to false to disable rate limiting for this endpoint. - */ - rateLimit?: Partial | false; -}; -export declare function tokenHandler({ provider, rateLimit: rateLimitConfig }: TokenHandlerOptions): RequestHandler; -//# sourceMappingURL=token.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/token.d.ts.map b/dist/esm/server/auth/handlers/token.d.ts.map deleted file mode 100644 index 3d539f3451..0000000000 --- a/dist/esm/server/auth/handlers/token.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"token.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/token.ts"],"names":[],"mappings":"AACA,OAAgB,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAIrD,OAAO,EAAa,OAAO,IAAI,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAW5E,MAAM,MAAM,mBAAmB,GAAG;IAC9B,QAAQ,EAAE,mBAAmB,CAAC;IAC9B;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC,gBAAgB,CAAC,GAAG,KAAK,CAAC;CACjD,CAAC;AAmBF,wBAAgB,YAAY,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,mBAAmB,GAAG,cAAc,CAiH1G"} \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/token.js b/dist/esm/server/auth/handlers/token.js deleted file mode 100644 index da9341e278..0000000000 --- a/dist/esm/server/auth/handlers/token.js +++ /dev/null @@ -1,107 +0,0 @@ -import * as z from 'zod/v4'; -import express from 'express'; -import cors from 'cors'; -import { verifyChallenge } from 'pkce-challenge'; -import { authenticateClient } from '../middleware/clientAuth.js'; -import { rateLimit } from 'express-rate-limit'; -import { allowedMethods } from '../middleware/allowedMethods.js'; -import { InvalidRequestError, InvalidGrantError, UnsupportedGrantTypeError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; -const TokenRequestSchema = z.object({ - grant_type: z.string() -}); -const AuthorizationCodeGrantSchema = z.object({ - code: z.string(), - code_verifier: z.string(), - redirect_uri: z.string().optional(), - resource: z.string().url().optional() -}); -const RefreshTokenGrantSchema = z.object({ - refresh_token: z.string(), - scope: z.string().optional(), - resource: z.string().url().optional() -}); -export function tokenHandler({ provider, rateLimit: rateLimitConfig }) { - // Nested router so we can configure middleware and restrict HTTP method - const router = express.Router(); - // Configure CORS to allow any origin, to make accessible to web-based MCP clients - router.use(cors()); - router.use(allowedMethods(['POST'])); - router.use(express.urlencoded({ extended: false })); - // Apply rate limiting unless explicitly disabled - if (rateLimitConfig !== false) { - router.use(rateLimit({ - windowMs: 15 * 60 * 1000, // 15 minutes - max: 50, // 50 requests per windowMs - standardHeaders: true, - legacyHeaders: false, - message: new TooManyRequestsError('You have exceeded the rate limit for token requests').toResponseObject(), - ...rateLimitConfig - })); - } - // Authenticate and extract client details - router.use(authenticateClient({ clientsStore: provider.clientsStore })); - router.post('/', async (req, res) => { - res.setHeader('Cache-Control', 'no-store'); - try { - const parseResult = TokenRequestSchema.safeParse(req.body); - if (!parseResult.success) { - throw new InvalidRequestError(parseResult.error.message); - } - const { grant_type } = parseResult.data; - const client = req.client; - if (!client) { - // This should never happen - throw new ServerError('Internal Server Error'); - } - switch (grant_type) { - case 'authorization_code': { - const parseResult = AuthorizationCodeGrantSchema.safeParse(req.body); - if (!parseResult.success) { - throw new InvalidRequestError(parseResult.error.message); - } - const { code, code_verifier, redirect_uri, resource } = parseResult.data; - const skipLocalPkceValidation = provider.skipLocalPkceValidation; - // Perform local PKCE validation unless explicitly skipped - // (e.g. to validate code_verifier in upstream server) - if (!skipLocalPkceValidation) { - const codeChallenge = await provider.challengeForAuthorizationCode(client, code); - if (!(await verifyChallenge(code_verifier, codeChallenge))) { - throw new InvalidGrantError('code_verifier does not match the challenge'); - } - } - // Passes the code_verifier to the provider if PKCE validation didn't occur locally - const tokens = await provider.exchangeAuthorizationCode(client, code, skipLocalPkceValidation ? code_verifier : undefined, redirect_uri, resource ? new URL(resource) : undefined); - res.status(200).json(tokens); - break; - } - case 'refresh_token': { - const parseResult = RefreshTokenGrantSchema.safeParse(req.body); - if (!parseResult.success) { - throw new InvalidRequestError(parseResult.error.message); - } - const { refresh_token, scope, resource } = parseResult.data; - const scopes = scope === null || scope === void 0 ? void 0 : scope.split(' '); - const tokens = await provider.exchangeRefreshToken(client, refresh_token, scopes, resource ? new URL(resource) : undefined); - res.status(200).json(tokens); - break; - } - // Not supported right now - //case "client_credentials": - default: - throw new UnsupportedGrantTypeError('The grant type is not supported by this authorization server.'); - } - } - catch (error) { - if (error instanceof OAuthError) { - const status = error instanceof ServerError ? 500 : 400; - res.status(status).json(error.toResponseObject()); - } - else { - const serverError = new ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - } - }); - return router; -} -//# sourceMappingURL=token.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/handlers/token.js.map b/dist/esm/server/auth/handlers/token.js.map deleted file mode 100644 index 312f568a2f..0000000000 --- a/dist/esm/server/auth/handlers/token.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"token.js","sourceRoot":"","sources":["../../../../../src/server/auth/handlers/token.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,OAA2B,MAAM,SAAS,CAAC;AAElD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAAE,SAAS,EAA+B,MAAM,oBAAo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leware/allowedMethods.d.ts deleted file mode 100644 index ee6037e0de..0000000000 --- a/dist/esm/server/auth/middleware/allowedMethods.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { RequestHandler } from 'express'; -/** - * Middleware to handle unsupported HTTP methods with a 405 Method Not Allowed response. - * - * @param allowedMethods Array of allowed HTTP methods for this endpoint (e.g., ['GET', 'POST']) - * @returns Express middleware that returns a 405 error if method not in allowed list - */ -export declare function allowedMethods(allowedMethods: string[]): RequestHandler; -//# sourceMappingURL=allowedMethods.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/allowedMethods.d.ts.map b/dist/esm/server/auth/middleware/allowedMethods.d.ts.map deleted file mode 100644 index d3de93e242..0000000000 --- a/dist/esm/server/auth/middleware/allowedMethods.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"allowedMethods.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/allowedMethods.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAGzC;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,cAAc,EAAE,MAAM,EAAE,GAAG,cAAc,CAUvE"} \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/allowedMethods.js b/dist/esm/server/auth/middleware/allowedMethods.js deleted file mode 100644 index af2ba08923..0000000000 --- a/dist/esm/server/auth/middleware/allowedMethods.js +++ /dev/null @@ -1,18 +0,0 @@ -import { MethodNotAllowedError } from '../errors.js'; -/** - * Middleware to handle unsupported HTTP methods with a 405 Method Not Allowed response. - * - * @param allowedMethods Array of allowed HTTP methods for this endpoint (e.g., ['GET', 'POST']) - * @returns Express middleware that returns a 405 error if method not in allowed list - */ -export function allowedMethods(allowedMethods) { - return (req, res, next) => { - if (allowedMethods.includes(req.method)) { - next(); - return; - } - const error = new MethodNotAllowedError(`The method ${req.method} is not allowed for this endpoint`); - res.status(405).set('Allow', allowedMethods.join(', ')).json(error.toResponseObject()); - }; -} -//# sourceMappingURL=allowedMethods.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/allowedMethods.js.map b/dist/esm/server/auth/middleware/allowedMethods.js.map deleted file mode 100644 index c410979868..0000000000 --- a/dist/esm/server/auth/middleware/allowedMethods.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"allowedMethods.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/allowedMethods.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAErD;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,cAAwB;IACnD,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACtB,IAAI,cAAc,CAAC,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;YACtC,IAAI,EAAE,CAAC;YACP,OAAO;QACX,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,qBAAqB,CAAC,cAAc,GAAG,CAAC,MAAM,mCAAmC,CAAC,CAAC;QACrG,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;IAC3F,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/bearerAuth.d.ts b/dist/esm/server/auth/middleware/bearerAuth.d.ts deleted file mode 100644 index 10730758bc..0000000000 --- a/dist/esm/server/auth/middleware/bearerAuth.d.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { RequestHandler } from 'express'; -import { OAuthTokenVerifier } from '../provider.js'; -import { AuthInfo } from '../types.js'; -export type BearerAuthMiddlewareOptions = { - /** - * A provider used to verify tokens. - */ - verifier: OAuthTokenVerifier; - /** - * Optional scopes that the token must have. - */ - requiredScopes?: string[]; - /** - * Optional resource metadata URL to include in WWW-Authenticate header. - */ - resourceMetadataUrl?: string; -}; -declare module 'express-serve-static-core' { - interface Request { - /** - * Information about the validated access token, if the `requireBearerAuth` middleware was used. - */ - auth?: AuthInfo; - } -} -/** - * Middleware that requires a valid Bearer token in the Authorization header. - * - * This will validate the token with the auth provider and add the resulting auth info to the request object. - * - * If resourceMetadataUrl is provided, it will be included in the WWW-Authenticate header - * for 401 responses as per the OAuth 2.0 Protected Resource Metadata spec. - */ -export declare function requireBearerAuth({ verifier, requiredScopes, resourceMetadataUrl }: BearerAuthMiddlewareOptions): RequestHandler; -//# sourceMappingURL=bearerAuth.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/bearerAuth.d.ts.map b/dist/esm/server/auth/middleware/bearerAuth.d.ts.map deleted file mode 100644 index c9d939f3b7..0000000000 --- a/dist/esm/server/auth/middleware/bearerAuth.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bearerAuth.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/bearerAuth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAEzC,OAAO,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEvC,MAAM,MAAM,2BAA2B,GAAG;IACtC;;OAEG;IACH,QAAQ,EAAE,kBAAkB,CAAC;IAE7B;;OAEG;IACH,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAE1B;;OAEG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;CAChC,CAAC;AAEF,OAAO,QAAQ,2BAA2B,CAAC;IACvC,UAAU,OAAO;QACb;;WAEG;QACH,IAAI,CAAC,EAAE,QAAQ,CAAC;KACnB;CACJ;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,cAAmB,EAAE,mBAAmB,EAAE,EAAE,2BAA2B,GAAG,cAAc,CA8DrI"} \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/bearerAuth.js b/dist/esm/server/auth/middleware/bearerAuth.js deleted file mode 100644 index 0c527b4f42..0000000000 --- a/dist/esm/server/auth/middleware/bearerAuth.js +++ /dev/null @@ -1,72 +0,0 @@ -import { InsufficientScopeError, InvalidTokenError, OAuthError, ServerError } from '../errors.js'; -/** - * Middleware that requires a valid Bearer token in the Authorization header. - * - * This will validate the token with the auth provider and add the resulting auth info to the request object. - * - * If resourceMetadataUrl is provided, it will be included in the WWW-Authenticate header - * for 401 responses as per the OAuth 2.0 Protected Resource Metadata spec. - */ -export function requireBearerAuth({ verifier, requiredScopes = [], resourceMetadataUrl }) { - return async (req, res, next) => { - try { - const authHeader = req.headers.authorization; - if (!authHeader) { - throw new InvalidTokenError('Missing Authorization header'); - } - const [type, token] = authHeader.split(' '); - if (type.toLowerCase() !== 'bearer' || !token) { - throw new InvalidTokenError("Invalid Authorization header format, expected 'Bearer TOKEN'"); - } - const authInfo = await verifier.verifyAccessToken(token); - // Check if token has the required scopes (if any) - if (requiredScopes.length > 0) { - const hasAllScopes = requiredScopes.every(scope => authInfo.scopes.includes(scope)); - if (!hasAllScopes) { - throw new InsufficientScopeError('Insufficient scope'); - } - } - // Check if the token is set to expire or if it is expired - if (typeof authInfo.expiresAt !== 'number' || isNaN(authInfo.expiresAt)) { - throw new InvalidTokenError('Token has no expiration time'); - } - else if (authInfo.expiresAt < Date.now() / 1000) { - throw new InvalidTokenError('Token has expired'); - } - req.auth = authInfo; - next(); - } - catch (error) { - // Build WWW-Authenticate header parts - const buildWwwAuthHeader = (errorCode, message) => { - let header = `Bearer error="${errorCode}", error_description="${message}"`; - if (requiredScopes.length > 0) { - header += `, scope="${requiredScopes.join(' ')}"`; - } - if (resourceMetadataUrl) { - header += `, resource_metadata="${resourceMetadataUrl}"`; - } - return header; - }; - if (error instanceof InvalidTokenError) { - res.set('WWW-Authenticate', buildWwwAuthHeader(error.errorCode, error.message)); - res.status(401).json(error.toResponseObject()); - } - else if (error instanceof InsufficientScopeError) { - res.set('WWW-Authenticate', buildWwwAuthHeader(error.errorCode, error.message)); - res.status(403).json(error.toResponseObject()); - } - else if (error instanceof ServerError) { - res.status(500).json(error.toResponseObject()); - } - else if (error instanceof OAuthError) { - res.status(400).json(error.toResponseObject()); - } - else { - const serverError = new ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - } - }; -} -//# sourceMappingURL=bearerAuth.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/bearerAuth.js.map b/dist/esm/server/auth/middleware/bearerAuth.js.map deleted file mode 100644 index d8d0179b76..0000000000 --- a/dist/esm/server/auth/middleware/bearerAuth.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"bearerAuth.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/bearerAuth.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AA8BlG;;;;;;;GAOG;AACH,MAAM,UAAU,iBAAiB,CAAC,EAAE,QAAQ,EAAE,cAAc,GAAG,EAAE,EAAE,mBAAmB,EAA+B;IACjH,OAAO,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QAC5B,IAAI,CAAC;YACD,MAAM,UAAU,GAAG,GAAG,CAAC,OAAO,CAAC,aAAa,CAAC;YAC7C,IAAI,CAAC,UAAU,EAAE,CAAC;gBACd,MAAM,IAAI,iBAAiB,CAAC,8BAA8B,CAAC,CAAC;YAChE,CAAC;YAED,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;YAC5C,IAAI,IAAI,CAAC,WAAW,EAAE,KAAK,QAAQ,IAAI,CAAC,KAAK,EAAE,CAAC;gBAC5C,MAAM,IAAI,iBAAiB,CAAC,8DAA8D,CAAC,CAAC;YAChG,CAAC;YAED,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AAO,MAAM,CAAC;YAClB,CAAC,CAAC;YAEF,IAAI,KAAK,YAAY,iBAAiB,EAAE,CAAC;gBACrC,GAAG,CAAC,GAAG,CAAC,kBAAkB,EAAE,kBAAkB,CAAC,KAAK,CAAC,SAAS,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;gBAChF,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACnD,CAAC;iBAAM,IAAI,KAAK,YAAY,sBAAsB,EAAE,CAAC;gBACjD,GAAG,CAAC,GAAG,CAAC,kBAAkB,EAAE,kBAAkB,CAAC,KAAK,CAAC,SAAS,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC;gBAChF,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACnD,CAAC;iBAAM,IAAI,KAAK,YAAY,WAAW,EAAE,CAAC;gBACtC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACnD,CAAC;iBAAM,IAAI,KAAK,YAAY,UAAU,EAAE,CAAC;gBACrC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACnD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,WAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/clientAuth.d.ts b/dist/esm/server/auth/middleware/clientAuth.d.ts deleted file mode 100644 index 837f95fd29..0000000000 --- a/dist/esm/server/auth/middleware/clientAuth.d.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { RequestHandler } from 'express'; -import { OAuthRegisteredClientsStore } from '../clients.js'; -import { OAuthClientInformationFull } from '../../../shared/auth.js'; -export type ClientAuthenticationMiddlewareOptions = { - /** - * A store used to read information about registered OAuth clients. - */ - clientsStore: OAuthRegisteredClientsStore; -}; -declare module 'express-serve-static-core' { - interface Request { - /** - * The authenticated client for this request, if the `authenticateClient` middleware was used. - */ - client?: OAuthClientInformationFull; - } -} -export declare function authenticateClient({ clientsStore }: ClientAuthenticationMiddlewareOptions): RequestHandler; -//# sourceMappingURL=clientAuth.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/clientAuth.d.ts.map b/dist/esm/server/auth/middleware/clientAuth.d.ts.map deleted file mode 100644 index 5dfa3924f2..0000000000 --- a/dist/esm/server/auth/middleware/clientAuth.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"clientAuth.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/clientAuth.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EAAE,0BAA0B,EAAE,MAAM,yBAAyB,CAAC;AAGrE,MAAM,MAAM,qCAAqC,GAAG;IAChD;;OAEG;IACH,YAAY,EAAE,2BAA2B,CAAC;CAC7C,CAAC;AAOF,OAAO,QAAQ,2BAA2B,CAAC;IACvC,UAAU,OAAO;QACb;;WAEG;QACH,MAAM,CAAC,EAAE,0BAA0B,CAAC;KACvC;CACJ;AAED,wBAAgB,kBAAkB,CAAC,EAAE,YAAY,EAAE,EAAE,qCAAqC,GAAG,cAAc,CA4C1G"} \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/clientAuth.js b/dist/esm/server/auth/middleware/clientAuth.js deleted file mode 100644 index 04e5dfe74c..0000000000 --- a/dist/esm/server/auth/middleware/clientAuth.js +++ /dev/null @@ -1,49 +0,0 @@ -import * as z from 'zod/v4'; -import { InvalidRequestError, InvalidClientError, ServerError, OAuthError } from '../errors.js'; -const ClientAuthenticatedRequestSchema = z.object({ - client_id: z.string(), - client_secret: z.string().optional() -}); -export function authenticateClient({ clientsStore }) { - return async (req, res, next) => { - try { - const result = ClientAuthenticatedRequestSchema.safeParse(req.body); - if (!result.success) { - throw new InvalidRequestError(String(result.error)); - } - const { client_id, client_secret } = result.data; - const client = await clientsStore.getClient(client_id); - if (!client) { - throw new InvalidClientError('Invalid client_id'); - } - // If client has a secret, validate it - if (client.client_secret) { - // Check if client_secret is required but not provided - if (!client_secret) { - throw new InvalidClientError('Client secret is required'); - } - // Check if client_secret matches - if (client.client_secret !== client_secret) { - throw new InvalidClientError('Invalid client_secret'); - } - // Check if client_secret has expired - if (client.client_secret_expires_at && client.client_secret_expires_at < Math.floor(Date.now() / 1000)) { - throw new InvalidClientError('Client secret has expired'); - } - } - req.client = client; - next(); - } - catch (error) { - if (error instanceof OAuthError) { - const status = error instanceof ServerError ? 500 : 400; - res.status(status).json(error.toResponseObject()); - } - else { - const serverError = new ServerError('Internal Server Error'); - res.status(500).json(serverError.toResponseObject()); - } - } - }; -} -//# sourceMappingURL=clientAuth.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/middleware/clientAuth.js.map b/dist/esm/server/auth/middleware/clientAuth.js.map deleted file mode 100644 index a5f969f941..0000000000 --- a/dist/esm/server/auth/middleware/clientAuth.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"clientAuth.js","sourceRoot":"","sources":["../../../../../src/server/auth/middleware/clientAuth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAI5B,OAAO,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAShG,MAAM,gCAAgC,GAAG,CAAC,CAAC,MAA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kB,CAAC,2BAA2B,CAAC,CAAC;gBAC9D,CAAC;YACL,CAAC;YAED,GAAG,CAAC,MAAM,GAAG,MAAM,CAAC;YACpB,IAAI,EAAE,CAAC;QACX,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,IAAI,KAAK,YAAY,UAAU,EAAE,CAAC;gBAC9B,MAAM,MAAM,GAAG,KAAK,YAAY,WAAW,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;gBACxD,GAAG,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACtD,CAAC;iBAAM,CAAC;gBACJ,MAAM,WAAW,GAAG,IAAI,WAAW,CAAC,uBAAuB,CAAC,CAAC;gBAC7D,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,EAAE,CAAC,CAAC;YACzD,CAAC;QACL,CAAC;IACL,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/provider.d.ts b/dist/esm/server/auth/provider.d.ts deleted file mode 100644 index 3e4eca392c..0000000000 --- a/dist/esm/server/auth/provider.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { Response } from 'express'; -import { OAuthRegisteredClientsStore } from './clients.js'; -import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../shared/auth.js'; -import { AuthInfo } from './types.js'; -export type AuthorizationParams = { - state?: string; - scopes?: string[]; - codeChallenge: string; - redirectUri: string; - resource?: URL; -}; -/** - * Implements an end-to-end OAuth server. - */ -export interface OAuthServerProvider { - /** - * A store used to read information about registered OAuth clients. - */ - get clientsStore(): OAuthRegisteredClientsStore; - /** - * Begins the authorization flow, which can either be implemented by this server itself or via redirection to a separate authorization server. - * - * This server must eventually issue a redirect with an authorization response or an error response to the given redirect URI. Per OAuth 2.1: - * - In the successful case, the redirect MUST include the `code` and `state` (if present) query parameters. - * - In the error case, the redirect MUST include the `error` query parameter, and MAY include an optional `error_description` query parameter. - */ - authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; - /** - * Returns the `codeChallenge` that was used when the indicated authorization began. - */ - challengeForAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string): Promise; - /** - * Exchanges an authorization code for an access token. - */ - exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, redirectUri?: string, resource?: URL): Promise; - /** - * Exchanges a refresh token for an access token. - */ - exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; - /** - * Verifies an access token and returns information about it. - */ - verifyAccessToken(token: string): Promise; - /** - * Revokes an access or refresh token. If unimplemented, token revocation is not supported (not recommended). - * - * If the given token is invalid or already revoked, this method should do nothing. - */ - revokeToken?(client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest): Promise; - /** - * Whether to skip local PKCE validation. - * - * If true, the server will not perform PKCE validation locally and will pass the code_verifier to the upstream server. - * - * NOTE: This should only be true if the upstream server is performing the actual PKCE validation. - */ - skipLocalPkceValidation?: boolean; -} -/** - * Slim implementation useful for token verification - */ -export interface OAuthTokenVerifier { - /** - * Verifies an access token and returns information about it. - */ - verifyAccessToken(token: string): Promise; -} -//# sourceMappingURL=provider.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/provider.d.ts.map b/dist/esm/server/auth/provider.d.ts.map deleted file mode 100644 index d1a4bfff0b..0000000000 --- a/dist/esm/server/auth/provider.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,2BAA2B,EAAE,WAAW,EAAE,MAAM,sBAA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EtG;;;;;;OAMG;IACH,uBAAuB,CAAC,EAAE,OAAO,CAAC;CACrC;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IAC/B;;OAEG;IACH,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CACvD"} \ No newline at end of file diff --git a/dist/esm/server/auth/provider.js b/dist/esm/server/auth/provider.js deleted file mode 100644 index be31058cd5..0000000000 --- a/dist/esm/server/auth/provider.js +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=provider.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/provider.js.map b/dist/esm/server/auth/provider.js.map deleted file mode 100644 index b968414aa9..0000000000 --- a/dist/esm/server/auth/provider.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../../../src/server/auth/provider.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/server/auth/providers/proxyProvider.d.ts b/dist/esm/server/auth/providers/proxyProvider.d.ts deleted file mode 100644 index ee6f350817..0000000000 --- a/dist/esm/server/auth/providers/proxyProvider.d.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Response } from 'express'; -import { OAuthRegisteredClientsStore } from '../clients.js'; -import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../../shared/auth.js'; -import { AuthInfo } from '../types.js'; -import { AuthorizationParams, OAuthServerProvider } from '../provider.js'; -import { FetchLike } from '../../../shared/transport.js'; -export type ProxyEndpoints = { - authorizationUrl: string; - tokenUrl: string; - revocationUrl?: string; - registrationUrl?: string; -}; -export type ProxyOptions = { - /** - * Individual endpoint URLs for proxying specific OAuth operations - */ - endpoints: ProxyEndpoints; - /** - * Function to verify access tokens and return auth info - */ - verifyAccessToken: (token: string) => Promise; - /** - * Function to fetch client information from the upstream server - */ - getClient: (clientId: string) => Promise; - /** - * Custom fetch implementation used for all network requests. - */ - fetch?: FetchLike; -}; -/** - * Implements an OAuth server that proxies requests to another OAuth server. - */ -export declare class ProxyOAuthServerProvider implements OAuthServerProvider { - protected readonly _endpoints: ProxyEndpoints; - protected readonly _verifyAccessToken: (token: string) => Promise; - protected readonly _getClient: (clientId: string) => Promise; - protected readonly _fetch?: FetchLike; - skipLocalPkceValidation: boolean; - revokeToken?: (client: OAuthClientInformationFull, request: OAuthTokenRevocationRequest) => Promise; - constructor(options: ProxyOptions); - get clientsStore(): OAuthRegisteredClientsStore; - authorize(client: OAuthClientInformationFull, params: AuthorizationParams, res: Response): Promise; - challengeForAuthorizationCode(_client: OAuthClientInformationFull, _authorizationCode: string): Promise; - exchangeAuthorizationCode(client: OAuthClientInformationFull, authorizationCode: string, codeVerifier?: string, redirectUri?: string, resource?: URL): Promise; - exchangeRefreshToken(client: OAuthClientInformationFull, refreshToken: string, scopes?: string[], resource?: URL): Promise; - verifyAccessToken(token: string): Promise; -} -//# sourceMappingURL=proxyProvider.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/providers/proxyProvider.d.ts.map b/dist/esm/server/auth/providers/proxyProvider.d.ts.map deleted file mode 100644 index ba2efd1aab..0000000000 --- a/dist/esm/server/auth/providers/proxyProvider.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"proxyProvider.d.ts","sourceRoot":"","sources":["../../../../../src/server/auth/providers/proxyProvider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,2BAA2B,EAAE,MAAM,eAAe,CAAC;AAC5D,OAAO,EACH,0BAA0B,EAE1B,2BAA2B,EAC3B,WAAW,EAEd,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE1E,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAEzD,MAAM,MAAM,cAAc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C,OAAO,EAAE,0BAA0B,EAAE,kBAAkB,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAM/G,yBAAyB,CAC3B,MAAM,EAAE,0BAA0B,EAClC,iBAAiB,EAAE,MAAM,EACzB,YAAY,CAAC,EAAE,MAAM,EACrB,WAAW,CAAC,EAAE,MAAM,EACpB,QAAQ,CAAC,EAAE,GAAG,GACf,OAAO,CAAC,WAAW,CAAC;IAuCjB,oBAAoB,CACtB,MAAM,EAAE,0BAA0B,EAClC,YAAY,EAAE,MAAM,EACpB,MAAM,CAAC,EAAE,MAAM,EAAE,EACjB,QAAQ,CAAC,EAAE,GAAG,GACf,OAAO,CAAC,WAAW,CAAC;IAmCjB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC;CAG5D"} \ No newline at end of file diff --git a/dist/esm/server/auth/providers/proxyProvider.js b/dist/esm/server/auth/providers/proxyProvider.js deleted file mode 100644 index 40fb0f1cb7..0000000000 --- a/dist/esm/server/auth/providers/proxyProvider.js +++ /dev/null @@ -1,157 +0,0 @@ -import { OAuthClientInformationFullSchema, OAuthTokensSchema } from '../../../shared/auth.js'; -import { ServerError } from '../errors.js'; -/** - * Implements an OAuth server that proxies requests to another OAuth server. - */ -export class ProxyOAuthServerProvider { - constructor(options) { - var _a; - this.skipLocalPkceValidation = true; - this._endpoints = options.endpoints; - this._verifyAccessToken = options.verifyAccessToken; - this._getClient = options.getClient; - this._fetch = options.fetch; - if ((_a = options.endpoints) === null || _a === void 0 ? void 0 : _a.revocationUrl) { - this.revokeToken = async (client, request) => { - var _a; - const revocationUrl = this._endpoints.revocationUrl; - if (!revocationUrl) { - throw new Error('No revocation endpoint configured'); - } - const params = new URLSearchParams(); - params.set('token', request.token); - params.set('client_id', client.client_id); - if (client.client_secret) { - params.set('client_secret', client.client_secret); - } - if (request.token_type_hint) { - params.set('token_type_hint', request.token_type_hint); - } - const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(revocationUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: params.toString() - }); - if (!response.ok) { - throw new ServerError(`Token revocation failed: ${response.status}`); - } - }; - } - } - get clientsStore() { - const registrationUrl = this._endpoints.registrationUrl; - return { - getClient: this._getClient, - ...(registrationUrl && { - registerClient: async (client) => { - var _a; - const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(registrationUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify(client) - }); - if (!response.ok) { - throw new ServerError(`Client registration failed: ${response.status}`); - } - const data = await response.json(); - return OAuthClientInformationFullSchema.parse(data); - } - }) - }; - } - async authorize(client, params, res) { - var _a; - // Start with required OAuth parameters - const targetUrl = new URL(this._endpoints.authorizationUrl); - const searchParams = new URLSearchParams({ - client_id: client.client_id, - response_type: 'code', - redirect_uri: params.redirectUri, - code_challenge: params.codeChallenge, - code_challenge_method: 'S256' - }); - // Add optional standard OAuth parameters - if (params.state) - searchParams.set('state', params.state); - if ((_a = params.scopes) === null || _a === void 0 ? void 0 : _a.length) - searchParams.set('scope', params.scopes.join(' ')); - if (params.resource) - searchParams.set('resource', params.resource.href); - targetUrl.search = searchParams.toString(); - res.redirect(targetUrl.toString()); - } - async challengeForAuthorizationCode(_client, _authorizationCode) { - // In a proxy setup, we don't store the code challenge ourselves - // Instead, we proxy the token request and let the upstream server validate it - return ''; - } - async exchangeAuthorizationCode(client, authorizationCode, codeVerifier, redirectUri, resource) { - var _a; - const params = new URLSearchParams({ - grant_type: 'authorization_code', - client_id: client.client_id, - code: authorizationCode - }); - if (client.client_secret) { - params.append('client_secret', client.client_secret); - } - if (codeVerifier) { - params.append('code_verifier', codeVerifier); - } - if (redirectUri) { - params.append('redirect_uri', redirectUri); - } - if (resource) { - params.append('resource', resource.href); - } - const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(this._endpoints.tokenUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: params.toString() - }); - if (!response.ok) { - throw new ServerError(`Token exchange failed: ${response.status}`); - } - const data = await response.json(); - return OAuthTokensSchema.parse(data); - } - async exchangeRefreshToken(client, refreshToken, scopes, resource) { - var _a; - const params = new URLSearchParams({ - grant_type: 'refresh_token', - client_id: client.client_id, - refresh_token: refreshToken - }); - if (client.client_secret) { - params.set('client_secret', client.client_secret); - } - if (scopes === null || scopes === void 0 ? void 0 : scopes.length) { - params.set('scope', scopes.join(' ')); - } - if (resource) { - params.set('resource', resource.href); - } - const response = await ((_a = this._fetch) !== null && _a !== void 0 ? _a : fetch)(this._endpoints.tokenUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: params.toString() - }); - if (!response.ok) { - throw new ServerError(`Token refresh failed: ${response.status}`); - } - const data = await response.json(); - return OAuthTokensSchema.parse(data); - } - async verifyAccessToken(token) { - return this._verifyAccessToken(token); - } -} -//# sourceMappingURL=proxyProvider.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/providers/proxyProvider.js.map b/dist/esm/server/auth/providers/proxyProvider.js.map deleted file mode 100644 index 896667e58f..0000000000 --- a/dist/esm/server/auth/providers/proxyProvider.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"proxyProvider.js","sourceRoot":"","sources":["../../../../../src/server/auth/providers/proxyProvider.ts"],"names":[],"mappings":"AAEA,OAAO,EAEH,gCAAgC,EAGhC,iBAAiB,EACpB,MAAM,yBAAyB,CAAC;AAGjC,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAgC3C;;GAEG;AACH,MAAM,OAAO,wBAAwB;IAUjC,YAAY,OAAqB;;QAJjC,4BAAuB,GAAG,IAAI,CAAC;QAK3B,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC;QACpC,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,iBAAiB,CAAC;QACpD,IAAI,CAAC,UAAU,GAAG,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,GAAG,MAAM,CAAC,MAAA,IAAI,CAAC,MAAM,mCAAI,KAAK,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE;YACpE,MAAM,EAAE,MAAM;YACd,OAAO,EAAE;gBACL,cAAc,EAAE,mCAAmC;aACtD;YACD,IAAI,EAAE,MAAM,CAAC,QAAQ,EAAE;SAC1B,CAAC,CAAC;QAEH,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACf,MAAM,IAAI,WAAW,CAAC,yBAAyB,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;QACtE,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,OAAO,iBAAiB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACzC,CAAC;IAED,KAAK,CAAC,iBAAiB,CAAC,KAAa;QACjC,OAAO,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/server/auth/router.d.ts b/dist/esm/server/auth/router.d.ts deleted file mode 100644 index 43dabde7d2..0000000000 --- a/dist/esm/server/auth/router.d.ts +++ /dev/null @@ -1,101 +0,0 @@ -import express, { RequestHandler } from 'express'; -import { ClientRegistrationHandlerOptions } from './handlers/register.js'; -import { TokenHandlerOptions } from './handlers/token.js'; -import { AuthorizationHandlerOptions } from './handlers/authorize.js'; -import { RevocationHandlerOptions } from './handlers/revoke.js'; -import { OAuthServerProvider } from './provider.js'; -import { OAuthMetadata } from '../../shared/auth.js'; -export type AuthRouterOptions = { - /** - * A provider implementing the actual authorization logic for this router. - */ - provider: OAuthServerProvider; - /** - * The authorization server's issuer identifier, which is a URL that uses the "https" scheme and has no query or fragment components. - */ - issuerUrl: URL; - /** - * The base URL of the authorization server to use for the metadata endpoints. - * - * If not provided, the issuer URL will be used as the base URL. - */ - baseUrl?: URL; - /** - * An optional URL of a page containing human-readable information that developers might want or need to know when using the authorization server. - */ - serviceDocumentationUrl?: URL; - /** - * An optional list of scopes supported by this authorization server - */ - scopesSupported?: string[]; - /** - * The resource name to be displayed in protected resource metadata - */ - resourceName?: string; - /** - * The URL of the protected resource (RS) whose metadata we advertise. - * If not provided, falls back to `baseUrl` and then to `issuerUrl` (AS=RS). - */ - resourceServerUrl?: URL; - authorizationOptions?: Omit; - clientRegistrationOptions?: Omit; - revocationOptions?: Omit; - tokenOptions?: Omit; -}; -export declare const createOAuthMetadata: (options: { - provider: OAuthServerProvider; - issuerUrl: URL; - baseUrl?: URL; - serviceDocumentationUrl?: URL; - scopesSupported?: string[]; -}) => OAuthMetadata; -/** - * Installs standard MCP authorization server endpoints, including dynamic client registration and token revocation (if supported). - * Also advertises standard authorization server metadata, for easier discovery of supported configurations by clients. - * Note: if your MCP server is only a resource server and not an authorization server, use mcpAuthMetadataRouter instead. - * - * By default, rate limiting is applied to all endpoints to prevent abuse. - * - * This router MUST be installed at the application root, like so: - * - * const app = express(); - * app.use(mcpAuthRouter(...)); - */ -export declare function mcpAuthRouter(options: AuthRouterOptions): RequestHandler; -export type AuthMetadataOptions = { - /** - * OAuth Metadata as would be returned from the authorization server - * this MCP server relies on - */ - oauthMetadata: OAuthMetadata; - /** - * The url of the MCP server, for use in protected resource metadata - */ - resourceServerUrl: URL; - /** - * The url for documentation for the MCP server - */ - serviceDocumentationUrl?: URL; - /** - * An optional list of scopes supported by this MCP server - */ - scopesSupported?: string[]; - /** - * An optional resource name to display in resource metadata - */ - resourceName?: string; -}; -export declare function mcpAuthMetadataRouter(options: AuthMetadataOptions): express.Router; -/** - * Helper function to construct the OAuth 2.0 Protected Resource Metadata URL - * from a given server URL. This replaces the path with the standard metadata endpoint. - * - * @param serverUrl - The base URL of the protected resource server - * @returns The URL for the OAuth protected resource metadata endpoint - * - * @example - * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) - * // Returns: 'https://api.example.com/.well-known/oauth-protected-resource/mcp' - */ -export declare function getOAuthProtectedResourceMetadataUrl(serverUrl: URL): string; -//# sourceMappingURL=router.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/router.d.ts.map b/dist/esm/server/auth/router.d.ts.map deleted file mode 100644 index 54e90be267..0000000000 --- a/dist/esm/server/auth/router.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/router.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,EAAE,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAA6B,gCAAgC,EAAE,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAgB,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAAwB,2BAA2B,EAAE,MAAM,yBAAyB,CAAC;AAC5F,OAAO,EAAqB,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAEnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,EAAE,aAAa,EAAkC,MAAM,sBAAsB,CAAC;AAErF,MAAM,MAAM,iBAAiB,GAAG;IAC5B;;OAEG;IACH,QAAQ,EAAE,mBAAmB,CAAC;IAE9B;;OAEG;IACH,SAAS,EAAE,GAAG,CAAC;IAEf;;;;OAIG;IACH,OAAO,CAAC,EAAE,GAAG,CAAC;IAEd;;OAEG;IACH,uBAAuB,CAAC,EAAE,GAAG,CAAC;IAE9B;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAE3B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;OAGG;IACH,iBAAiB,CAAC,EAAE,GAAG,CAAC;IAGxB,oBAAoB,CAAC,EAAE,IAAI,CAAC,2BAA2B,EAAE,UAAU,CAAC,CAAC;IACrE,yBAAyB,CAAC,EAAE,IAAI,CAAC,gCAAgC,EAAE,cAAc,CAAC,CAAC;IACnF,iBAAiB,CAAC,EAAE,IAAI,CAAC,wBAAwB,EAAE,UAAU,CAAC,CAAC;IAC/D,YAAY,CAAC,EAAE,IAAI,CAAC,mBAAmB,EAAE,UAAU,CAAC,CAAC;CACxD,CAAC;AAeF,eAAO,MAAM,mBAAmB,YAAa;IACzC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,SAAS,EAAE,GAAG,CAAC;IACf,OAAO,CAAC,EAAE,GAAG,CAAC;IACd,uBAAuB,CAAC,EAAE,GAAG,CAAC;IAC9B,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;CAC9B,KAAG,aAgCH,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,iBAAiB,GAAG,cAAc,CAyCxE;AAED,MAAM,MAAM,mBAAmB,GAAG;IAC9B;;;OAGG;IACH,aAAa,EAAE,aAAa,CAAC;IAE7B;;OAEG;IACH,iBAAiB,EAAE,GAAG,CAAC;IAEvB;;OAEG;IACH,uBAAuB,CAAC,EAAE,GAAG,CAAC;IAE9B;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAE3B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACzB,CAAC;AAEF,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,MAAM,CAuBlF;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,oCAAoC,CAAC,SAAS,EAAE,GAAG,GAAG,MAAM,CAI3E"} \ No newline at end of file diff --git a/dist/esm/server/auth/router.js b/dist/esm/server/auth/router.js deleted file mode 100644 index ff72f643f3..0000000000 --- a/dist/esm/server/auth/router.js +++ /dev/null @@ -1,115 +0,0 @@ -import express from 'express'; -import { clientRegistrationHandler } from './handlers/register.js'; -import { tokenHandler } from './handlers/token.js'; -import { authorizationHandler } from './handlers/authorize.js'; -import { revocationHandler } from './handlers/revoke.js'; -import { metadataHandler } from './handlers/metadata.js'; -const checkIssuerUrl = (issuer) => { - // Technically RFC 8414 does not permit a localhost HTTPS exemption, but this will be necessary for ease of testing - if (issuer.protocol !== 'https:' && issuer.hostname !== 'localhost' && issuer.hostname !== '127.0.0.1') { - throw new Error('Issuer URL must be HTTPS'); - } - if (issuer.hash) { - throw new Error(`Issuer URL must not have a fragment: ${issuer}`); - } - if (issuer.search) { - throw new Error(`Issuer URL must not have a query string: ${issuer}`); - } -}; -export const createOAuthMetadata = (options) => { - var _a; - const issuer = options.issuerUrl; - const baseUrl = options.baseUrl; - checkIssuerUrl(issuer); - const authorization_endpoint = '/authorize'; - const token_endpoint = '/token'; - const registration_endpoint = options.provider.clientsStore.registerClient ? '/register' : undefined; - const revocation_endpoint = options.provider.revokeToken ? '/revoke' : undefined; - const metadata = { - issuer: issuer.href, - service_documentation: (_a = options.serviceDocumentationUrl) === null || _a === void 0 ? void 0 : _a.href, - authorization_endpoint: new URL(authorization_endpoint, baseUrl || issuer).href, - response_types_supported: ['code'], - code_challenge_methods_supported: ['S256'], - token_endpoint: new URL(token_endpoint, baseUrl || issuer).href, - token_endpoint_auth_methods_supported: ['client_secret_post', 'none'], - grant_types_supported: ['authorization_code', 'refresh_token'], - scopes_supported: options.scopesSupported, - revocation_endpoint: revocation_endpoint ? new URL(revocation_endpoint, baseUrl || issuer).href : undefined, - revocation_endpoint_auth_methods_supported: revocation_endpoint ? ['client_secret_post'] : undefined, - registration_endpoint: registration_endpoint ? new URL(registration_endpoint, baseUrl || issuer).href : undefined - }; - return metadata; -}; -/** - * Installs standard MCP authorization server endpoints, including dynamic client registration and token revocation (if supported). - * Also advertises standard authorization server metadata, for easier discovery of supported configurations by clients. - * Note: if your MCP server is only a resource server and not an authorization server, use mcpAuthMetadataRouter instead. - * - * By default, rate limiting is applied to all endpoints to prevent abuse. - * - * This router MUST be installed at the application root, like so: - * - * const app = express(); - * app.use(mcpAuthRouter(...)); - */ -export function mcpAuthRouter(options) { - var _a, _b; - const oauthMetadata = createOAuthMetadata(options); - const router = express.Router(); - router.use(new URL(oauthMetadata.authorization_endpoint).pathname, authorizationHandler({ provider: options.provider, ...options.authorizationOptions })); - router.use(new URL(oauthMetadata.token_endpoint).pathname, tokenHandler({ provider: options.provider, ...options.tokenOptions })); - router.use(mcpAuthMetadataRouter({ - oauthMetadata, - // Prefer explicit RS; otherwise fall back to AS baseUrl, then to issuer (back-compat) - resourceServerUrl: (_b = (_a = options.resourceServerUrl) !== null && _a !== void 0 ? _a : options.baseUrl) !== null && _b !== void 0 ? _b : new URL(oauthMetadata.issuer), - serviceDocumentationUrl: options.serviceDocumentationUrl, - scopesSupported: options.scopesSupported, - resourceName: options.resourceName - })); - if (oauthMetadata.registration_endpoint) { - router.use(new URL(oauthMetadata.registration_endpoint).pathname, clientRegistrationHandler({ - clientsStore: options.provider.clientsStore, - ...options.clientRegistrationOptions - })); - } - if (oauthMetadata.revocation_endpoint) { - router.use(new URL(oauthMetadata.revocation_endpoint).pathname, revocationHandler({ provider: options.provider, ...options.revocationOptions })); - } - return router; -} -export function mcpAuthMetadataRouter(options) { - var _a; - checkIssuerUrl(new URL(options.oauthMetadata.issuer)); - const router = express.Router(); - const protectedResourceMetadata = { - resource: options.resourceServerUrl.href, - authorization_servers: [options.oauthMetadata.issuer], - scopes_supported: options.scopesSupported, - resource_name: options.resourceName, - resource_documentation: (_a = options.serviceDocumentationUrl) === null || _a === void 0 ? void 0 : _a.href - }; - // Serve PRM at the path-specific URL per RFC 9728 - const rsPath = new URL(options.resourceServerUrl.href).pathname; - router.use(`/.well-known/oauth-protected-resource${rsPath === '/' ? '' : rsPath}`, metadataHandler(protectedResourceMetadata)); - // Always add this for OAuth Authorization Server metadata per RFC 8414 - router.use('/.well-known/oauth-authorization-server', metadataHandler(options.oauthMetadata)); - return router; -} -/** - * Helper function to construct the OAuth 2.0 Protected Resource Metadata URL - * from a given server URL. This replaces the path with the standard metadata endpoint. - * - * @param serverUrl - The base URL of the protected resource server - * @returns The URL for the OAuth protected resource metadata endpoint - * - * @example - * getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) - * // Returns: 'https://api.example.com/.well-known/oauth-protected-resource/mcp' - */ -export function getOAuthProtectedResourceMetadataUrl(serverUrl) { - const u = new URL(serverUrl.href); - const rsPath = u.pathname && u.pathname !== '/' ? u.pathname : ''; - return new URL(`/.well-known/oauth-protected-resource${rsPath}`, u).href; -} -//# sourceMappingURL=router.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/router.js.map b/dist/esm/server/auth/router.js.map deleted file mode 100644 index 363e49566b..0000000000 --- a/dist/esm/server/auth/router.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"router.js","sourceRoot":"","sources":["../../../../src/server/auth/router.ts"],"names":[],"mappings":"AAAA,OAAO,OAA2B,MAAM,SAAS,CAAC;AAClD,OAAO,EAAE,yBAAyB,EAAoC,MAAM,wBAAwB,CAAC;AACrG,OAAO,EAAE,YAAY,EAAuB,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAAE,oBAAoB,EAA+B,MAAM,yBAAyB,CAAC;AAC5F,OAAO,EAAE,iBAAiB,EAA4B,MAAM,sBAAsB,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAkDzD,MAAM,cAAc,GAAG,CAAC,MAAW,EAAQ,EAAE;IACzC,mHAAmH;IACnH,IAAI,MAAM,CAAC,QAAQ,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,KAAK,WAAW,IAAI,MAAM,CAAC,QAAQ,KAAK,WAAW,EAAE,CAAC;QACrG,MAAM,IAAI,KAAK,CAAC,0BAA0B,CAAC,CAAC;IAChD,CAAC;IACD,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC;QACd,MAAM,IAAI,KAAK,CAAC,wCAAwC,MAAM,EAAE,CAAC,CAAC;IACtE,CAAC;IACD,IAAI,MAAM,CAAC,MAAM,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,4CAA4C,MAAM,EAAE,CAAC,CAAC;IAC1E,CAAC;AACL,CAAC,CAAC;AAEF,MAAM,CAAC,MAA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AAC,yCAAyC,EAAE,eAAe,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC,CAAC;IAE9F,OAAO,MAAM,CAAC;AAClB,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,oCAAoC,CAAC,SAAc;IAC/D,MAAM,CAAC,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IAClC,MAAM,MAAM,GAAG,CAAC,CAAC,QAAQ,IAAI,CAAC,CAAC,QAAQ,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC;IAClE,OAAO,IAAI,GAAG,CAAC,wCAAwC,MAAM,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAC7E,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/auth/types.d.ts b/dist/esm/server/auth/types.d.ts deleted file mode 100644 index 05ec8485a5..0000000000 --- a/dist/esm/server/auth/types.d.ts +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Information about a validated access token, provided to request handlers. - */ -export interface AuthInfo { - /** - * The access token. - */ - token: string; - /** - * The client ID associated with this token. - */ - clientId: string; - /** - * Scopes associated with this token. - */ - scopes: string[]; - /** - * When the token expires (in seconds since epoch). - */ - expiresAt?: number; - /** - * The RFC 8707 resource server identifier for which this token is valid. - * If set, this MUST match the MCP server's resource identifier (minus hash fragment). - */ - resource?: URL; - /** - * Additional data associated with the token. - * This field should be used for any additional data that needs to be attached to the auth info. - */ - extra?: Record; -} -//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/auth/types.d.ts.map b/dist/esm/server/auth/types.d.ts.map deleted file mode 100644 index 021e947401..0000000000 --- a/dist/esm/server/auth/types.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../../src/server/auth/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,QAAQ;IACrB;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IAEd;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,MAAM,EAAE,MAAM,EAAE,CAAC;IAEjB;;OAEG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IAEnB;;;OAGG;IACH,QAAQ,CAAC,EAAE,GAAG,CAAC;IAEf;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC"} \ No newline at end of file diff --git a/dist/esm/server/auth/types.js b/dist/esm/server/auth/types.js deleted file mode 100644 index 718fd38ae4..0000000000 --- a/dist/esm/server/auth/types.js +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/esm/server/auth/types.js.map b/dist/esm/server/auth/types.js.map deleted file mode 100644 index 0d8063dee4..0000000000 --- a/dist/esm/server/auth/types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/server/auth/types.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/dist/esm/server/completable.d.ts b/dist/esm/server/completable.d.ts deleted file mode 100644 index 1b3159ac8f..0000000000 --- a/dist/esm/server/completable.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { AnySchema, SchemaInput } from './zod-compat.js'; -export declare const COMPLETABLE_SYMBOL: unique symbol; -export type CompleteCallback = (value: SchemaInput, context?: { - arguments?: Record; -}) => SchemaInput[] | Promise[]>; -export type CompletableMeta = { - complete: CompleteCallback; -}; -export type CompletableSchema = T & { - [COMPLETABLE_SYMBOL]: CompletableMeta; -}; -/** - * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. - * Works with both Zod v3 and v4 schemas. - */ -export declare function completable(schema: T, complete: CompleteCallback): CompletableSchema; -/** - * Checks if a schema is completable (has completion metadata). - */ -export declare function isCompletable(schema: unknown): schema is CompletableSchema; -/** - * Gets the completer callback from a completable schema, if it exists. - */ -export declare function getCompleter(schema: T): CompleteCallback | undefined; -/** - * Unwraps a completable schema to get the underlying schema. - * For backward compatibility with code that called `.unwrap()`. - */ -export declare function unwrapCompletable(schema: CompletableSchema): T; -export declare enum McpZodTypeKind { - Completable = "McpCompletable" -} -export interface CompletableDef { - type: T; - complete: CompleteCallback; - typeName: McpZodTypeKind.Completable; -} -//# sourceMappingURL=completable.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/completable.d.ts.map b/dist/esm/server/completable.d.ts.map deleted file mode 100644 index 83ea2f1e27..0000000000 --- a/dist/esm/server/completable.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"completable.d.ts","sourceRoot":"","sources":["../../../src/server/completable.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAEzD,eAAO,MAAM,kBAAkB,EAAE,OAAO,MAAsC,CAAC;AAE/E,MAAM,MAAM,gBAAgB,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS,IAAI,CAC5D,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,EACrB,OAAO,CAAC,EAAE;IACN,SAAS,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACtC,KACA,WAAW,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;AAElD,MAAM,MAAM,eAAe,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS,IAAI;IAC3D,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC;CACjC,CAAC;AAEF,MAAM,MAAM,iBAAiB,CAAC,CAAC,SAAS,SAAS,IAAI,CAAC,GAAG;IACrD,CAAC,kBAAkB,CAAC,EAAE,eAAe,CAAC,CAAC,CAAC,CAAC;CAC5C,CAAC;AAEF;;;GAGG;AACH,wBAAgB,WAAW,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,CAAC,EAAE,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,GAAG,iBAAiB,CAAC,CAAC,CAAC,CAQ/G;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,IAAI,iBAAiB,CAAC,SAAS,CAAC,CAErF;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,CAAC,GAAG,gBAAgB,CAAC,CAAC,CAAC,GAAG,SAAS,CAG5F;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,SAAS,EAAE,MAAM,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,CAAC,CAEtF;AAID,oBAAY,cAAc;IACtB,WAAW,mBAAmB;CACjC;AAED,MAAM,WAAW,cAAc,CAAC,CAAC,SAAS,SAAS,GAAG,SAAS;IAC3D,IAAI,EAAE,CAAC,CAAC;IACR,QAAQ,EAAE,gBAAgB,CAAC,CAAC,CAAC,CAAC;IAC9B,QAAQ,EAAE,cAAc,CAAC,WAAW,CAAC;CACxC"} \ No newline at end of file diff --git a/dist/esm/server/completable.js b/dist/esm/server/completable.js deleted file mode 100644 index 4f636e3eaa..0000000000 --- a/dist/esm/server/completable.js +++ /dev/null @@ -1,41 +0,0 @@ -export const COMPLETABLE_SYMBOL = Symbol.for('mcp.completable'); -/** - * Wraps a Zod type to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. - * Works with both Zod v3 and v4 schemas. - */ -export function completable(schema, complete) { - Object.defineProperty(schema, COMPLETABLE_SYMBOL, { - value: { complete }, - enumerable: false, - writable: false, - configurable: false - }); - return schema; -} -/** - * Checks if a schema is completable (has completion metadata). - */ -export function isCompletable(schema) { - return !!schema && typeof schema === 'object' && COMPLETABLE_SYMBOL in schema; -} -/** - * Gets the completer callback from a completable schema, if it exists. - */ -export function getCompleter(schema) { - const meta = schema[COMPLETABLE_SYMBOL]; - return meta === null || meta === void 0 ? void 0 : meta.complete; -} -/** - * Unwraps a completable schema to get the underlying schema. - * For backward compatibility with code that called `.unwrap()`. - */ -export function unwrapCompletable(schema) { - return schema; -} -// Legacy exports for backward compatibility -// These types are deprecated but kept for existing code -export var McpZodTypeKind; -(function (McpZodTypeKind) { - McpZodTypeKind["Completable"] = "McpCompletable"; -})(McpZodTypeKind || (McpZodTypeKind = {})); -//# sourceMappingURL=completable.js.map \ No newline at end of file diff --git a/dist/esm/server/completable.js.map b/dist/esm/server/completable.js.map deleted file mode 100644 index d8700d494b..0000000000 --- a/dist/esm/server/completable.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"completable.js","sourceRoot":"","sources":["../../../src/server/completable.ts"],"names":[],"mappings":"AAEA,MAAM,CAAC,MAAM,kBAAkB,GAAkB,MAAM,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;AAiB/E;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAsB,MAAS,EAAE,QAA6B;IACrF,MAAM,CAAC,cAAc,CAAC,MAAgB,EAAE,kBAAkB,EAAE;QACxD,KAAK,EAAE,EAAE,QAAQ,EAAwB;QACzC,UAAU,EAAE,KAAK;QACjB,QAAQ,EAAE,KAAK;QACf,YAAY,EAAE,KAAK;KACtB,CAAC,CAAC;IACH,OAAO,MAA8B,CAAC;AAC1C,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa,CAAC,MAAe;IACzC,OAAO,CAAC,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,kBAAkB,IAAK,MAAiB,CAAC;AAC9F,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,YAAY,CAAsB,MAAS;IACvD,MAAM,IAAI,GAAI,MAAmE,CAAC,kBAAkB,CAAC,CAAC;IACtG,OAAO,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,QAA2C,CAAC;AAC7D,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAAsB,MAA4B;IAC/E,OAAO,MAAM,CAAC;AAClB,CAAC;AAED,4CAA4C;AAC5C,wDAAwD;AACxD,MAAM,CAAN,IAAY,cAEX;AAFD,WAAY,cAAc;IACtB,gDAA8B,CAAA;AAClC,CAAC,EAFW,cAAc,KAAd,cAAc,QAEzB"} \ No newline at end of file diff --git a/dist/esm/server/index.d.ts b/dist/esm/server/index.d.ts deleted file mode 100644 index 8aabf3c536..0000000000 --- a/dist/esm/server/index.d.ts +++ /dev/null @@ -1,333 +0,0 @@ -import { Protocol, type NotificationOptions, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; -import { type ClientCapabilities, type CreateMessageRequest, type ElicitRequestFormParams, type ElicitRequestURLParams, type ElicitResult, type Implementation, type ListRootsRequest, type LoggingMessageNotification, type Notification, type Request, type ResourceUpdatedNotification, type Result, type ServerCapabilities, type ServerNotification, type ServerRequest, type ServerResult } from '../types.js'; -import type { jsonSchemaValidator } from '../validation/types.js'; -type LegacyElicitRequestFormParams = Omit; -export type ServerOptions = ProtocolOptions & { - /** - * Capabilities to advertise as being supported by this server. - */ - capabilities?: ServerCapabilities; - /** - * Optional instructions describing how to use the server and its features. - */ - instructions?: string; - /** - * JSON Schema validator for elicitation response validation. - * - * The validator is used to validate user input returned from elicitation - * requests against the requested schema. - * - * @default AjvJsonSchemaValidator - * - * @example - * ```typescript - * // ajv (default) - * const server = new Server( - * { name: 'my-server', version: '1.0.0' }, - * { - * capabilities: {} - * jsonSchemaValidator: new AjvJsonSchemaValidator() - * } - * ); - * - * // @cfworker/json-schema - * const server = new Server( - * { name: 'my-server', version: '1.0.0' }, - * { - * capabilities: {}, - * jsonSchemaValidator: new CfWorkerJsonSchemaValidator() - * } - * ); - * ``` - */ - jsonSchemaValidator?: jsonSchemaValidator; -}; -/** - * An MCP server on top of a pluggable transport. - * - * This server will automatically respond to the initialization flow as initiated from the client. - * - * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: - * - * ```typescript - * // Custom schemas - * const CustomRequestSchema = RequestSchema.extend({...}) - * const CustomNotificationSchema = NotificationSchema.extend({...}) - * const CustomResultSchema = ResultSchema.extend({...}) - * - * // Type aliases - * type CustomRequest = z.infer - * type CustomNotification = z.infer - * type CustomResult = z.infer - * - * // Create typed server - * const server = new Server({ - * name: "CustomServer", - * version: "1.0.0" - * }) - * ``` - * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. - */ -export declare class Server extends Protocol { - private _serverInfo; - private _clientCapabilities?; - private _clientVersion?; - private _capabilities; - private _instructions?; - private _jsonSchemaValidator; - /** - * Callback for when initialization has fully completed (i.e., the client has sent an `initialized` notification). - */ - oninitialized?: () => void; - /** - * Initializes this server with the given name and version information. - */ - constructor(_serverInfo: Implementation, options?: ServerOptions); - private _loggingLevels; - private readonly LOG_LEVEL_SEVERITY; - private isMessageIgnored; - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - registerCapabilities(capabilities: ServerCapabilities): void; - protected assertCapabilityForMethod(method: RequestT['method']): void; - protected assertNotificationCapability(method: (ServerNotification | NotificationT)['method']): void; - protected assertRequestHandlerCapability(method: string): void; - private _oninitialize; - /** - * After initialization has completed, this will be populated with the client's reported capabilities. - */ - getClientCapabilities(): ClientCapabilities | undefined; - /** - * After initialization has completed, this will be populated with information about the client's name and version. - */ - getClientVersion(): Implementation | undefined; - private getCapabilities; - ping(): Promise<{ - _meta?: Record | undefined; - }>; - createMessage(params: CreateMessageRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - model: string; - role: "user" | "assistant"; - content: { - type: "text"; - text: string; - _meta?: Record | undefined; - } | { - type: "image"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "audio"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - [x: string]: unknown; - type: "tool_use"; - name: string; - id: string; - input: { - [x: string]: unknown; - }; - _meta?: { - [x: string]: unknown; - } | undefined; - } | { - [x: string]: unknown; - type: "tool_result"; - toolUseId: string; - content: ({ - type: "text"; - text: string; - _meta?: Record | undefined; - } | { - type: "image"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "audio"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "resource"; - resource: { - uri: string; - text: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - } | { - uri: string; - blob: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - }; - _meta?: Record | undefined; - } | { - uri: string; - name: string; - type: "resource_link"; - description?: string | undefined; - mimeType?: string | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - })[]; - structuredContent?: { - [x: string]: unknown; - } | undefined; - isError?: boolean | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - } | ({ - type: "text"; - text: string; - _meta?: Record | undefined; - } | { - type: "image"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "audio"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - [x: string]: unknown; - type: "tool_use"; - name: string; - id: string; - input: { - [x: string]: unknown; - }; - _meta?: { - [x: string]: unknown; - } | undefined; - } | { - [x: string]: unknown; - type: "tool_result"; - toolUseId: string; - content: ({ - type: "text"; - text: string; - _meta?: Record | undefined; - } | { - type: "image"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "audio"; - data: string; - mimeType: string; - _meta?: Record | undefined; - } | { - type: "resource"; - resource: { - uri: string; - text: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - } | { - uri: string; - blob: string; - mimeType?: string | undefined; - _meta?: Record | undefined; - }; - _meta?: Record | undefined; - } | { - uri: string; - name: string; - type: "resource_link"; - description?: string | undefined; - mimeType?: string | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - icons?: { - src: string; - mimeType?: string | undefined; - sizes?: string[] | undefined; - }[] | undefined; - title?: string | undefined; - })[]; - structuredContent?: { - [x: string]: unknown; - } | undefined; - isError?: boolean | undefined; - _meta?: { - [x: string]: unknown; - } | undefined; - })[]; - _meta?: Record | undefined; - stopReason?: string | undefined; - }>; - /** - * Creates an elicitation request for the given parameters. - * @param params The parameters for the form elicitation request (explicit mode: 'form'). - * @param options Optional request options. - * @returns The result of the elicitation request. - */ - elicitInput(params: ElicitRequestFormParams, options?: RequestOptions): Promise; - /** - * Creates an elicitation request for the given parameters. - * @param params The parameters for the URL elicitation request (with url and elicitationId). - * @param options Optional request options. - * @returns The result of the elicitation request. - */ - elicitInput(params: ElicitRequestURLParams, options?: RequestOptions): Promise; - /** - * Creates an elicitation request for the given parameters. - * @deprecated Use the overloads with explicit `mode: 'form' | 'url'` instead. - * @param params The parameters for the form elicitation request (legacy signature without mode). - * @param options Optional request options. - * @returns The result of the elicitation request. - */ - elicitInput(params: LegacyElicitRequestFormParams, options?: RequestOptions): Promise; - /** - * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` - * notification for the specified elicitation ID. - * - * @param elicitationId The ID of the elicitation to mark as complete. - * @param options Optional notification options. Useful when the completion notification should be related to a prior request. - * @returns A function that emits the completion notification when awaited. - */ - createElicitationCompletionNotifier(elicitationId: string, options?: NotificationOptions): () => Promise; - listRoots(params?: ListRootsRequest['params'], options?: RequestOptions): Promise<{ - [x: string]: unknown; - roots: { - uri: string; - name?: string | undefined; - _meta?: Record | undefined; - }[]; - _meta?: Record | undefined; - }>; - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON RPC message - * @see LoggingMessageNotification - * @param params - * @param sessionId optional for stateless and backward compatibility - */ - sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string): Promise; - sendResourceUpdated(params: ResourceUpdatedNotification['params']): Promise; - sendResourceListChanged(): Promise; - sendToolListChanged(): Promise; - sendPromptListChanged(): Promise; -} -export {}; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/index.d.ts.map b/dist/esm/server/index.d.ts.map deleted file mode 100644 index 4b8cc1c0a0..0000000000 --- a/dist/esm/server/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,QAAQ,EAAE,KAAK,mBAAmB,EAAE,KAAK,eAAe,EAAE,KAAK,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACzI,OAAO,EACH,KAAK,kBAAkB,EACvB,KAAK,oBAAoB,EAEzB,KAAK,uBAAuB,EAC5B,KAAK,sBAAsB,EAC3B,KAAK,YAAY,EAIjB,KAAK,cAAc,EAMnB,KAAK,gBAAgB,EAIrB,KAAK,0BAA0B,EAE/B,KAAK,YAAY,EACjB,KAAK,OAAO,EACZ,KAAK,2BAA2B,EAChC,KAAK,MAAM,EACX,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAClB,KAAK,YAAY,EAGpB,MAAM,aAAa,CAAC;AAErB,OAAO,KAAK,EAAkB,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAElF,KAAK,6BAA6B,GAAG,IAAI,CAAC,uBAAuB,EAAE,MAAM,CAAC,CAAC;AAE3E,MAAM,MAAM,aAAa,GAAG,eAAe,GAAG;IAC1C;;OAEG;IACH,YAAY,CAAC,EAAE,kBAAkB,CAAC;IAElC;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACH,mBAAmB,CAAC,EAAE,mBAAmB,CAAC;CAC7C,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,qBAAa,MAAM,CACf,QAAQ,SAAS,OAAO,GAAG,OAAO,EAClC,aAAa,SAAS,YAAY,GAAG,YAAY,EACjD,OAAO,SAAS,MAAM,GAAG,MAAM,CACjC,SAAQ,QAAQ,CAAC,aAAa,GAAG,QAAQ,EAAE,kBAAkB,GAAG,aAAa,E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;;;;;;;;;;;;;;;;;;;;IAIpF;;;;;OAKG;IACG,WAAW,CAAC,MAAM,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC;IACnG;;;;;OAKG;IACG,WAAW,CAAC,MAAM,EAAE,sBAAsB,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC;IAClG;;;;;;OAMG;IACG,WAAW,CAAC,MAAM,EAAE,6BAA6B,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,YAAY,CAAC;IAuDzG;;;;;;;OAOG;IACH,mCAAmC,CAAC,aAAa,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC;IAiBxG,SAAS,CAAC,MAAM,CAAC,EAAE,gBAAgB,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC,EAAE,cAAc;;;;;;;;;IAI7E;;;;;;OAMG;IACG,kBAAkB,CAAC,MAAM,EAAE,0BAA0B,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC,EAAE,MAAM;IAQnF,mBAAmB,CAAC,MAAM,EAAE,2BAA2B,CAAC,QAAQ,CAAC;IAOjE,uBAAuB;IAMvB,mBAAmB;IAInB,qBAAqB;CAG9B"} \ No newline at end of file diff --git a/dist/esm/server/index.js b/dist/esm/server/index.js deleted file mode 100644 index 9a0afd2801..0000000000 --- a/dist/esm/server/index.js +++ /dev/null @@ -1,300 +0,0 @@ -import { mergeCapabilities, Protocol } from '../shared/protocol.js'; -import { CreateMessageResultSchema, ElicitResultSchema, EmptyResultSchema, ErrorCode, InitializedNotificationSchema, InitializeRequestSchema, LATEST_PROTOCOL_VERSION, ListRootsResultSchema, LoggingLevelSchema, McpError, SetLevelRequestSchema, SUPPORTED_PROTOCOL_VERSIONS } from '../types.js'; -import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; -/** - * An MCP server on top of a pluggable transport. - * - * This server will automatically respond to the initialization flow as initiated from the client. - * - * To use with custom types, extend the base Request/Notification/Result types and pass them as type parameters: - * - * ```typescript - * // Custom schemas - * const CustomRequestSchema = RequestSchema.extend({...}) - * const CustomNotificationSchema = NotificationSchema.extend({...}) - * const CustomResultSchema = ResultSchema.extend({...}) - * - * // Type aliases - * type CustomRequest = z.infer - * type CustomNotification = z.infer - * type CustomResult = z.infer - * - * // Create typed server - * const server = new Server({ - * name: "CustomServer", - * version: "1.0.0" - * }) - * ``` - * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. - */ -export class Server extends Protocol { - /** - * Initializes this server with the given name and version information. - */ - constructor(_serverInfo, options) { - var _a, _b; - super(options); - this._serverInfo = _serverInfo; - // Map log levels by session id - this._loggingLevels = new Map(); - // Map LogLevelSchema to severity index - this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); - // Is a message with the given level ignored in the log level set for the given session id? - this.isMessageIgnored = (level, sessionId) => { - const currentLevel = this._loggingLevels.get(sessionId); - return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; - }; - this._capabilities = (_a = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a !== void 0 ? _a : {}; - this._instructions = options === null || options === void 0 ? void 0 : options.instructions; - this._jsonSchemaValidator = (_b = options === null || options === void 0 ? void 0 : options.jsonSchemaValidator) !== null && _b !== void 0 ? _b : new AjvJsonSchemaValidator(); - this.setRequestHandler(InitializeRequestSchema, request => this._oninitialize(request)); - this.setNotificationHandler(InitializedNotificationSchema, () => { var _a; return (_a = this.oninitialized) === null || _a === void 0 ? void 0 : _a.call(this); }); - if (this._capabilities.logging) { - this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => { - var _a; - const transportSessionId = extra.sessionId || ((_a = extra.requestInfo) === null || _a === void 0 ? void 0 : _a.headers['mcp-session-id']) || undefined; - const { level } = request.params; - const parseResult = LoggingLevelSchema.safeParse(level); - if (parseResult.success) { - this._loggingLevels.set(transportSessionId, parseResult.data); - } - return {}; - }); - } - } - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - registerCapabilities(capabilities) { - if (this.transport) { - throw new Error('Cannot register capabilities after connecting to transport'); - } - this._capabilities = mergeCapabilities(this._capabilities, capabilities); - } - assertCapabilityForMethod(method) { - var _a, _b, _c; - switch (method) { - case 'sampling/createMessage': - if (!((_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.sampling)) { - throw new Error(`Client does not support sampling (required for ${method})`); - } - break; - case 'elicitation/create': - if (!((_b = this._clientCapabilities) === null || _b === void 0 ? void 0 : _b.elicitation)) { - throw new Error(`Client does not support elicitation (required for ${method})`); - } - break; - case 'roots/list': - if (!((_c = this._clientCapabilities) === null || _c === void 0 ? void 0 : _c.roots)) { - throw new Error(`Client does not support listing roots (required for ${method})`); - } - break; - case 'ping': - // No specific capability required for ping - break; - } - } - assertNotificationCapability(method) { - var _a, _b; - switch (method) { - case 'notifications/message': - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case 'notifications/resources/updated': - case 'notifications/resources/list_changed': - if (!this._capabilities.resources) { - throw new Error(`Server does not support notifying about resources (required for ${method})`); - } - break; - case 'notifications/tools/list_changed': - if (!this._capabilities.tools) { - throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); - } - break; - case 'notifications/prompts/list_changed': - if (!this._capabilities.prompts) { - throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); - } - break; - case 'notifications/elicitation/complete': - if (!((_b = (_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.elicitation) === null || _b === void 0 ? void 0 : _b.url)) { - throw new Error(`Client does not support URL elicitation (required for ${method})`); - } - break; - case 'notifications/cancelled': - // Cancellation notifications are always allowed - break; - case 'notifications/progress': - // Progress notifications are always allowed - break; - } - } - assertRequestHandlerCapability(method) { - switch (method) { - case 'completion/complete': - if (!this._capabilities.completions) { - throw new Error(`Server does not support completions (required for ${method})`); - } - break; - case 'logging/setLevel': - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case 'prompts/get': - case 'prompts/list': - if (!this._capabilities.prompts) { - throw new Error(`Server does not support prompts (required for ${method})`); - } - break; - case 'resources/list': - case 'resources/templates/list': - case 'resources/read': - if (!this._capabilities.resources) { - throw new Error(`Server does not support resources (required for ${method})`); - } - break; - case 'tools/call': - case 'tools/list': - if (!this._capabilities.tools) { - throw new Error(`Server does not support tools (required for ${method})`); - } - break; - case 'ping': - case 'initialize': - // No specific capability required for these methods - break; - } - } - async _oninitialize(request) { - const requestedVersion = request.params.protocolVersion; - this._clientCapabilities = request.params.capabilities; - this._clientVersion = request.params.clientInfo; - const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION; - return { - protocolVersion, - capabilities: this.getCapabilities(), - serverInfo: this._serverInfo, - ...(this._instructions && { instructions: this._instructions }) - }; - } - /** - * After initialization has completed, this will be populated with the client's reported capabilities. - */ - getClientCapabilities() { - return this._clientCapabilities; - } - /** - * After initialization has completed, this will be populated with information about the client's name and version. - */ - getClientVersion() { - return this._clientVersion; - } - getCapabilities() { - return this._capabilities; - } - async ping() { - return this.request({ method: 'ping' }, EmptyResultSchema); - } - async createMessage(params, options) { - return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultSchema, options); - } - // Implementation (not visible to callers) - async elicitInput(params, options) { - var _a, _b, _c, _d; - const mode = ('mode' in params ? params.mode : 'form'); - switch (mode) { - case 'url': { - if (!((_b = (_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.elicitation) === null || _b === void 0 ? void 0 : _b.url)) { - throw new Error('Client does not support url elicitation.'); - } - const urlParams = params; - return this.request({ method: 'elicitation/create', params: urlParams }, ElicitResultSchema, options); - } - case 'form': { - if (!((_d = (_c = this._clientCapabilities) === null || _c === void 0 ? void 0 : _c.elicitation) === null || _d === void 0 ? void 0 : _d.form)) { - throw new Error('Client does not support form elicitation.'); - } - const formParams = 'mode' in params - ? params - : { ...params, mode: 'form' }; - const result = await this.request({ method: 'elicitation/create', params: formParams }, ElicitResultSchema, options); - if (result.action === 'accept' && result.content && formParams.requestedSchema) { - try { - const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); - const validationResult = validator(result.content); - if (!validationResult.valid) { - throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); - } - } - catch (error) { - if (error instanceof McpError) { - throw error; - } - throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); - } - } - return result; - } - } - } - /** - * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` - * notification for the specified elicitation ID. - * - * @param elicitationId The ID of the elicitation to mark as complete. - * @param options Optional notification options. Useful when the completion notification should be related to a prior request. - * @returns A function that emits the completion notification when awaited. - */ - createElicitationCompletionNotifier(elicitationId, options) { - var _a, _b; - if (!((_b = (_a = this._clientCapabilities) === null || _a === void 0 ? void 0 : _a.elicitation) === null || _b === void 0 ? void 0 : _b.url)) { - throw new Error('Client does not support URL elicitation (required for notifications/elicitation/complete)'); - } - return () => this.notification({ - method: 'notifications/elicitation/complete', - params: { - elicitationId - } - }, options); - } - async listRoots(params, options) { - return this.request({ method: 'roots/list', params }, ListRootsResultSchema, options); - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON RPC message - * @see LoggingMessageNotification - * @param params - * @param sessionId optional for stateless and backward compatibility - */ - async sendLoggingMessage(params, sessionId) { - if (this._capabilities.logging) { - if (!this.isMessageIgnored(params.level, sessionId)) { - return this.notification({ method: 'notifications/message', params }); - } - } - } - async sendResourceUpdated(params) { - return this.notification({ - method: 'notifications/resources/updated', - params - }); - } - async sendResourceListChanged() { - return this.notification({ - method: 'notifications/resources/list_changed' - }); - } - async sendToolListChanged() { - return this.notification({ method: 'notifications/tools/list_changed' }); - } - async sendPromptListChanged() { - return this.notification({ method: 'notifications/prompts/list_changed' }); - } -} -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/esm/server/index.js.map b/dist/esm/server/index.js.map deleted file mode 100644 index 654cd3dce9..0000000000 --- a/dist/esm/server/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/server/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,QAAQ,EAAuE,MAAM,uBAAuB,CAAC;AACzI,OAAO,EAGH,yBAAyB,EAIzB,kBAAkB,EAClB,iBAAiB,EACjB,SAAS,EAET,6BAA6B,EAE7B,uBAAuB,EAEvB,uBAAuB,EAEvB,qBAAqB,EAErB,kBAAkB,EAElB,QAAQ,EASR,qBAAqB,EACrB,2BAA2B,EAC9B,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AAgDvE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,OAAO,MAIX,SAAQ,QAA8F;IAYpG;;OAEG;IACH,YACY,WAA2B,EACnC,OAAuB;;QAEvB,KAAK,CAAC,OAAO,CAAC,CAAC;QAHP,gBAAW,GAAX,WAAW,CAAgB;QAyBvC,+BAA+B;QACvB,mBAAc,GAAG,IAAI,GAAG,EAAoC,CAAC;QAErE,uCAAuC;QACtB,uBAAkB,GAAG,IAAI,GAAG,CAAC,kBAAkB,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;QAEhH,2FAA2F;QACnF,qBAAgB,GAAG,CAAC,KAAmB,EAAE,SAAkB,EAAW,EAAE;YAC5E,MAAM,YAAY,GAAG,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;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,uBAAuB;QACzB,OAAO,IAAI,CAAC,YAAY,CAAC;YACrB,MAAM,EAAE,sCAAsC;SACjD,CAAC,CAAC;IACP,CAAC;IAED,KAAK,CAAC,mBAAmB;QACrB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,kCAAkC,EAAE,CAAC,CAAC;IAC7E,CAAC;IAED,KAAK,CAAC,qBAAqB;QACvB,OAAO,IAAI,CAAC,YAAY,CAAC,EAAE,MAAM,EAAE,oCAAoC,EAAE,CAAC,CAAC;IAC/E,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/server/mcp.d.ts b/dist/esm/server/mcp.d.ts deleted file mode 100644 index c0294b5698..0000000000 --- a/dist/esm/server/mcp.d.ts +++ /dev/null @@ -1,332 +0,0 @@ -import { Server, ServerOptions } from './index.js'; -import { AnySchema, AnyObjectSchema, ZodRawShapeCompat, SchemaOutput, ShapeOutput } from './zod-compat.js'; -import { Implementation, CallToolResult, Resource, ListResourcesResult, GetPromptResult, ReadResourceResult, ServerRequest, ServerNotification, ToolAnnotations, SecurityScheme, LoggingMessageNotification } from '../types.js'; -import { UriTemplate, Variables } from '../shared/uriTemplate.js'; -import { RequestHandlerExtra } from '../shared/protocol.js'; -import { Transport } from '../shared/transport.js'; -/** - * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. - * For advanced usage (like sending notifications or setting custom request handlers), use the underlying - * Server instance available via the `server` property. - */ -export declare class McpServer { - /** - * The underlying Server instance, useful for advanced operations like sending notifications. - */ - readonly server: Server; - private _registeredResources; - private _registeredResourceTemplates; - private _registeredTools; - private _registeredPrompts; - constructor(serverInfo: Implementation, options?: ServerOptions); - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. - */ - connect(transport: Transport): Promise; - /** - * Closes the connection. - */ - close(): Promise; - private _toolHandlersInitialized; - private setToolRequestHandlers; - /** - * Creates a tool error result. - * - * @param errorMessage - The error message. - * @returns The tool error result. - */ - private createToolError; - private _completionHandlerInitialized; - private setCompletionRequestHandler; - private handlePromptCompletion; - private handleResourceCompletion; - private _resourceHandlersInitialized; - private setResourceRequestHandlers; - private _promptHandlersInitialized; - private setPromptRequestHandlers; - /** - * Registers a resource `name` at a fixed URI, which will use the given callback to respond to read requests. - * @deprecated Use `registerResource` instead. - */ - resource(name: string, uri: string, readCallback: ReadResourceCallback): RegisteredResource; - /** - * Registers a resource `name` at a fixed URI with metadata, which will use the given callback to respond to read requests. - * @deprecated Use `registerResource` instead. - */ - resource(name: string, uri: string, metadata: ResourceMetadata, readCallback: ReadResourceCallback): RegisteredResource; - /** - * Registers a resource `name` with a template pattern, which will use the given callback to respond to read requests. - * @deprecated Use `registerResource` instead. - */ - resource(name: string, template: ResourceTemplate, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; - /** - * Registers a resource `name` with a template pattern and metadata, which will use the given callback to respond to read requests. - * @deprecated Use `registerResource` instead. - */ - resource(name: string, template: ResourceTemplate, metadata: ResourceMetadata, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; - /** - * Registers a resource with a config object and callback. - * For static resources, use a URI string. For dynamic resources, use a ResourceTemplate. - */ - registerResource(name: string, uriOrTemplate: string, config: ResourceMetadata, readCallback: ReadResourceCallback): RegisteredResource; - registerResource(name: string, uriOrTemplate: ResourceTemplate, config: ResourceMetadata, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate; - private _createRegisteredResource; - private _createRegisteredResourceTemplate; - private _createRegisteredPrompt; - private _createRegisteredTool; - /** - * Registers a zero-argument tool `name`, which will run the given function when the client calls it. - * @deprecated Use `registerTool` instead. - */ - tool(name: string, cb: ToolCallback): RegisteredTool; - /** - * Registers a zero-argument tool `name` (with a description) which will run the given function when the client calls it. - * @deprecated Use `registerTool` instead. - */ - tool(name: string, description: string, cb: ToolCallback): RegisteredTool; - /** - * Registers a tool taking either a parameter schema for validation or annotations for additional metadata. - * This unified overload handles both `tool(name, paramsSchema, cb)` and `tool(name, annotations, cb)` cases. - * - * Note: We use a union type for the second parameter because TypeScript cannot reliably disambiguate - * between ToolAnnotations and ZodRawShape during overload resolution, as both are plain object types. - * @deprecated Use `registerTool` instead. - */ - tool(name: string, paramsSchemaOrAnnotations: Args | ToolAnnotations, cb: ToolCallback): RegisteredTool; - /** - * Registers a tool `name` (with a description) taking either parameter schema or annotations. - * This unified overload handles both `tool(name, description, paramsSchema, cb)` and - * `tool(name, description, annotations, cb)` cases. - * - * Note: We use a union type for the third parameter because TypeScript cannot reliably disambiguate - * between ToolAnnotations and ZodRawShape during overload resolution, as both are plain object types. - * @deprecated Use `registerTool` instead. - */ - tool(name: string, description: string, paramsSchemaOrAnnotations: Args | ToolAnnotations, cb: ToolCallback): RegisteredTool; - /** - * Registers a tool with both parameter schema and annotations. - * @deprecated Use `registerTool` instead. - */ - tool(name: string, paramsSchema: Args, annotations: ToolAnnotations, cb: ToolCallback): RegisteredTool; - /** - * Registers a tool with description, parameter schema, and annotations. - * @deprecated Use `registerTool` instead. - */ - tool(name: string, description: string, paramsSchema: Args, annotations: ToolAnnotations, cb: ToolCallback): RegisteredTool; - /** - * Registers a tool with a config object and callback. - */ - registerTool(name: string, config: { - title?: string; - description?: string; - inputSchema?: InputArgs; - outputSchema?: OutputArgs; - annotations?: ToolAnnotations; - securitySchemes?: SecurityScheme[]; - _meta?: Record; - }, cb: ToolCallback): RegisteredTool; - /** - * Registers a zero-argument prompt `name`, which will run the given function when the client calls it. - * @deprecated Use `registerPrompt` instead. - */ - prompt(name: string, cb: PromptCallback): RegisteredPrompt; - /** - * Registers a zero-argument prompt `name` (with a description) which will run the given function when the client calls it. - * @deprecated Use `registerPrompt` instead. - */ - prompt(name: string, description: string, cb: PromptCallback): RegisteredPrompt; - /** - * Registers a prompt `name` accepting the given arguments, which must be an object containing named properties associated with Zod schemas. When the client calls it, the function will be run with the parsed and validated arguments. - * @deprecated Use `registerPrompt` instead. - */ - prompt(name: string, argsSchema: Args, cb: PromptCallback): RegisteredPrompt; - /** - * Registers a prompt `name` (with a description) accepting the given arguments, which must be an object containing named properties associated with Zod schemas. When the client calls it, the function will be run with the parsed and validated arguments. - * @deprecated Use `registerPrompt` instead. - */ - prompt(name: string, description: string, argsSchema: Args, cb: PromptCallback): RegisteredPrompt; - /** - * Registers a prompt with a config object and callback. - */ - registerPrompt(name: string, config: { - title?: string; - description?: string; - argsSchema?: Args; - }, cb: PromptCallback): RegisteredPrompt; - /** - * Checks if the server is connected to a transport. - * @returns True if the server is connected - */ - isConnected(): boolean; - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON RPC message - * @see LoggingMessageNotification - * @param params - * @param sessionId optional for stateless and backward compatibility - */ - sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string): Promise; - /** - * Sends a resource list changed event to the client, if connected. - */ - sendResourceListChanged(): void; - /** - * Sends a tool list changed event to the client, if connected. - */ - sendToolListChanged(): void; - /** - * Sends a prompt list changed event to the client, if connected. - */ - sendPromptListChanged(): void; -} -/** - * A callback to complete one variable within a resource template's URI template. - */ -export type CompleteResourceTemplateCallback = (value: string, context?: { - arguments?: Record; -}) => string[] | Promise; -/** - * A resource template combines a URI pattern with optional functionality to enumerate - * all resources matching that pattern. - */ -export declare class ResourceTemplate { - private _callbacks; - private _uriTemplate; - constructor(uriTemplate: string | UriTemplate, _callbacks: { - /** - * A callback to list all resources matching this template. This is required to specified, even if `undefined`, to avoid accidentally forgetting resource listing. - */ - list: ListResourcesCallback | undefined; - /** - * An optional callback to autocomplete variables within the URI template. Useful for clients and users to discover possible values. - */ - complete?: { - [variable: string]: CompleteResourceTemplateCallback; - }; - }); - /** - * Gets the URI template pattern. - */ - get uriTemplate(): UriTemplate; - /** - * Gets the list callback, if one was provided. - */ - get listCallback(): ListResourcesCallback | undefined; - /** - * Gets the callback for completing a specific URI template variable, if one was provided. - */ - completeCallback(variable: string): CompleteResourceTemplateCallback | undefined; -} -/** - * Callback for a tool handler registered with Server.tool(). - * - * Parameters will include tool arguments, if applicable, as well as other request handler context. - * - * The callback should return: - * - `structuredContent` if the tool has an outputSchema defined - * - `content` if the tool does not have an outputSchema - * - Both fields are optional but typically one should be provided - */ -export type ToolCallback = Args extends ZodRawShapeCompat ? (args: ShapeOutput, extra: RequestHandlerExtra) => CallToolResult | Promise : Args extends AnySchema ? (args: SchemaOutput, extra: RequestHandlerExtra) => CallToolResult | Promise : (extra: RequestHandlerExtra) => CallToolResult | Promise; -export type RegisteredTool = { - title?: string; - description?: string; - inputSchema?: AnySchema; - outputSchema?: AnySchema; - annotations?: ToolAnnotations; - securitySchemes?: SecurityScheme[]; - _meta?: Record; - callback: ToolCallback; - enabled: boolean; - enable(): void; - disable(): void; - update(updates: { - name?: string | null; - title?: string; - description?: string; - paramsSchema?: InputArgs; - outputSchema?: OutputArgs; - annotations?: ToolAnnotations; - securitySchemes?: SecurityScheme[]; - _meta?: Record; - callback?: ToolCallback; - enabled?: boolean; - }): void; - remove(): void; -}; -/** - * Additional, optional information for annotating a resource. - */ -export type ResourceMetadata = Omit; -/** - * Callback to list all resources matching a given template. - */ -export type ListResourcesCallback = (extra: RequestHandlerExtra) => ListResourcesResult | Promise; -/** - * Callback to read a resource at a given URI. - */ -export type ReadResourceCallback = (uri: URL, extra: RequestHandlerExtra) => ReadResourceResult | Promise; -export type RegisteredResource = { - name: string; - title?: string; - metadata?: ResourceMetadata; - readCallback: ReadResourceCallback; - enabled: boolean; - enable(): void; - disable(): void; - update(updates: { - name?: string; - title?: string; - uri?: string | null; - metadata?: ResourceMetadata; - callback?: ReadResourceCallback; - enabled?: boolean; - }): void; - remove(): void; -}; -/** - * Callback to read a resource at a given URI, following a filled-in URI template. - */ -export type ReadResourceTemplateCallback = (uri: URL, variables: Variables, extra: RequestHandlerExtra) => ReadResourceResult | Promise; -export type RegisteredResourceTemplate = { - resourceTemplate: ResourceTemplate; - title?: string; - metadata?: ResourceMetadata; - readCallback: ReadResourceTemplateCallback; - enabled: boolean; - enable(): void; - disable(): void; - update(updates: { - name?: string | null; - title?: string; - template?: ResourceTemplate; - metadata?: ResourceMetadata; - callback?: ReadResourceTemplateCallback; - enabled?: boolean; - }): void; - remove(): void; -}; -type PromptArgsRawShape = ZodRawShapeCompat; -export type PromptCallback = Args extends PromptArgsRawShape ? (args: ShapeOutput, extra: RequestHandlerExtra) => GetPromptResult | Promise : (extra: RequestHandlerExtra) => GetPromptResult | Promise; -export type RegisteredPrompt = { - title?: string; - description?: string; - argsSchema?: AnyObjectSchema; - callback: PromptCallback; - enabled: boolean; - enable(): void; - disable(): void; - update(updates: { - name?: string | null; - title?: string; - description?: string; - argsSchema?: Args; - callback?: PromptCallback; - enabled?: boolean; - }): void; - remove(): void; -}; -export {}; -//# sourceMappingURL=mcp.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/mcp.d.ts.map b/dist/esm/server/mcp.d.ts.map deleted file mode 100644 index 9ed3a0fd27..0000000000 --- a/dist/esm/server/mcp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"mcp.d.ts","sourceRoot":"","sources":["../../../src/server/mcp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACnD,OAAO,EACH,SAAS,EACT,eAAe,EACf,iBAAiB,EACjB,YAAY,EACZ,WAAW,EASd,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EACH,cAAc,EAGd,cAAc,EAOd,QAAQ,EACR,mBAAmB,EAYnB,eAAe,EACf,kBAAkB,EAClB,aAAa,EACb,kBAAkB,EAClB,eAAe,EACf,cAAc,EACd,0BAA0B,EAK7B,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAGnD;;;;GAIG;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,CAAC,KAAK,EAAE,mBAAmB,CAAC,aAAa,EAAE,kBAAkB,CAAC,KAAK,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;AAEpH,MAAM,MAAM,gBAAgB,GAAG;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,eAAe,CAAC;IAC7B,QAAQ,EAAE,cAAc,CAAC,SAAS,GAAG,kBAAkB,CAAC,CAAC;IACzD,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,IAAI,IAAI,CAAC;IACf,OAAO,IAAI,IAAI,CAAC;IAChB,MAAM,CAAC,IAAI,SAAS,kBAAkB,EAAE,OAAO,EAAE;QAC7C,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;QACrB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,WAAW,CAAC,EAAE,MAAM,CAAC;QACrB,UAAU,CAAC,EAAE,IAAI,CAAC;QAClB,QAAQ,CAAC,EAAE,cAAc,CAAC,IAAI,CAAC,CAAC;QAChC,OAAO,CAAC,EAAE,OAAO,CAAC;KACrB,GAAG,IAAI,CAAC;IACT,MAAM,IAAI,IAAI,CAAC;CAClB,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/mcp.js b/dist/esm/server/mcp.js deleted file mode 100644 index b0392350b5..0000000000 --- a/dist/esm/server/mcp.js +++ /dev/null @@ -1,753 +0,0 @@ -import { Server } from './index.js'; -import { normalizeObjectSchema, safeParseAsync, getObjectShape, objectFromShape, getParseErrorMessage, getSchemaDescription, isSchemaOptional, getLiteralValue } from './zod-compat.js'; -import { toJsonSchemaCompat } from './zod-json-schema-compat.js'; -import { McpError, ErrorCode, ListResourceTemplatesRequestSchema, ReadResourceRequestSchema, ListToolsRequestSchema, CallToolRequestSchema, ListResourcesRequestSchema, ListPromptsRequestSchema, GetPromptRequestSchema, CompleteRequestSchema, assertCompleteRequestPrompt, assertCompleteRequestResourceTemplate } from '../types.js'; -import { isCompletable, getCompleter } from './completable.js'; -import { UriTemplate } from '../shared/uriTemplate.js'; -import { validateAndWarnToolName } from '../shared/toolNameValidation.js'; -/** - * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. - * For advanced usage (like sending notifications or setting custom request handlers), use the underlying - * Server instance available via the `server` property. - */ -export class McpServer { - constructor(serverInfo, options) { - this._registeredResources = {}; - this._registeredResourceTemplates = {}; - this._registeredTools = {}; - this._registeredPrompts = {}; - this._toolHandlersInitialized = false; - this._completionHandlerInitialized = false; - this._resourceHandlersInitialized = false; - this._promptHandlersInitialized = false; - this.server = new Server(serverInfo, options); - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The `server` object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. - */ - async connect(transport) { - return await this.server.connect(transport); - } - /** - * Closes the connection. - */ - async close() { - await this.server.close(); - } - setToolRequestHandlers() { - if (this._toolHandlersInitialized) { - return; - } - this.server.assertCanSetRequestHandler(getMethodValue(ListToolsRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(CallToolRequestSchema)); - this.server.registerCapabilities({ - tools: { - listChanged: true - } - }); - this.server.setRequestHandler(ListToolsRequestSchema, () => { - // eslint-disable-next-line no-console - console.log('Tool list handler called'); - return { - tools: Object.entries(this._registeredTools) - .filter(([, tool]) => tool.enabled) - .map(([name, tool]) => { - const toolDefinition = { - name, - title: tool.title, - description: tool.description, - inputSchema: (() => { - const obj = normalizeObjectSchema(tool.inputSchema); - return obj - ? toJsonSchemaCompat(obj, { - strictUnions: true, - pipeStrategy: 'input' - }) - : EMPTY_OBJECT_JSON_SCHEMA; - })(), - annotations: tool.annotations, - securitySchemes: tool.securitySchemes, - _meta: tool._meta - }; - if (tool.outputSchema) { - const obj = normalizeObjectSchema(tool.outputSchema); - if (obj) { - toolDefinition.outputSchema = toJsonSchemaCompat(obj, { - strictUnions: true, - pipeStrategy: 'output' - }); - } - } - return toolDefinition; - }) - }; - }); - this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => { - const tool = this._registeredTools[request.params.name]; - let result; - try { - if (!tool) { - throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} not found`); - } - if (!tool.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); - } - if (tool.inputSchema) { - const cb = tool.callback; - // Try to normalize to object schema first (for raw shapes and object schemas) - // If that fails, use the schema directly (for union/intersection/etc) - const inputObj = normalizeObjectSchema(tool.inputSchema); - const schemaToParse = inputObj !== null && inputObj !== void 0 ? inputObj : tool.inputSchema; - const parseResult = await safeParseAsync(schemaToParse, request.params.arguments); - if (!parseResult.success) { - throw new McpError(ErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${request.params.name}: ${getParseErrorMessage(parseResult.error)}`); - } - const args = parseResult.data; - result = await Promise.resolve(cb(args, extra)); - } - else { - const cb = tool.callback; - result = await Promise.resolve(cb(extra)); - } - if (tool.outputSchema && !result.isError) { - if (!result.structuredContent) { - throw new McpError(ErrorCode.InvalidParams, `Output validation error: Tool ${request.params.name} has an output schema but no structured content was provided`); - } - // if the tool has an output schema, validate structured content - const outputObj = normalizeObjectSchema(tool.outputSchema); - const parseResult = await safeParseAsync(outputObj, result.structuredContent); - if (!parseResult.success) { - throw new McpError(ErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${request.params.name}: ${getParseErrorMessage(parseResult.error)}`); - } - } - } - catch (error) { - if (error instanceof McpError) { - if (error.code === ErrorCode.UrlElicitationRequired) { - throw error; // Return the error to the caller without wrapping in CallToolResult - } - } - return this.createToolError(error instanceof Error ? error.message : String(error)); - } - return result; - }); - this._toolHandlersInitialized = true; - } - /** - * Creates a tool error result. - * - * @param errorMessage - The error message. - * @returns The tool error result. - */ - createToolError(errorMessage) { - return { - content: [ - { - type: 'text', - text: errorMessage - } - ], - isError: true - }; - } - setCompletionRequestHandler() { - if (this._completionHandlerInitialized) { - return; - } - this.server.assertCanSetRequestHandler(getMethodValue(CompleteRequestSchema)); - this.server.registerCapabilities({ - completions: {} - }); - this.server.setRequestHandler(CompleteRequestSchema, async (request) => { - switch (request.params.ref.type) { - case 'ref/prompt': - assertCompleteRequestPrompt(request); - return this.handlePromptCompletion(request, request.params.ref); - case 'ref/resource': - assertCompleteRequestResourceTemplate(request); - return this.handleResourceCompletion(request, request.params.ref); - default: - throw new McpError(ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); - } - }); - this._completionHandlerInitialized = true; - } - async handlePromptCompletion(request, ref) { - const prompt = this._registeredPrompts[ref.name]; - if (!prompt) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} not found`); - } - if (!prompt.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); - } - if (!prompt.argsSchema) { - return EMPTY_COMPLETION_RESULT; - } - const promptShape = getObjectShape(prompt.argsSchema); - const field = promptShape === null || promptShape === void 0 ? void 0 : promptShape[request.params.argument.name]; - if (!isCompletable(field)) { - return EMPTY_COMPLETION_RESULT; - } - const completer = getCompleter(field); - if (!completer) { - return EMPTY_COMPLETION_RESULT; - } - const suggestions = await completer(request.params.argument.value, request.params.context); - return createCompletionResult(suggestions); - } - async handleResourceCompletion(request, ref) { - const template = Object.values(this._registeredResourceTemplates).find(t => t.resourceTemplate.uriTemplate.toString() === ref.uri); - if (!template) { - if (this._registeredResources[ref.uri]) { - // Attempting to autocomplete a fixed resource URI is not an error in the spec (but probably should be). - return EMPTY_COMPLETION_RESULT; - } - throw new McpError(ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); - } - const completer = template.resourceTemplate.completeCallback(request.params.argument.name); - if (!completer) { - return EMPTY_COMPLETION_RESULT; - } - const suggestions = await completer(request.params.argument.value, request.params.context); - return createCompletionResult(suggestions); - } - setResourceRequestHandlers() { - if (this._resourceHandlersInitialized) { - return; - } - this.server.assertCanSetRequestHandler(getMethodValue(ListResourcesRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(ListResourceTemplatesRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(ReadResourceRequestSchema)); - this.server.registerCapabilities({ - resources: { - listChanged: true - } - }); - this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra) => { - const resources = Object.entries(this._registeredResources) - .filter(([_, resource]) => resource.enabled) - .map(([uri, resource]) => ({ - uri, - name: resource.name, - ...resource.metadata - })); - const templateResources = []; - for (const template of Object.values(this._registeredResourceTemplates)) { - if (!template.resourceTemplate.listCallback) { - continue; - } - const result = await template.resourceTemplate.listCallback(extra); - for (const resource of result.resources) { - templateResources.push({ - ...template.metadata, - // the defined resource metadata should override the template metadata if present - ...resource - }); - } - } - return { resources: [...resources, ...templateResources] }; - }); - this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => { - const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ - name, - uriTemplate: template.resourceTemplate.uriTemplate.toString(), - ...template.metadata - })); - return { resourceTemplates }; - }); - this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => { - const uri = new URL(request.params.uri); - // First check for exact resource match - const resource = this._registeredResources[uri.toString()]; - if (resource) { - if (!resource.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} disabled`); - } - return resource.readCallback(uri, extra); - } - // Then check templates - for (const template of Object.values(this._registeredResourceTemplates)) { - const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); - if (variables) { - return template.readCallback(uri, variables, extra); - } - } - throw new McpError(ErrorCode.InvalidParams, `Resource ${uri} not found`); - }); - this.setCompletionRequestHandler(); - this._resourceHandlersInitialized = true; - } - setPromptRequestHandlers() { - if (this._promptHandlersInitialized) { - return; - } - this.server.assertCanSetRequestHandler(getMethodValue(ListPromptsRequestSchema)); - this.server.assertCanSetRequestHandler(getMethodValue(GetPromptRequestSchema)); - this.server.registerCapabilities({ - prompts: { - listChanged: true - } - }); - this.server.setRequestHandler(ListPromptsRequestSchema, () => ({ - prompts: Object.entries(this._registeredPrompts) - .filter(([, prompt]) => prompt.enabled) - .map(([name, prompt]) => { - return { - name, - title: prompt.title, - description: prompt.description, - arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : undefined - }; - }) - })); - this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra) => { - const prompt = this._registeredPrompts[request.params.name]; - if (!prompt) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); - } - if (!prompt.enabled) { - throw new McpError(ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); - } - if (prompt.argsSchema) { - const argsObj = normalizeObjectSchema(prompt.argsSchema); - const parseResult = await safeParseAsync(argsObj, request.params.arguments); - if (!parseResult.success) { - throw new McpError(ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${getParseErrorMessage(parseResult.error)}`); - } - const args = parseResult.data; - const cb = prompt.callback; - return await Promise.resolve(cb(args, extra)); - } - else { - const cb = prompt.callback; - return await Promise.resolve(cb(extra)); - } - }); - this.setCompletionRequestHandler(); - this._promptHandlersInitialized = true; - } - resource(name, uriOrTemplate, ...rest) { - let metadata; - if (typeof rest[0] === 'object') { - metadata = rest.shift(); - } - const readCallback = rest[0]; - if (typeof uriOrTemplate === 'string') { - if (this._registeredResources[uriOrTemplate]) { - throw new Error(`Resource ${uriOrTemplate} is already registered`); - } - const registeredResource = this._createRegisteredResource(name, undefined, uriOrTemplate, metadata, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } - else { - if (this._registeredResourceTemplates[name]) { - throw new Error(`Resource template ${name} is already registered`); - } - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, undefined, uriOrTemplate, metadata, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - registerResource(name, uriOrTemplate, config, readCallback) { - if (typeof uriOrTemplate === 'string') { - if (this._registeredResources[uriOrTemplate]) { - throw new Error(`Resource ${uriOrTemplate} is already registered`); - } - const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } - else { - if (this._registeredResourceTemplates[name]) { - throw new Error(`Resource template ${name} is already registered`); - } - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback); - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - _createRegisteredResource(name, title, uri, metadata, readCallback) { - const registeredResource = { - name, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResource.update({ enabled: false }), - enable: () => registeredResource.update({ enabled: true }), - remove: () => registeredResource.update({ uri: null }), - update: updates => { - if (typeof updates.uri !== 'undefined' && updates.uri !== uri) { - delete this._registeredResources[uri]; - if (updates.uri) - this._registeredResources[updates.uri] = registeredResource; - } - if (typeof updates.name !== 'undefined') - registeredResource.name = updates.name; - if (typeof updates.title !== 'undefined') - registeredResource.title = updates.title; - if (typeof updates.metadata !== 'undefined') - registeredResource.metadata = updates.metadata; - if (typeof updates.callback !== 'undefined') - registeredResource.readCallback = updates.callback; - if (typeof updates.enabled !== 'undefined') - registeredResource.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResources[uri] = registeredResource; - return registeredResource; - } - _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { - const registeredResourceTemplate = { - resourceTemplate: template, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResourceTemplate.update({ enabled: false }), - enable: () => registeredResourceTemplate.update({ enabled: true }), - remove: () => registeredResourceTemplate.update({ name: null }), - update: updates => { - if (typeof updates.name !== 'undefined' && updates.name !== name) { - delete this._registeredResourceTemplates[name]; - if (updates.name) - this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; - } - if (typeof updates.title !== 'undefined') - registeredResourceTemplate.title = updates.title; - if (typeof updates.template !== 'undefined') - registeredResourceTemplate.resourceTemplate = updates.template; - if (typeof updates.metadata !== 'undefined') - registeredResourceTemplate.metadata = updates.metadata; - if (typeof updates.callback !== 'undefined') - registeredResourceTemplate.readCallback = updates.callback; - if (typeof updates.enabled !== 'undefined') - registeredResourceTemplate.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResourceTemplates[name] = registeredResourceTemplate; - return registeredResourceTemplate; - } - _createRegisteredPrompt(name, title, description, argsSchema, callback) { - const registeredPrompt = { - title, - description, - argsSchema: argsSchema === undefined ? undefined : objectFromShape(argsSchema), - callback, - enabled: true, - disable: () => registeredPrompt.update({ enabled: false }), - enable: () => registeredPrompt.update({ enabled: true }), - remove: () => registeredPrompt.update({ name: null }), - update: updates => { - if (typeof updates.name !== 'undefined' && updates.name !== name) { - delete this._registeredPrompts[name]; - if (updates.name) - this._registeredPrompts[updates.name] = registeredPrompt; - } - if (typeof updates.title !== 'undefined') - registeredPrompt.title = updates.title; - if (typeof updates.description !== 'undefined') - registeredPrompt.description = updates.description; - if (typeof updates.argsSchema !== 'undefined') - registeredPrompt.argsSchema = objectFromShape(updates.argsSchema); - if (typeof updates.callback !== 'undefined') - registeredPrompt.callback = updates.callback; - if (typeof updates.enabled !== 'undefined') - registeredPrompt.enabled = updates.enabled; - this.sendPromptListChanged(); - } - }; - this._registeredPrompts[name] = registeredPrompt; - return registeredPrompt; - } - _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, securitySchemes, _meta, callback) { - // Validate tool name according to SEP specification - validateAndWarnToolName(name); - const registeredTool = { - title, - description, - inputSchema: getZodSchemaObject(inputSchema), - outputSchema: getZodSchemaObject(outputSchema), - annotations, - securitySchemes, - _meta, - callback, - enabled: true, - disable: () => registeredTool.update({ enabled: false }), - enable: () => registeredTool.update({ enabled: true }), - remove: () => registeredTool.update({ name: null }), - update: updates => { - if (typeof updates.name !== 'undefined' && updates.name !== name) { - if (typeof updates.name === 'string') { - validateAndWarnToolName(updates.name); - } - delete this._registeredTools[name]; - if (updates.name) - this._registeredTools[updates.name] = registeredTool; - } - if (typeof updates.title !== 'undefined') - registeredTool.title = updates.title; - if (typeof updates.description !== 'undefined') - registeredTool.description = updates.description; - if (typeof updates.paramsSchema !== 'undefined') - registeredTool.inputSchema = objectFromShape(updates.paramsSchema); - if (typeof updates.callback !== 'undefined') - registeredTool.callback = updates.callback; - if (typeof updates.annotations !== 'undefined') - registeredTool.annotations = updates.annotations; - if (typeof updates.securitySchemes !== 'undefined') - registeredTool.securitySchemes = updates.securitySchemes; - if (typeof updates._meta !== 'undefined') - registeredTool._meta = updates._meta; - if (typeof updates.enabled !== 'undefined') - registeredTool.enabled = updates.enabled; - this.sendToolListChanged(); - } - }; - this._registeredTools[name] = registeredTool; - this.setToolRequestHandlers(); - this.sendToolListChanged(); - return registeredTool; - } - /** - * tool() implementation. Parses arguments passed to overrides defined above. - */ - tool(name, ...rest) { - if (this._registeredTools[name]) { - throw new Error(`Tool ${name} is already registered`); - } - let description; - let inputSchema; - let outputSchema; - let annotations; - // Tool properties are passed as separate arguments, with omissions allowed. - // Support for this style is frozen as of protocol version 2025-03-26. Future additions - // to tool definition should *NOT* be added. - if (typeof rest[0] === 'string') { - description = rest.shift(); - } - // Handle the different overload combinations - if (rest.length > 1) { - // We have at least one more arg before the callback - const firstArg = rest[0]; - if (isZodRawShape(firstArg)) { - // We have a params schema as the first arg - inputSchema = rest.shift(); - // Check if the next arg is potentially annotations - if (rest.length > 1 && typeof rest[0] === 'object' && rest[0] !== null && !isZodRawShape(rest[0])) { - // Case: tool(name, paramsSchema, annotations, cb) - // Or: tool(name, description, paramsSchema, annotations, cb) - annotations = rest.shift(); - } - } - else if (typeof firstArg === 'object' && firstArg !== null) { - // Not a ZodRawShape, so must be annotations in this position - // Case: tool(name, annotations, cb) - // Or: tool(name, description, annotations, cb) - annotations = rest.shift(); - } - } - const callback = rest[0]; - return this._createRegisteredTool(name, undefined, description, inputSchema, outputSchema, annotations, undefined, undefined, callback); - } - /** - * Registers a tool with a config object and callback. - */ - registerTool(name, config, cb) { - if (this._registeredTools[name]) { - throw new Error(`Tool ${name} is already registered`); - } - console.log('registerTool'); - const { title, description, inputSchema, outputSchema, annotations, securitySchemes, _meta } = config; - return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, securitySchemes, _meta, cb); - } - prompt(name, ...rest) { - if (this._registeredPrompts[name]) { - throw new Error(`Prompt ${name} is already registered`); - } - let description; - if (typeof rest[0] === 'string') { - description = rest.shift(); - } - let argsSchema; - if (rest.length > 1) { - argsSchema = rest.shift(); - } - const cb = rest[0]; - const registeredPrompt = this._createRegisteredPrompt(name, undefined, description, argsSchema, cb); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; - } - /** - * Registers a prompt with a config object and callback. - */ - registerPrompt(name, config, cb) { - if (this._registeredPrompts[name]) { - throw new Error(`Prompt ${name} is already registered`); - } - const { title, description, argsSchema } = config; - const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; - } - /** - * Checks if the server is connected to a transport. - * @returns True if the server is connected - */ - isConnected() { - return this.server.transport !== undefined; - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON RPC message - * @see LoggingMessageNotification - * @param params - * @param sessionId optional for stateless and backward compatibility - */ - async sendLoggingMessage(params, sessionId) { - return this.server.sendLoggingMessage(params, sessionId); - } - /** - * Sends a resource list changed event to the client, if connected. - */ - sendResourceListChanged() { - if (this.isConnected()) { - this.server.sendResourceListChanged(); - } - } - /** - * Sends a tool list changed event to the client, if connected. - */ - sendToolListChanged() { - if (this.isConnected()) { - this.server.sendToolListChanged(); - } - } - /** - * Sends a prompt list changed event to the client, if connected. - */ - sendPromptListChanged() { - if (this.isConnected()) { - this.server.sendPromptListChanged(); - } - } -} -/** - * A resource template combines a URI pattern with optional functionality to enumerate - * all resources matching that pattern. - */ -export class ResourceTemplate { - constructor(uriTemplate, _callbacks) { - this._callbacks = _callbacks; - this._uriTemplate = typeof uriTemplate === 'string' ? new UriTemplate(uriTemplate) : uriTemplate; - } - /** - * Gets the URI template pattern. - */ - get uriTemplate() { - return this._uriTemplate; - } - /** - * Gets the list callback, if one was provided. - */ - get listCallback() { - return this._callbacks.list; - } - /** - * Gets the callback for completing a specific URI template variable, if one was provided. - */ - completeCallback(variable) { - var _a; - return (_a = this._callbacks.complete) === null || _a === void 0 ? void 0 : _a[variable]; - } -} -const EMPTY_OBJECT_JSON_SCHEMA = { - type: 'object', - properties: {} -}; -// Helper to check if an object is a Zod schema (ZodRawShapeCompat) -function isZodRawShape(obj) { - if (typeof obj !== 'object' || obj === null) - return false; - const isEmptyObject = Object.keys(obj).length === 0; - // Check if object is empty or at least one property is a ZodType instance - // Note: use heuristic check to avoid instanceof failure across different Zod versions - return isEmptyObject || Object.values(obj).some(isZodTypeLike); -} -function isZodTypeLike(value) { - return (value !== null && - typeof value === 'object' && - 'parse' in value && - typeof value.parse === 'function' && - 'safeParse' in value && - typeof value.safeParse === 'function'); -} -/** - * Converts a provided Zod schema to a Zod object if it is a ZodRawShape, - * otherwise returns the schema as is. - */ -function getZodSchemaObject(schema) { - if (!schema) { - return undefined; - } - if (isZodRawShape(schema)) { - return objectFromShape(schema); - } - return schema; -} -function promptArgumentsFromSchema(schema) { - const shape = getObjectShape(schema); - if (!shape) - return []; - return Object.entries(shape).map(([name, field]) => { - // Get description - works for both v3 and v4 - const description = getSchemaDescription(field); - // Check if optional - works for both v3 and v4 - const isOptional = isSchemaOptional(field); - return { - name, - description, - required: !isOptional - }; - }); -} -function getMethodValue(schema) { - const shape = getObjectShape(schema); - const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method; - if (!methodSchema) { - throw new Error('Schema is missing a method literal'); - } - // Extract literal value - works for both v3 and v4 - const value = getLiteralValue(methodSchema); - if (typeof value === 'string') { - return value; - } - throw new Error('Schema method literal must be a string'); -} -function createCompletionResult(suggestions) { - return { - completion: { - values: suggestions.slice(0, 100), - total: suggestions.length, - hasMore: suggestions.length > 100 - } - }; -} -const EMPTY_COMPLETION_RESULT = { - completion: { - values: [], - hasMore: false - } -}; -//# sourceMappingURL=mcp.js.map \ No newline at end of file diff --git a/dist/esm/server/mcp.js.map b/dist/esm/server/mcp.js.map deleted file mode 100644 index 65a19268f4..0000000000 --- a/dist/esm/server/mcp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"mcp.js","sourceRoot":"","sources":["../../../src/server/mcp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAiB,MAAM,YAAY,CAAC;AACnD,OAAO,EAMH,qBAAqB,EACrB,cAAc,EACd,cAAc,EACd,eAAe,EACf,oBAAoB,EACpB,oBAAoB,EACpB,gBAAgB,EAChB,eAAe,EAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EAKH,QAAQ,EACR,SAAS,EAOT,kCAAkC,EAClC,yBAAyB,EACzB,sBAAsB,EACtB,qBAAqB,EACrB,0BAA0B,EAC1B,wBAAwB,EACxB,sBAAsB,EACtB,qBAAqB,EAarB,2BAA2B,EAC3B,qCAAqC,EACxC,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAa,MAAM,0BAA0B,CAAC;AAGlE,OAAO,EAAE,uBAAuB,EAAE,MAAM,iCAAiC,CAAC;AAE1E;;;;GAIG;AACH,MAAM,OAAO,SAAS;IAalB,YAAY,UAA0B,EAAE,OAAuB;QAPvD,yBAAoB,GAA0C,EAAE,CAAC;QACjE,iCAA4B,GAEhC,EAAE,CAAC;QACC,qBAAgB,GAAuC,EAAE,CAAC;QAC1D,uBAAkB,GAAyC,EAAE,CAAC;QAsB9D,6BAAwB,GAAG,KAAK,CAAC;QAkJjC,kCAA6B,GAAG,KAAK,CAAC;QAmFtC,iCAA4B,GAAG,KAAK,CAAC;QAmFrC,+BAA0B,GAAG,KAAK,CAAC;QA3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AC;QAChB,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;IAC1D,CAAC;IAED,mDAAmD;IACnD,MAAM,KAAK,GAAG,eAAe,CAAC,YAAY,CAAC,CAAC;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC5B,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;AAC9D,CAAC;AAED,SAAS,sBAAsB,CAAC,WAAqB;IACjD,OAAO;QACH,UAAU,EAAE;YACR,MAAM,EAAE,WAAW,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC;YACjC,KAAK,EAAE,WAAW,CAAC,MAAM;YACzB,OAAO,EAAE,WAAW,CAAC,MAAM,GAAG,GAAG;SACpC;KACJ,CAAC;AACN,CAAC;AAED,MAAM,uBAAuB,GAAmB;IAC5C,UAAU,EAAE;QACR,MAAM,EAAE,EAAE;QACV,OAAO,EAAE,KAAK;KACjB;CACJ,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/sse.d.ts b/dist/esm/server/sse.d.ts deleted file mode 100644 index aba8d51209..0000000000 --- a/dist/esm/server/sse.d.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { IncomingMessage, ServerResponse } from 'node:http'; -import { Transport } from '../shared/transport.js'; -import { JSONRPCMessage, MessageExtraInfo } from '../types.js'; -import { AuthInfo } from './auth/types.js'; -/** - * Configuration options for SSEServerTransport. - */ -export interface SSEServerTransportOptions { - /** - * List of allowed host header values for DNS rebinding protection. - * If not specified, host validation is disabled. - */ - allowedHosts?: string[]; - /** - * List of allowed origin header values for DNS rebinding protection. - * If not specified, origin validation is disabled. - */ - allowedOrigins?: string[]; - /** - * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). - * Default is false for backwards compatibility. - */ - enableDnsRebindingProtection?: boolean; -} -/** - * Server transport for SSE: this will send messages over an SSE connection and receive messages from HTTP POST requests. - * - * This transport is only available in Node.js environments. - * @deprecated SSEServerTransport is deprecated. Use StreamableHTTPServerTransport instead. - */ -export declare class SSEServerTransport implements Transport { - private _endpoint; - private res; - private _sseResponse?; - private _sessionId; - private _options; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; - /** - * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. - */ - constructor(_endpoint: string, res: ServerResponse, options?: SSEServerTransportOptions); - /** - * Validates request headers for DNS rebinding protection. - * @returns Error message if validation fails, undefined if validation passes. - */ - private validateRequestHeaders; - /** - * Handles the initial SSE connection request. - * - * This should be called when a GET request is made to establish the SSE stream. - */ - start(): Promise; - /** - * Handles incoming POST messages. - * - * This should be called when a POST request is made to send a message to the server. - */ - handlePostMessage(req: IncomingMessage & { - auth?: AuthInfo; - }, res: ServerResponse, parsedBody?: unknown): Promise; - /** - * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. - */ - handleMessage(message: unknown, extra?: MessageExtraInfo): Promise; - close(): Promise; - send(message: JSONRPCMessage): Promise; - /** - * Returns the session ID for this transport. - * - * This can be used to route incoming POST requests. - */ - get sessionId(): string; -} -//# sourceMappingURL=sse.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/sse.d.ts.map b/dist/esm/server/sse.d.ts.map deleted file mode 100644 index c3c267cd8f..0000000000 --- a/dist/esm/server/sse.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../../../src/server/sse.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAwB,gBAAgB,EAAe,MAAM,aAAa,CAAC;AAGlG,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAK3C;;GAEG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,IAAI,SAAS,IAAI,MAAM,CAEtB;CACJ"} \ No newline at end of file diff --git a/dist/esm/server/sse.js b/dist/esm/server/sse.js deleted file mode 100644 index 3bf3c51952..0000000000 --- a/dist/esm/server/sse.js +++ /dev/null @@ -1,161 +0,0 @@ -import { randomUUID } from 'node:crypto'; -import { JSONRPCMessageSchema } from '../types.js'; -import getRawBody from 'raw-body'; -import contentType from 'content-type'; -import { URL } from 'url'; -const MAXIMUM_MESSAGE_SIZE = '4mb'; -/** - * Server transport for SSE: this will send messages over an SSE connection and receive messages from HTTP POST requests. - * - * This transport is only available in Node.js environments. - * @deprecated SSEServerTransport is deprecated. Use StreamableHTTPServerTransport instead. - */ -export class SSEServerTransport { - /** - * Creates a new SSE server transport, which will direct the client to POST messages to the relative or absolute URL identified by `_endpoint`. - */ - constructor(_endpoint, res, options) { - this._endpoint = _endpoint; - this.res = res; - this._sessionId = randomUUID(); - this._options = options || { enableDnsRebindingProtection: false }; - } - /** - * Validates request headers for DNS rebinding protection. - * @returns Error message if validation fails, undefined if validation passes. - */ - validateRequestHeaders(req) { - // Skip validation if protection is not enabled - if (!this._options.enableDnsRebindingProtection) { - return undefined; - } - // Validate Host header if allowedHosts is configured - if (this._options.allowedHosts && this._options.allowedHosts.length > 0) { - const hostHeader = req.headers.host; - if (!hostHeader || !this._options.allowedHosts.includes(hostHeader)) { - return `Invalid Host header: ${hostHeader}`; - } - } - // Validate Origin header if allowedOrigins is configured - if (this._options.allowedOrigins && this._options.allowedOrigins.length > 0) { - const originHeader = req.headers.origin; - if (!originHeader || !this._options.allowedOrigins.includes(originHeader)) { - return `Invalid Origin header: ${originHeader}`; - } - } - return undefined; - } - /** - * Handles the initial SSE connection request. - * - * This should be called when a GET request is made to establish the SSE stream. - */ - async start() { - if (this._sseResponse) { - throw new Error('SSEServerTransport already started! If using Server class, note that connect() calls start() automatically.'); - } - this.res.writeHead(200, { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }); - // Send the endpoint event - // Use a dummy base URL because this._endpoint is relative. - // This allows using URL/URLSearchParams for robust parameter handling. - const dummyBase = 'http://localhost'; // Any valid base works - const endpointUrl = new URL(this._endpoint, dummyBase); - endpointUrl.searchParams.set('sessionId', this._sessionId); - // Reconstruct the relative URL string (pathname + search + hash) - const relativeUrlWithSession = endpointUrl.pathname + endpointUrl.search + endpointUrl.hash; - this.res.write(`event: endpoint\ndata: ${relativeUrlWithSession}\n\n`); - this._sseResponse = this.res; - this.res.on('close', () => { - var _a; - this._sseResponse = undefined; - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - }); - } - /** - * Handles incoming POST messages. - * - * This should be called when a POST request is made to send a message to the server. - */ - async handlePostMessage(req, res, parsedBody) { - var _a, _b, _c, _d; - if (!this._sseResponse) { - const message = 'SSE connection not established'; - res.writeHead(500).end(message); - throw new Error(message); - } - // Validate request headers for DNS rebinding protection - const validationError = this.validateRequestHeaders(req); - if (validationError) { - res.writeHead(403).end(validationError); - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(validationError)); - return; - } - const authInfo = req.auth; - const requestInfo = { headers: req.headers }; - let body; - try { - const ct = contentType.parse((_b = req.headers['content-type']) !== null && _b !== void 0 ? _b : ''); - if (ct.type !== 'application/json') { - throw new Error(`Unsupported content-type: ${ct.type}`); - } - body = - parsedBody !== null && parsedBody !== void 0 ? parsedBody : (await getRawBody(req, { - limit: MAXIMUM_MESSAGE_SIZE, - encoding: (_c = ct.parameters.charset) !== null && _c !== void 0 ? _c : 'utf-8' - })); - } - catch (error) { - res.writeHead(400).end(String(error)); - (_d = this.onerror) === null || _d === void 0 ? void 0 : _d.call(this, error); - return; - } - try { - await this.handleMessage(typeof body === 'string' ? JSON.parse(body) : body, { requestInfo, authInfo }); - } - catch (_e) { - res.writeHead(400).end(`Invalid message: ${body}`); - return; - } - res.writeHead(202).end('Accepted'); - } - /** - * Handle a client message, regardless of how it arrived. This can be used to inform the server of messages that arrive via a means different than HTTP POST. - */ - async handleMessage(message, extra) { - var _a, _b; - let parsedMessage; - try { - parsedMessage = JSONRPCMessageSchema.parse(message); - } - catch (error) { - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - throw error; - } - (_b = this.onmessage) === null || _b === void 0 ? void 0 : _b.call(this, parsedMessage, extra); - } - async close() { - var _a, _b; - (_a = this._sseResponse) === null || _a === void 0 ? void 0 : _a.end(); - this._sseResponse = undefined; - (_b = this.onclose) === null || _b === void 0 ? void 0 : _b.call(this); - } - async send(message) { - if (!this._sseResponse) { - throw new Error('Not connected'); - } - this._sseResponse.write(`event: message\ndata: ${JSON.stringify(message)}\n\n`); - } - /** - * Returns the session ID for this transport. - * - * This can be used to route incoming POST requests. - */ - get sessionId() { - return this._sessionId; - } -} -//# sourceMappingURL=sse.js.map \ No newline at end of file diff --git a/dist/esm/server/sse.js.map b/dist/esm/server/sse.js.map deleted file mode 100644 index af4dc36a1b..0000000000 --- a/dist/esm/server/sse.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"sse.js","sourceRoot":"","sources":["../../../src/server/sse.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,OAAO,EAAkB,oBAAoB,EAAiC,MAAM,aAAa,CAAC;AAClG,OAAO,UAAU,MAAM,UAAU,CAAC;AAClC,OAAO,WAAW,MAAM,cAAc,CAAC;AAEvC,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAE1B,MAAM,oBAAoB,GAAG,KAAK,CAAC;AAyBnC;;;;;GAKG;AACH,MAAM,OAAO,kBAAkB;IAQ3B;;OAEG;IACH,YACY,SAAiB,EACjB,GAAmB,EAC3B,OAAmC;QAF3B,cAAS,GAAT,SAAS,CAAQ;QACjB,QAAG,GAAH,GAAG,CAAgB;QAG3B,IAAI,CAAC,UAAU,GAAG,UAAU,EAAE,CAAC;QAC/B,IAAI,CAAC,QAAQ,GAAG,OAAO,IA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AAG,CAAC,CAAC,GAAG,CAAC,oBAAoB,IAAI,EAAE,CAAC,CAAC;YACnD,OAAO;QACX,CAAC;QAED,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACvC,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,aAAa,CAAC,OAAgB,EAAE,KAAwB;;QAC1D,IAAI,aAA6B,CAAC;QAClC,IAAI,CAAC;YACD,aAAa,GAAG,oBAAoB,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QACxD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACb,MAAA,IAAI,CAAC,OAAO,qDAAG,KAAc,CAAC,CAAC;YAC/B,MAAM,KAAK,CAAC;QAChB,CAAC;QAED,MAAA,IAAI,CAAC,SAAS,qDAAG,aAAa,EAAE,KAAK,CAAC,CAAC;IAC3C,CAAC;IAED,KAAK,CAAC,KAAK;;QACP,MAAA,IAAI,CAAC,YAAY,0CAAE,GAAG,EAAE,CAAC;QACzB,IAAI,CAAC,YAAY,GAAG,SAAS,CAAC;QAC9B,MAAA,IAAI,CAAC,OAAO,oDAAI,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,OAAuB;QAC9B,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC;YACrB,MAAM,IAAI,KAAK,CAAC,eAAe,CAAC,CAAC;QACrC,CAAC;QAED,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,yBAAyB,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IACpF,CAAC;IAED;;;;OAIG;IACH,IAAI,SAAS;QACT,OAAO,IAAI,CAAC,UAAU,CAAC;IAC3B,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/server/stdio.d.ts b/dist/esm/server/stdio.d.ts deleted file mode 100644 index df3029d0da..0000000000 --- a/dist/esm/server/stdio.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { Readable, Writable } from 'node:stream'; -import { JSONRPCMessage } from '../types.js'; -import { Transport } from '../shared/transport.js'; -/** - * Server transport for stdio: this communicates with a MCP client by reading from the current process' stdin and writing to stdout. - * - * This transport is only available in Node.js environments. - */ -export declare class StdioServerTransport implements Transport { - private _stdin; - private _stdout; - private _readBuffer; - private _started; - constructor(_stdin?: Readable, _stdout?: Writable); - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage) => void; - _ondata: (chunk: Buffer) => void; - _onerror: (error: Error) => void; - /** - * Starts listening for messages on stdin. - */ - start(): Promise; - private processReadBuffer; - close(): Promise; - send(message: JSONRPCMessage): Promise; -} -//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/stdio.d.ts.map b/dist/esm/server/stdio.d.ts.map deleted file mode 100644 index fdd2dfe48e..0000000000 --- a/dist/esm/server/stdio.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/server/stdio.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AAEnD;;;;GAIG;AACH,qBAAa,oBAAqB,YAAW,SAAS;IAK9C,OAAO,CAAC,MAAM;IACd,OAAO,CAAC,OAAO;IALnB,OAAO,CAAC,WAAW,CAAgC;IACnD,OAAO,CAAC,QAAQ,CAAS;gBAGb,MAAM,GAAE,QAAwB,EAChC,OAAO,GAAE,QAAyB;IAG9C,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;IACrB,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACjC,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,cAAc,KAAK,IAAI,CAAC;IAG9C,OAAO,UAAW,MAAM,UAGtB;IACF,QAAQ,UAAW,KAAK,UAEtB;IAEF;;OAEG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAY5B,OAAO,CAAC,iBAAiB;IAenB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAkB5B,IAAI,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;CAU/C"} \ No newline at end of file diff --git a/dist/esm/server/stdio.js b/dist/esm/server/stdio.js deleted file mode 100644 index 98a3467ed2..0000000000 --- a/dist/esm/server/stdio.js +++ /dev/null @@ -1,78 +0,0 @@ -import process from 'node:process'; -import { ReadBuffer, serializeMessage } from '../shared/stdio.js'; -/** - * Server transport for stdio: this communicates with a MCP client by reading from the current process' stdin and writing to stdout. - * - * This transport is only available in Node.js environments. - */ -export class StdioServerTransport { - constructor(_stdin = process.stdin, _stdout = process.stdout) { - this._stdin = _stdin; - this._stdout = _stdout; - this._readBuffer = new ReadBuffer(); - this._started = false; - // Arrow functions to bind `this` properly, while maintaining function identity. - this._ondata = (chunk) => { - this._readBuffer.append(chunk); - this.processReadBuffer(); - }; - this._onerror = (error) => { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }; - } - /** - * Starts listening for messages on stdin. - */ - async start() { - if (this._started) { - throw new Error('StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.'); - } - this._started = true; - this._stdin.on('data', this._ondata); - this._stdin.on('error', this._onerror); - } - processReadBuffer() { - var _a, _b; - while (true) { - try { - const message = this._readBuffer.readMessage(); - if (message === null) { - break; - } - (_a = this.onmessage) === null || _a === void 0 ? void 0 : _a.call(this, message); - } - catch (error) { - (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); - } - } - } - async close() { - var _a; - // Remove our event listeners first - this._stdin.off('data', this._ondata); - this._stdin.off('error', this._onerror); - // Check if we were the only data listener - const remainingDataListeners = this._stdin.listenerCount('data'); - if (remainingDataListeners === 0) { - // Only pause stdin if we were the only listener - // This prevents interfering with other parts of the application that might be using stdin - this._stdin.pause(); - } - // Clear the buffer and notify closure - this._readBuffer.clear(); - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - } - send(message) { - return new Promise(resolve => { - const json = serializeMessage(message); - if (this._stdout.write(json)) { - resolve(); - } - else { - this._stdout.once('drain', resolve); - } - }); - } -} -//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/dist/esm/server/stdio.js.map b/dist/esm/server/stdio.js.map deleted file mode 100644 index f2d202de70..0000000000 --- a/dist/esm/server/stdio.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/server/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,cAAc,CAAC;AAEnC,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAIlE;;;;GAIG;AACH,MAAM,OAAO,oBAAoB;IAI7B,YACY,SAAmB,OAAO,CAAC,KAAK,EAChC,UAAoB,OAAO,CAAC,MAAM;QADlC,WAAM,GAAN,MAAM,CAA0B;QAChC,YAAO,GAAP,OAAO,CAA2B;QALtC,gBAAW,GAAe,IAAI,UAAU,EAAE,CAAC;QAC3C,aAAQ,GAAG,KAAK,CAAC;QAWzB,gFAAgF;QAChF,YAAO,GAAG,CAAC,KAAa,EAAE,EAAE;YACxB,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAC/B,IAAI,CAAC,iBAAiB,EAAE,CAAC;QAC7B,CAAC,CAAC;QACF,aAAQ,GAAG,CAAC,KAAY,EAAE,EAAE;;YACxB,MAAA,IAAI,CAAC,OAAO,qDAAG,KAAK,CAAC,CAAC;QAC1B,CAAC,CAAC;IAbC,CAAC;IAeJ;;OAEG;IACH,KAAK,CAAC,KAAK;QACP,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAChB,MAAM,IAAI,KAAK,CACX,+GAA+G,CAClH,CAAC;QACN,CAAC;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,EAAE;YACzB,MAAM,IAAI,GAAG,gBAAgB,CAAC,OAAO,CAAC,CAAC;YACvC,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;gBAC3B,OAAO,EAAE,CAAC;YACd,CAAC;iBAAM,CAAC;gBACJ,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/server/streamableHttp.d.ts b/dist/esm/server/streamableHttp.d.ts deleted file mode 100644 index cdad6d6593..0000000000 --- a/dist/esm/server/streamableHttp.d.ts +++ /dev/null @@ -1,185 +0,0 @@ -import { IncomingMessage, ServerResponse } from 'node:http'; -import { Transport } from '../shared/transport.js'; -import { MessageExtraInfo, JSONRPCMessage, RequestId } from '../types.js'; -import { AuthInfo } from './auth/types.js'; -export type StreamId = string; -export type EventId = string; -/** - * Interface for resumability support via event storage - */ -export interface EventStore { - /** - * Stores an event for later retrieval - * @param streamId ID of the stream the event belongs to - * @param message The JSON-RPC message to store - * @returns The generated event ID for the stored event - */ - storeEvent(streamId: StreamId, message: JSONRPCMessage): Promise; - replayEventsAfter(lastEventId: EventId, { send }: { - send: (eventId: EventId, message: JSONRPCMessage) => Promise; - }): Promise; -} -/** - * Configuration options for StreamableHTTPServerTransport - */ -export interface StreamableHTTPServerTransportOptions { - /** - * Function that generates a session ID for the transport. - * The session ID SHOULD be globally unique and cryptographically secure (e.g., a securely generated UUID, a JWT, or a cryptographic hash) - * - * Return undefined to disable session management. - */ - sessionIdGenerator: (() => string) | undefined; - /** - * A callback for session initialization events - * This is called when the server initializes a new session. - * Useful in cases when you need to register multiple mcp sessions - * and need to keep track of them. - * @param sessionId The generated session ID - */ - onsessioninitialized?: (sessionId: string) => void | Promise; - /** - * A callback for session close events - * This is called when the server closes a session due to a DELETE request. - * Useful in cases when you need to clean up resources associated with the session. - * Note that this is different from the transport closing, if you are handling - * HTTP requests from multiple nodes you might want to close each - * StreamableHTTPServerTransport after a request is completed while still keeping the - * session open/running. - * @param sessionId The session ID that was closed - */ - onsessionclosed?: (sessionId: string) => void | Promise; - /** - * If true, the server will return JSON responses instead of starting an SSE stream. - * This can be useful for simple request/response scenarios without streaming. - * Default is false (SSE streams are preferred). - */ - enableJsonResponse?: boolean; - /** - * Event store for resumability support - * If provided, resumability will be enabled, allowing clients to reconnect and resume messages - */ - eventStore?: EventStore; - /** - * List of allowed host header values for DNS rebinding protection. - * If not specified, host validation is disabled. - */ - allowedHosts?: string[]; - /** - * List of allowed origin header values for DNS rebinding protection. - * If not specified, origin validation is disabled. - */ - allowedOrigins?: string[]; - /** - * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). - * Default is false for backwards compatibility. - */ - enableDnsRebindingProtection?: boolean; -} -/** - * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. - * It supports both SSE streaming and direct HTTP responses. - * - * Usage example: - * - * ```typescript - * // Stateful mode - server sets the session ID - * const statefulTransport = new StreamableHTTPServerTransport({ - * sessionIdGenerator: () => randomUUID(), - * }); - * - * // Stateless mode - explicitly set session ID to undefined - * const statelessTransport = new StreamableHTTPServerTransport({ - * sessionIdGenerator: undefined, - * }); - * - * // Using with pre-parsed request body - * app.post('/mcp', (req, res) => { - * transport.handleRequest(req, res, req.body); - * }); - * ``` - * - * In stateful mode: - * - Session ID is generated and included in response headers - * - Session ID is always included in initialization responses - * - Requests with invalid session IDs are rejected with 404 Not Found - * - Non-initialization requests without a session ID are rejected with 400 Bad Request - * - State is maintained in-memory (connections, message history) - * - * In stateless mode: - * - No Session ID is included in any responses - * - No session validation is performed - */ -export declare class StreamableHTTPServerTransport implements Transport { - private sessionIdGenerator; - private _started; - private _streamMapping; - private _requestToStreamMapping; - private _requestResponseMap; - private _initialized; - private _enableJsonResponse; - private _standaloneSseStreamId; - private _eventStore?; - private _onsessioninitialized?; - private _onsessionclosed?; - private _allowedHosts?; - private _allowedOrigins?; - private _enableDnsRebindingProtection; - sessionId?: string; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; - constructor(options: StreamableHTTPServerTransportOptions); - /** - * Starts the transport. This is required by the Transport interface but is a no-op - * for the Streamable HTTP transport as connections are managed per-request. - */ - start(): Promise; - /** - * Validates request headers for DNS rebinding protection. - * @returns Error message if validation fails, undefined if validation passes. - */ - private validateRequestHeaders; - /** - * Handles an incoming HTTP request, whether GET or POST - */ - handleRequest(req: IncomingMessage & { - auth?: AuthInfo; - }, res: ServerResponse, parsedBody?: unknown): Promise; - /** - * Handles GET requests for SSE stream - */ - private handleGetRequest; - /** - * Replays events that would have been sent after the specified event ID - * Only used when resumability is enabled - */ - private replayEvents; - /** - * Writes an event to the SSE stream with proper formatting - */ - private writeSSEEvent; - /** - * Handles unsupported requests (PUT, PATCH, etc.) - */ - private handleUnsupportedRequest; - /** - * Handles POST requests containing JSON-RPC messages - */ - private handlePostRequest; - /** - * Handles DELETE requests to terminate sessions - */ - private handleDeleteRequest; - /** - * Validates session ID for non-initialization requests - * Returns true if the session is valid, false otherwise - */ - private validateSession; - private validateProtocolVersion; - close(): Promise; - send(message: JSONRPCMessage, options?: { - relatedRequestId?: RequestId; - }): Promise; -} -//# sourceMappingURL=streamableHttp.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/streamableHttp.d.ts.map b/dist/esm/server/streamableHttp.d.ts.map deleted file mode 100644 index b0b33e921d..0000000000 --- a/dist/esm/server/streamableHttp.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"streamableHttp.d.ts","sourceRoot":"","sources":["../../../src/server/streamableHttp.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EACH,gBAAgB,EAMh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EG;YACW,mBAAmB;IAYjC;;;OAGG;IACH,OAAO,CAAC,eAAe;IAkEvB,OAAO,CAAC,uBAAuB;IAsBzB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAYtB,IAAI,CAAC,OAAO,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE;QAAE,gBAAgB,CAAC,EAAE,SAAS,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CA+FjG"} \ No newline at end of file diff --git a/dist/esm/server/streamableHttp.js b/dist/esm/server/streamableHttp.js deleted file mode 100644 index c528954670..0000000000 --- a/dist/esm/server/streamableHttp.js +++ /dev/null @@ -1,624 +0,0 @@ -import { isInitializeRequest, isJSONRPCError, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessageSchema, SUPPORTED_PROTOCOL_VERSIONS, DEFAULT_NEGOTIATED_PROTOCOL_VERSION } from '../types.js'; -import getRawBody from 'raw-body'; -import contentType from 'content-type'; -import { randomUUID } from 'node:crypto'; -const MAXIMUM_MESSAGE_SIZE = '4mb'; -/** - * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. - * It supports both SSE streaming and direct HTTP responses. - * - * Usage example: - * - * ```typescript - * // Stateful mode - server sets the session ID - * const statefulTransport = new StreamableHTTPServerTransport({ - * sessionIdGenerator: () => randomUUID(), - * }); - * - * // Stateless mode - explicitly set session ID to undefined - * const statelessTransport = new StreamableHTTPServerTransport({ - * sessionIdGenerator: undefined, - * }); - * - * // Using with pre-parsed request body - * app.post('/mcp', (req, res) => { - * transport.handleRequest(req, res, req.body); - * }); - * ``` - * - * In stateful mode: - * - Session ID is generated and included in response headers - * - Session ID is always included in initialization responses - * - Requests with invalid session IDs are rejected with 404 Not Found - * - Non-initialization requests without a session ID are rejected with 400 Bad Request - * - State is maintained in-memory (connections, message history) - * - * In stateless mode: - * - No Session ID is included in any responses - * - No session validation is performed - */ -export class StreamableHTTPServerTransport { - constructor(options) { - var _a, _b; - this._started = false; - this._streamMapping = new Map(); - this._requestToStreamMapping = new Map(); - this._requestResponseMap = new Map(); - this._initialized = false; - this._enableJsonResponse = false; - this._standaloneSseStreamId = '_GET_stream'; - this.sessionIdGenerator = options.sessionIdGenerator; - this._enableJsonResponse = (_a = options.enableJsonResponse) !== null && _a !== void 0 ? _a : false; - this._eventStore = options.eventStore; - this._onsessioninitialized = options.onsessioninitialized; - this._onsessionclosed = options.onsessionclosed; - this._allowedHosts = options.allowedHosts; - this._allowedOrigins = options.allowedOrigins; - this._enableDnsRebindingProtection = (_b = options.enableDnsRebindingProtection) !== null && _b !== void 0 ? _b : false; - } - /** - * Starts the transport. This is required by the Transport interface but is a no-op - * for the Streamable HTTP transport as connections are managed per-request. - */ - async start() { - if (this._started) { - throw new Error('Transport already started'); - } - this._started = true; - } - /** - * Validates request headers for DNS rebinding protection. - * @returns Error message if validation fails, undefined if validation passes. - */ - validateRequestHeaders(req) { - // Skip validation if protection is not enabled - if (!this._enableDnsRebindingProtection) { - return undefined; - } - // Validate Host header if allowedHosts is configured - if (this._allowedHosts && this._allowedHosts.length > 0) { - const hostHeader = req.headers.host; - if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { - return `Invalid Host header: ${hostHeader}`; - } - } - // Validate Origin header if allowedOrigins is configured - if (this._allowedOrigins && this._allowedOrigins.length > 0) { - const originHeader = req.headers.origin; - if (!originHeader || !this._allowedOrigins.includes(originHeader)) { - return `Invalid Origin header: ${originHeader}`; - } - } - return undefined; - } - /** - * Handles an incoming HTTP request, whether GET or POST - */ - async handleRequest(req, res, parsedBody) { - var _a; - // Validate request headers for DNS rebinding protection - const validationError = this.validateRequestHeaders(req); - if (validationError) { - res.writeHead(403).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: validationError - }, - id: null - })); - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error(validationError)); - return; - } - if (req.method === 'POST') { - await this.handlePostRequest(req, res, parsedBody); - } - else if (req.method === 'GET') { - await this.handleGetRequest(req, res); - } - else if (req.method === 'DELETE') { - await this.handleDeleteRequest(req, res); - } - else { - await this.handleUnsupportedRequest(res); - } - } - /** - * Handles GET requests for SSE stream - */ - async handleGetRequest(req, res) { - // The client MUST include an Accept header, listing text/event-stream as a supported content type. - const acceptHeader = req.headers.accept; - if (!(acceptHeader === null || acceptHeader === void 0 ? void 0 : acceptHeader.includes('text/event-stream'))) { - res.writeHead(406).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Not Acceptable: Client must accept text/event-stream' - }, - id: null - })); - return; - } - // If an Mcp-Session-Id is returned by the server during initialization, - // clients using the Streamable HTTP transport MUST include it - // in the Mcp-Session-Id header on all of their subsequent HTTP requests. - if (!this.validateSession(req, res)) { - return; - } - if (!this.validateProtocolVersion(req, res)) { - return; - } - // Handle resumability: check for Last-Event-ID header - if (this._eventStore) { - const lastEventId = req.headers['last-event-id']; - if (lastEventId) { - await this.replayEvents(lastEventId, res); - return; - } - } - // The server MUST either return Content-Type: text/event-stream in response to this HTTP GET, - // or else return HTTP 405 Method Not Allowed - const headers = { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }; - // After initialization, always include the session ID if we have one - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - // Check if there's already an active standalone SSE stream for this session - if (this._streamMapping.get(this._standaloneSseStreamId) !== undefined) { - // Only one GET SSE stream is allowed per session - res.writeHead(409).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Conflict: Only one SSE stream is allowed per session' - }, - id: null - })); - return; - } - // We need to send headers immediately as messages will arrive much later, - // otherwise the client will just wait for the first message - res.writeHead(200, headers).flushHeaders(); - // Assign the response to the standalone SSE stream - this._streamMapping.set(this._standaloneSseStreamId, res); - // Set up close handler for client disconnects - res.on('close', () => { - this._streamMapping.delete(this._standaloneSseStreamId); - }); - // Add error handler for standalone SSE stream - res.on('error', error => { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }); - } - /** - * Replays events that would have been sent after the specified event ID - * Only used when resumability is enabled - */ - async replayEvents(lastEventId, res) { - var _a, _b; - if (!this._eventStore) { - return; - } - try { - const headers = { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }; - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - res.writeHead(200, headers).flushHeaders(); - const streamId = await ((_a = this._eventStore) === null || _a === void 0 ? void 0 : _a.replayEventsAfter(lastEventId, { - send: async (eventId, message) => { - var _a; - if (!this.writeSSEEvent(res, message, eventId)) { - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, new Error('Failed replay events')); - res.end(); - } - } - })); - this._streamMapping.set(streamId, res); - // Add error handler for replay stream - res.on('error', error => { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }); - } - catch (error) { - (_b = this.onerror) === null || _b === void 0 ? void 0 : _b.call(this, error); - } - } - /** - * Writes an event to the SSE stream with proper formatting - */ - writeSSEEvent(res, message, eventId) { - let eventData = `event: message\n`; - // Include event ID if provided - this is important for resumability - if (eventId) { - eventData += `id: ${eventId}\n`; - } - eventData += `data: ${JSON.stringify(message)}\n\n`; - return res.write(eventData); - } - /** - * Handles unsupported requests (PUT, PATCH, etc.) - */ - async handleUnsupportedRequest(res) { - res.writeHead(405, { - Allow: 'GET, POST, DELETE' - }).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Method not allowed.' - }, - id: null - })); - } - /** - * Handles POST requests containing JSON-RPC messages - */ - async handlePostRequest(req, res, parsedBody) { - var _a, _b, _c, _d, _e; - try { - // Validate the Accept header - const acceptHeader = req.headers.accept; - // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types. - if (!(acceptHeader === null || acceptHeader === void 0 ? void 0 : acceptHeader.includes('application/json')) || !acceptHeader.includes('text/event-stream')) { - res.writeHead(406).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Not Acceptable: Client must accept both application/json and text/event-stream' - }, - id: null - })); - return; - } - const ct = req.headers['content-type']; - if (!ct || !ct.includes('application/json')) { - res.writeHead(415).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Unsupported Media Type: Content-Type must be application/json' - }, - id: null - })); - return; - } - const authInfo = req.auth; - const requestInfo = { headers: req.headers }; - let rawMessage; - if (parsedBody !== undefined) { - rawMessage = parsedBody; - } - else { - const parsedCt = contentType.parse(ct); - const body = await getRawBody(req, { - limit: MAXIMUM_MESSAGE_SIZE, - encoding: (_a = parsedCt.parameters.charset) !== null && _a !== void 0 ? _a : 'utf-8' - }); - rawMessage = JSON.parse(body.toString()); - } - let messages; - // handle batch and single messages - if (Array.isArray(rawMessage)) { - messages = rawMessage.map(msg => JSONRPCMessageSchema.parse(msg)); - } - else { - messages = [JSONRPCMessageSchema.parse(rawMessage)]; - } - // Check if this is an initialization request - // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/ - const isInitializationRequest = messages.some(isInitializeRequest); - if (isInitializationRequest) { - // If it's a server with session management and the session ID is already set we should reject the request - // to avoid re-initialization. - if (this._initialized && this.sessionId !== undefined) { - res.writeHead(400).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32600, - message: 'Invalid Request: Server already initialized' - }, - id: null - })); - return; - } - if (messages.length > 1) { - res.writeHead(400).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32600, - message: 'Invalid Request: Only one initialization request is allowed' - }, - id: null - })); - return; - } - this.sessionId = (_b = this.sessionIdGenerator) === null || _b === void 0 ? void 0 : _b.call(this); - this._initialized = true; - // If we have a session ID and an onsessioninitialized handler, call it immediately - // This is needed in cases where the server needs to keep track of multiple sessions - if (this.sessionId && this._onsessioninitialized) { - await Promise.resolve(this._onsessioninitialized(this.sessionId)); - } - } - if (!isInitializationRequest) { - // If an Mcp-Session-Id is returned by the server during initialization, - // clients using the Streamable HTTP transport MUST include it - // in the Mcp-Session-Id header on all of their subsequent HTTP requests. - if (!this.validateSession(req, res)) { - return; - } - // Mcp-Protocol-Version header is required for all requests after initialization. - if (!this.validateProtocolVersion(req, res)) { - return; - } - } - // check if it contains requests - const hasRequests = messages.some(isJSONRPCRequest); - if (!hasRequests) { - // if it only contains notifications or responses, return 202 - res.writeHead(202).end(); - // handle each message - for (const message of messages) { - (_c = this.onmessage) === null || _c === void 0 ? void 0 : _c.call(this, message, { authInfo, requestInfo }); - } - } - else if (hasRequests) { - // The default behavior is to use SSE streaming - // but in some cases server will return JSON responses - const streamId = randomUUID(); - if (!this._enableJsonResponse) { - const headers = { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache', - Connection: 'keep-alive' - }; - // After initialization, always include the session ID if we have one - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - res.writeHead(200, headers); - } - // Store the response for this request to send messages back through this connection - // We need to track by request ID to maintain the connection - for (const message of messages) { - if (isJSONRPCRequest(message)) { - this._streamMapping.set(streamId, res); - this._requestToStreamMapping.set(message.id, streamId); - } - } - // Set up close handler for client disconnects - res.on('close', () => { - this._streamMapping.delete(streamId); - }); - // Add error handler for stream write errors - res.on('error', error => { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - }); - // handle each message - for (const message of messages) { - (_d = this.onmessage) === null || _d === void 0 ? void 0 : _d.call(this, message, { authInfo, requestInfo }); - } - // The server SHOULD NOT close the SSE stream before sending all JSON-RPC responses - // This will be handled by the send() method when responses are ready - } - } - catch (error) { - // return JSON-RPC formatted error - res.writeHead(400).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32700, - message: 'Parse error', - data: String(error) - }, - id: null - })); - (_e = this.onerror) === null || _e === void 0 ? void 0 : _e.call(this, error); - } - } - /** - * Handles DELETE requests to terminate sessions - */ - async handleDeleteRequest(req, res) { - var _a; - if (!this.validateSession(req, res)) { - return; - } - if (!this.validateProtocolVersion(req, res)) { - return; - } - await Promise.resolve((_a = this._onsessionclosed) === null || _a === void 0 ? void 0 : _a.call(this, this.sessionId)); - await this.close(); - res.writeHead(200).end(); - } - /** - * Validates session ID for non-initialization requests - * Returns true if the session is valid, false otherwise - */ - validateSession(req, res) { - if (this.sessionIdGenerator === undefined) { - // If the sessionIdGenerator ID is not set, the session management is disabled - // and we don't need to validate the session ID - return true; - } - if (!this._initialized) { - // If the server has not been initialized yet, reject all requests - res.writeHead(400).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: Server not initialized' - }, - id: null - })); - return false; - } - const sessionId = req.headers['mcp-session-id']; - if (!sessionId) { - // Non-initialization requests without a session ID should return 400 Bad Request - res.writeHead(400).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: Mcp-Session-Id header is required' - }, - id: null - })); - return false; - } - else if (Array.isArray(sessionId)) { - res.writeHead(400).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Bad Request: Mcp-Session-Id header must be a single value' - }, - id: null - })); - return false; - } - else if (sessionId !== this.sessionId) { - // Reject requests with invalid session ID with 404 Not Found - res.writeHead(404).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32001, - message: 'Session not found' - }, - id: null - })); - return false; - } - return true; - } - validateProtocolVersion(req, res) { - var _a; - let protocolVersion = (_a = req.headers['mcp-protocol-version']) !== null && _a !== void 0 ? _a : DEFAULT_NEGOTIATED_PROTOCOL_VERSION; - if (Array.isArray(protocolVersion)) { - protocolVersion = protocolVersion[protocolVersion.length - 1]; - } - if (!SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) { - res.writeHead(400).end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: `Bad Request: Unsupported protocol version (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(', ')})` - }, - id: null - })); - return false; - } - return true; - } - async close() { - var _a; - // Close all SSE connections - this._streamMapping.forEach(response => { - response.end(); - }); - this._streamMapping.clear(); - // Clear any pending responses - this._requestResponseMap.clear(); - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - } - async send(message, options) { - let requestId = options === null || options === void 0 ? void 0 : options.relatedRequestId; - if (isJSONRPCResponse(message) || isJSONRPCError(message)) { - // If the message is a response, use the request ID from the message - requestId = message.id; - } - // Check if this message should be sent on the standalone SSE stream (no request ID) - // Ignore notifications from tools (which have relatedRequestId set) - // Those will be sent via dedicated response SSE streams - if (requestId === undefined) { - // For standalone SSE streams, we can only send requests and notifications - if (isJSONRPCResponse(message) || isJSONRPCError(message)) { - throw new Error('Cannot send a response on a standalone SSE stream unless resuming a previous client request'); - } - const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); - if (standaloneSse === undefined) { - // The spec says the server MAY send messages on the stream, so it's ok to discard if no stream - return; - } - // Generate and store event ID if event store is provided - let eventId; - if (this._eventStore) { - // Stores the event and gets the generated event ID - eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); - } - // Send the message to the standalone SSE stream - this.writeSSEEvent(standaloneSse, message, eventId); - return; - } - // Get the response for this request - const streamId = this._requestToStreamMapping.get(requestId); - const response = this._streamMapping.get(streamId); - if (!streamId) { - throw new Error(`No connection established for request ID: ${String(requestId)}`); - } - if (!this._enableJsonResponse) { - // For SSE responses, generate event ID if event store is provided - let eventId; - if (this._eventStore) { - eventId = await this._eventStore.storeEvent(streamId, message); - } - if (response) { - // Write the event to the response stream - this.writeSSEEvent(response, message, eventId); - } - } - if (isJSONRPCResponse(message) || isJSONRPCError(message)) { - this._requestResponseMap.set(requestId, message); - const relatedIds = Array.from(this._requestToStreamMapping.entries()) - .filter(([_, streamId]) => this._streamMapping.get(streamId) === response) - .map(([id]) => id); - // Check if we have responses for all requests using this connection - const allResponsesReady = relatedIds.every(id => this._requestResponseMap.has(id)); - if (allResponsesReady) { - if (!response) { - throw new Error(`No connection established for request ID: ${String(requestId)}`); - } - if (this._enableJsonResponse) { - // All responses ready, send as JSON - const headers = { - 'Content-Type': 'application/json' - }; - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - const responses = relatedIds.map(id => this._requestResponseMap.get(id)); - response.writeHead(200, headers); - if (responses.length === 1) { - response.end(JSON.stringify(responses[0])); - } - else { - response.end(JSON.stringify(responses)); - } - } - else { - // End the SSE stream - response.end(); - } - // Clean up - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - } - } - } -} -//# sourceMappingURL=streamableHttp.js.map \ No newline at end of file diff --git a/dist/esm/server/streamableHttp.js.map b/dist/esm/server/streamableHttp.js.map deleted file mode 100644 index 34df3a2173..0000000000 --- a/dist/esm/server/streamableHttp.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"streamableHttp.js","sourceRoot":"","sources":["../../../src/server/streamableHttp.ts"],"names":[],"mappings":"AAEA,OAAO,EAGH,mBAAmB,EACnB,cAAc,EACd,gBAAgB,EAChB,iBAAiB,EAEjB,oBAAoB,EAEpB,2BAA2B,EAC3B,mCAAmC,EACtC,MAAM,aAAa,CAAC;AACrB,OAAO,UAAU,MAAM,UAAU,CAAC;AAClC,OAAO,WAAW,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAGzC,MAAM,oBAAoB,GAAG,KAAK,CAAC;AA4FnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAM,OAAO,6BAA6B;IAsBtC,YAAY,OAA6C;;QAnBjD,aAAQ,GAAY,KAAK,CAAC;QAC1B,mBAAc,GAAgC,IAAI,GAAG,EAAE,CAAC;QACxD,4BAAuB,GAA2B,IAAI,GAAG,EAAE,CAAC;QAC5D,wBAAmB,GAAmC,IAAI,GAAG,EAAE,CAAC;QAChE,iBAAY,GAAY,KAAK,CAAC;QAC9B,wBAAmB,GAAY,KAAK,CAAC;QACrC,2BAAsB,GAAW,aAAa,CAAC;QAcnD,IAAI,CAAC,kBA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AAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;oBAC/C,CAAC;yBAAM,CAAC;wBACJ,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,CAAC,CAAC;oBAC5C,CAAC;gBACL,CAAC;qBAAM,CAAC;oBACJ,qBAAqB;oBACrB,QAAQ,CAAC,GAAG,EAAE,CAAC;gBACnB,CAAC;gBACD,WAAW;gBACX,KAAK,MAAM,EAAE,IAAI,UAAU,EAAE,CAAC;oBAC1B,IAAI,CAAC,mBAAmB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;oBACpC,IAAI,CAAC,uBAAuB,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBAC5C,CAAC;YACL,CAAC;QACL,CAAC;IACL,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/server/zod-compat.d.ts b/dist/esm/server/zod-compat.d.ts deleted file mode 100644 index 13fb9723c5..0000000000 --- a/dist/esm/server/zod-compat.d.ts +++ /dev/null @@ -1,82 +0,0 @@ -import type * as z3 from 'zod/v3'; -import type * as z4 from 'zod/v4/core'; -export type AnySchema = z3.ZodTypeAny | z4.$ZodType; -export type AnyObjectSchema = z3.AnyZodObject | z4.$ZodObject | AnySchema; -export type ZodRawShapeCompat = Record; -export interface ZodV3Internal { - _def?: { - typeName?: string; - value?: unknown; - values?: unknown[]; - shape?: Record | (() => Record); - description?: string; - }; - shape?: Record | (() => Record); - value?: unknown; -} -export interface ZodV4Internal { - _zod?: { - def?: { - typeName?: string; - value?: unknown; - values?: unknown[]; - shape?: Record | (() => Record); - description?: string; - }; - }; - value?: unknown; -} -export type SchemaOutput = S extends z3.ZodTypeAny ? z3.infer : S extends z4.$ZodType ? z4.output : never; -export type SchemaInput = S extends z3.ZodTypeAny ? z3.input : S extends z4.$ZodType ? z4.input : never; -/** - * Infers the output type from a ZodRawShapeCompat (raw shape object). - * Maps over each key in the shape and infers the output type from each schema. - */ -export type ShapeOutput = { - [K in keyof Shape]: SchemaOutput; -}; -export declare function isZ4Schema(s: AnySchema): s is z4.$ZodType; -export declare function objectFromShape(shape: ZodRawShapeCompat): AnyObjectSchema; -export declare function safeParse(schema: S, data: unknown): { - success: true; - data: SchemaOutput; -} | { - success: false; - error: unknown; -}; -export declare function safeParseAsync(schema: S, data: unknown): Promise<{ - success: true; - data: SchemaOutput; -} | { - success: false; - error: unknown; -}>; -export declare function getObjectShape(schema: AnyObjectSchema | undefined): Record | undefined; -/** - * Normalizes a schema to an object schema. Handles both: - * - Already-constructed object schemas (v3 or v4) - * - Raw shapes that need to be wrapped into object schemas - */ -export declare function normalizeObjectSchema(schema: AnySchema | ZodRawShapeCompat | undefined): AnyObjectSchema | undefined; -/** - * Safely extracts an error message from a parse result error. - * Zod errors can have different structures, so we handle various cases. - */ -export declare function getParseErrorMessage(error: unknown): string; -/** - * Gets the description from a schema, if available. - * Works with both Zod v3 and v4. - */ -export declare function getSchemaDescription(schema: AnySchema): string | undefined; -/** - * Checks if a schema is optional. - * Works with both Zod v3 and v4. - */ -export declare function isSchemaOptional(schema: AnySchema): boolean; -/** - * Gets the literal value from a schema, if it's a literal schema. - * Works with both Zod v3 and v4. - * Returns undefined if the schema is not a literal or the value cannot be determined. - */ -export declare function getLiteralValue(schema: AnySchema): unknown; -//# sourceMappingURL=zod-compat.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/zod-compat.d.ts.map b/dist/esm/server/zod-compat.d.ts.map deleted file mode 100644 index 608ca930c3..0000000000 --- a/dist/esm/server/zod-compat.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"zod-compat.d.ts","sourceRoot":"","sources":["../../../src/server/zod-compat.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,KAAK,EAAE,MAAM,QAAQ,CAAC;AAClC,OAAO,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAMvC,MAAM,MAAM,SAAS,GAAG,EAAE,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AG,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,SAAS,CAyBzG;AAGD;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,SAAS,GAAG,iBAAiB,GAAG,SAAS,GAAG,eAAe,GAAG,SAAS,CAiDpH;AAGD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAoB3D;AAGD;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,SAAS,GAAG,MAAM,GAAG,SAAS,CAQ1E;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAW3D;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,GAAG,OAAO,CAwB1D"} \ No newline at end of file diff --git a/dist/esm/server/zod-compat.js b/dist/esm/server/zod-compat.js deleted file mode 100644 index 0ff17cc10e..0000000000 --- a/dist/esm/server/zod-compat.js +++ /dev/null @@ -1,217 +0,0 @@ -// zod-compat.ts -// ---------------------------------------------------- -// Unified types + helpers to accept Zod v3 and v4 (Mini) -// ---------------------------------------------------- -import * as z3rt from 'zod/v3'; -import * as z4mini from 'zod/v4-mini'; -// --- Runtime detection --- -export function isZ4Schema(s) { - // Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3 - const schema = s; - return !!schema._zod; -} -// --- Schema construction --- -export function objectFromShape(shape) { - const values = Object.values(shape); - if (values.length === 0) - return z4mini.object({}); // default to v4 Mini - const allV4 = values.every(isZ4Schema); - const allV3 = values.every(s => !isZ4Schema(s)); - if (allV4) - return z4mini.object(shape); - if (allV3) - return z3rt.object(shape); - throw new Error('Mixed Zod versions detected in object shape.'); -} -// --- Unified parsing --- -export function safeParse(schema, data) { - if (isZ4Schema(schema)) { - // Mini exposes top-level safeParse - const result = z4mini.safeParse(schema, data); - return result; - } - const v3Schema = schema; - const result = v3Schema.safeParse(data); - return result; -} -export async function safeParseAsync(schema, data) { - if (isZ4Schema(schema)) { - // Mini exposes top-level safeParseAsync - const result = await z4mini.safeParseAsync(schema, data); - return result; - } - const v3Schema = schema; - const result = await v3Schema.safeParseAsync(data); - return result; -} -// --- Shape extraction --- -export function getObjectShape(schema) { - var _a, _b; - if (!schema) - return undefined; - // Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape` - let rawShape; - if (isZ4Schema(schema)) { - const v4Schema = schema; - rawShape = (_b = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def) === null || _b === void 0 ? void 0 : _b.shape; - } - else { - const v3Schema = schema; - rawShape = v3Schema.shape; - } - if (!rawShape) - return undefined; - if (typeof rawShape === 'function') { - try { - return rawShape(); - } - catch (_c) { - return undefined; - } - } - return rawShape; -} -// --- Schema normalization --- -/** - * Normalizes a schema to an object schema. Handles both: - * - Already-constructed object schemas (v3 or v4) - * - Raw shapes that need to be wrapped into object schemas - */ -export function normalizeObjectSchema(schema) { - var _a; - if (!schema) - return undefined; - // First check if it's a raw shape (Record) - // Raw shapes don't have _def or _zod properties and aren't schemas themselves - if (typeof schema === 'object') { - // Check if it's actually a ZodRawShapeCompat (not a schema instance) - // by checking if it lacks schema-like internal properties - const asV3 = schema; - const asV4 = schema; - // If it's not a schema instance (no _def or _zod), it might be a raw shape - if (!asV3._def && !asV4._zod) { - // Check if all values are schemas (heuristic to confirm it's a raw shape) - const values = Object.values(schema); - if (values.length > 0 && - values.every(v => typeof v === 'object' && - v !== null && - (v._def !== undefined || - v._zod !== undefined || - typeof v.parse === 'function'))) { - return objectFromShape(schema); - } - } - } - // If we get here, it should be an AnySchema (not a raw shape) - // Check if it's already an object schema - if (isZ4Schema(schema)) { - // Check if it's a v4 object - const v4Schema = schema; - const def = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def; - if (def && (def.typeName === 'object' || def.shape !== undefined)) { - return schema; - } - } - else { - // Check if it's a v3 object - const v3Schema = schema; - if (v3Schema.shape !== undefined) { - return schema; - } - } - return undefined; -} -// --- Error message extraction --- -/** - * Safely extracts an error message from a parse result error. - * Zod errors can have different structures, so we handle various cases. - */ -export function getParseErrorMessage(error) { - if (error && typeof error === 'object') { - // Try common error structures - if ('message' in error && typeof error.message === 'string') { - return error.message; - } - if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) { - const firstIssue = error.issues[0]; - if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) { - return String(firstIssue.message); - } - } - // Fallback: try to stringify the error - try { - return JSON.stringify(error); - } - catch (_a) { - return String(error); - } - } - return String(error); -} -// --- Schema metadata access --- -/** - * Gets the description from a schema, if available. - * Works with both Zod v3 and v4. - */ -export function getSchemaDescription(schema) { - var _a, _b, _c, _d; - if (isZ4Schema(schema)) { - const v4Schema = schema; - return (_b = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def) === null || _b === void 0 ? void 0 : _b.description; - } - const v3Schema = schema; - // v3 may have description on the schema itself or in _def - return (_c = schema.description) !== null && _c !== void 0 ? _c : (_d = v3Schema._def) === null || _d === void 0 ? void 0 : _d.description; -} -/** - * Checks if a schema is optional. - * Works with both Zod v3 and v4. - */ -export function isSchemaOptional(schema) { - var _a, _b, _c; - if (isZ4Schema(schema)) { - const v4Schema = schema; - return ((_b = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def) === null || _b === void 0 ? void 0 : _b.typeName) === 'ZodOptional'; - } - const v3Schema = schema; - // v3 has isOptional() method - if (typeof schema.isOptional === 'function') { - return schema.isOptional(); - } - return ((_c = v3Schema._def) === null || _c === void 0 ? void 0 : _c.typeName) === 'ZodOptional'; -} -/** - * Gets the literal value from a schema, if it's a literal schema. - * Works with both Zod v3 and v4. - * Returns undefined if the schema is not a literal or the value cannot be determined. - */ -export function getLiteralValue(schema) { - var _a; - if (isZ4Schema(schema)) { - const v4Schema = schema; - const def = (_a = v4Schema._zod) === null || _a === void 0 ? void 0 : _a.def; - if (def) { - // Try various ways to get the literal value - if (def.value !== undefined) - return def.value; - if (Array.isArray(def.values) && def.values.length > 0) { - return def.values[0]; - } - } - } - const v3Schema = schema; - const def = v3Schema._def; - if (def) { - if (def.value !== undefined) - return def.value; - if (Array.isArray(def.values) && def.values.length > 0) { - return def.values[0]; - } - } - // Fallback: check for direct value property (some Zod versions) - const directValue = schema.value; - if (directValue !== undefined) - return directValue; - return undefined; -} -//# sourceMappingURL=zod-compat.js.map \ No newline at end of file diff --git a/dist/esm/server/zod-compat.js.map b/dist/esm/server/zod-compat.js.map deleted file mode 100644 index df880a39d4..0000000000 --- a/dist/esm/server/zod-compat.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"zod-compat.js","sourceRoot":"","sources":["../../../src/server/zod-compat.ts"],"names":[],"mappings":"AAAA,gBAAgB;AAChB,uDAAuD;AACvD,yDAAyD;AACzD,uDAAuD;AAKvD,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAC;AAC/B,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AA+CtC,4BAA4B;AAC5B,MAAM,UAAU,UAAU,CAAC,CAAY;IACnC,6DAA6D;IAC7D,MAAM,MAAM,GAAG,CAA6B,CAAC;IAC7C,OAAO,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC;AACzB,CAAC;AAED,8BAA8B;AAC9B,MAAM,UAAU,eAAe,CAAC,KAAwB;IACpD,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACpC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,qBAAqB;IAExE,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACvC,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;IAEhD,IAAI,KAAK;QAAE,OAAO,MAAM,CAAC,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AC,MAAM,CAAC,EAAE,CAAC;QACrB,MAAM,QAAQ,GAAG,MAAkC,CAAC;QACpD,MAAM,GAAG,GAAG,MAAA,QAAQ,CAAC,IAAI,0CAAE,GAAG,CAAC;QAC/B,IAAI,GAAG,EAAE,CAAC;YACN,4CAA4C;YAC5C,IAAI,GAAG,CAAC,KAAK,KAAK,SAAS;gBAAE,OAAO,GAAG,CAAC,KAAK,CAAC;YAC9C,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACrD,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;YACzB,CAAC;QACL,CAAC;IACL,CAAC;IACD,MAAM,QAAQ,GAAG,MAAkC,CAAC;IACpD,MAAM,GAAG,GAAG,QAAQ,CAAC,IAAI,CAAC;IAC1B,IAAI,GAAG,EAAE,CAAC;QACN,IAAI,GAAG,CAAC,KAAK,KAAK,SAAS;YAAE,OAAO,GAAG,CAAC,KAAK,CAAC;QAC9C,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,GAAG,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACrD,OAAO,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QACzB,CAAC;IACL,CAAC;IACD,gEAAgE;IAChE,MAAM,WAAW,GAAI,MAA8B,CAAC,KAAK,CAAC;IAC1D,IAAI,WAAW,KAAK,SAAS;QAAE,OAAO,WAAW,CAAC;IAClD,OAAO,SAAS,CAAC;AACrB,CAAC"} \ No newline at end of file diff --git a/dist/esm/server/zod-json-schema-compat.d.ts b/dist/esm/server/zod-json-schema-compat.d.ts deleted file mode 100644 index 3a04452b47..0000000000 --- a/dist/esm/server/zod-json-schema-compat.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { AnySchema, AnyObjectSchema } from './zod-compat.js'; -type JsonSchema = Record; -type CommonOpts = { - strictUnions?: boolean; - pipeStrategy?: 'input' | 'output'; - target?: 'jsonSchema7' | 'draft-7' | 'jsonSchema2019-09' | 'draft-2020-12'; -}; -export declare function toJsonSchemaCompat(schema: AnyObjectSchema, opts?: CommonOpts): JsonSchema; -export declare function getMethodLiteral(schema: AnyObjectSchema): string; -export declare function parseWithCompat(schema: AnySchema, data: unknown): unknown; -export {}; -//# sourceMappingURL=zod-json-schema-compat.d.ts.map \ No newline at end of file diff --git a/dist/esm/server/zod-json-schema-compat.d.ts.map b/dist/esm/server/zod-json-schema-compat.d.ts.map deleted file mode 100644 index 0b851bf50e..0000000000 --- a/dist/esm/server/zod-json-schema-compat.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"zod-json-schema-compat.d.ts","sourceRoot":"","sources":["../../../src/server/zod-json-schema-compat.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,SAAS,EAAE,eAAe,EAA0D,MAAM,iBAAiB,CAAC;AAGrH,KAAK,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAG1C,KAAK,UAAU,GAAG;IACd,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,YAAY,CAAC,EAAE,OAAO,GAAG,QAAQ,CAAC;IAClC,MAAM,CAAC,EAAE,aAAa,GAAG,SAAS,GAAG,mBAAmB,GAAG,eAAe,CAAC;CAC9E,CAAC;AASF,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,eAAe,EAAE,IAAI,CAAC,EAAE,UAAU,GAAG,UAAU,CAczF;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,eAAe,GAAG,MAAM,CAahE;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,GAAG,OAAO,CAMzE"} \ No newline at end of file diff --git a/dist/esm/server/zod-json-schema-compat.js b/dist/esm/server/zod-json-schema-compat.js deleted file mode 100644 index bd2a25f20a..0000000000 --- a/dist/esm/server/zod-json-schema-compat.js +++ /dev/null @@ -1,52 +0,0 @@ -// zod-json-schema-compat.ts -// ---------------------------------------------------- -// JSON Schema conversion for both Zod v3 and Zod v4 (Mini) -// v3 uses your vendored converter; v4 uses Mini's toJSONSchema -// ---------------------------------------------------- -import * as z4mini from 'zod/v4-mini'; -import { getObjectShape, safeParse, isZ4Schema, getLiteralValue } from './zod-compat.js'; -import { zodToJsonSchema } from 'zod-to-json-schema'; -function mapMiniTarget(t) { - if (!t) - return 'draft-7'; - if (t === 'jsonSchema7' || t === 'draft-7') - return 'draft-7'; - if (t === 'jsonSchema2019-09' || t === 'draft-2020-12') - return 'draft-2020-12'; - return 'draft-7'; // fallback -} -export function toJsonSchemaCompat(schema, opts) { - var _a, _b, _c; - if (isZ4Schema(schema)) { - // v4 branch — use Mini's built-in toJSONSchema - return z4mini.toJSONSchema(schema, { - target: mapMiniTarget(opts === null || opts === void 0 ? void 0 : opts.target), - io: (_a = opts === null || opts === void 0 ? void 0 : opts.pipeStrategy) !== null && _a !== void 0 ? _a : 'input' - }); - } - // v3 branch — use vendored converter - return zodToJsonSchema(schema, { - strictUnions: (_b = opts === null || opts === void 0 ? void 0 : opts.strictUnions) !== null && _b !== void 0 ? _b : true, - pipeStrategy: (_c = opts === null || opts === void 0 ? void 0 : opts.pipeStrategy) !== null && _c !== void 0 ? _c : 'input' - }); -} -export function getMethodLiteral(schema) { - const shape = getObjectShape(schema); - const methodSchema = shape === null || shape === void 0 ? void 0 : shape.method; - if (!methodSchema) { - throw new Error('Schema is missing a method literal'); - } - const value = getLiteralValue(methodSchema); - if (typeof value !== 'string') { - throw new Error('Schema method literal must be a string'); - } - return value; -} -export function parseWithCompat(schema, data) { - const result = safeParse(schema, data); - if (!result.success) { - throw result.error; - } - return result.data; -} -//# sourceMappingURL=zod-json-schema-compat.js.map \ No newline at end of file diff --git a/dist/esm/server/zod-json-schema-compat.js.map b/dist/esm/server/zod-json-schema-compat.js.map deleted file mode 100644 index d6973cb1c9..0000000000 --- a/dist/esm/server/zod-json-schema-compat.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"zod-json-schema-compat.js","sourceRoot":"","sources":["../../../src/server/zod-json-schema-compat.ts"],"names":[],"mappings":"AAAA,4BAA4B;AAC5B,uDAAuD;AACvD,2DAA2D;AAC3D,+DAA+D;AAC/D,uDAAuD;AAKvD,OAAO,KAAK,MAAM,MAAM,aAAa,CAAC;AAEtC,OAAO,EAA8B,cAAc,EAAE,SAAS,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AACrH,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAWrD,SAAS,aAAa,CAAC,CAAmC;IACtD,IAAI,CAAC,CAAC;QAAE,OAAO,SAAS,CAAC;IACzB,IAAI,CAAC,KAAK,aAAa,IAAI,CAAC,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC7D,IAAI,CAAC,KAAK,mBAAmB,IAAI,CAAC,KAAK,eAAe;QAAE,OAAO,eAAe,CAAC;IAC/E,OAAO,SAAS,CAAC,CAAC,WAAW;AACjC,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,MAAuB,EAAE,IAAiB;;IACzE,IAAI,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC;QACrB,+CAA+C;QAC/C,OAAO,MAAM,CAAC,YAAY,CAAC,MAAsB,EAAE;YAC/C,MAAM,EAAE,aAAa,CAAC,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,MAAM,CAAC;YACnC,EAAE,EAAE,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,YAAY,mCAAI,OAAO;SACpC,CAAe,CAAC;IACrB,CAAC;IAED,qCAAqC;IACrC,OAAO,eAAe,CAAC,MAAuB,EAAE;QAC5C,YAAY,EAAE,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,YAAY,mCAAI,IAAI;QACxC,YAAY,EAAE,MAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,YAAY,mCAAI,OAAO;KAC9C,CAAe,CAAC;AACrB,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,MAAuB;IACpD,MAAM,KAAK,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC;IACrC,MAAM,YAAY,GAAG,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,MAA+B,CAAC;IAC5D,IAAI,CAAC,YAAY,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;IAC1D,CAAC;IAED,MAAM,KAAK,GAAG,eAAe,CAAC,YAAY,CAAC,CAAC;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC5B,MAAM,IAAI,KAAK,CAAC,wCAAwC,CAAC,CAAC;IAC9D,CAAC;IAED,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,MAAiB,EAAE,IAAa;IAC5D,MAAM,MAAM,GAAG,SAAS,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;IACvC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QAClB,MAAM,MAAM,CAAC,KAAK,CAAC;IACvB,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC;AACvB,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/auth-utils.d.ts b/dist/esm/shared/auth-utils.d.ts deleted file mode 100644 index c966e30e74..0000000000 --- a/dist/esm/shared/auth-utils.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Utilities for handling OAuth resource URIs. - */ -/** - * Converts a server URL to a resource URL by removing the fragment. - * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". - * Keeps everything else unchanged (scheme, domain, port, path, query). - */ -export declare function resourceUrlFromServerUrl(url: URL | string): URL; -/** - * Checks if a requested resource URL matches a configured resource URL. - * A requested resource matches if it has the same scheme, domain, port, - * and its path starts with the configured resource's path. - * - * @param requestedResource The resource URL being requested - * @param configuredResource The resource URL that has been configured - * @returns true if the requested resource matches the configured resource, false otherwise - */ -export declare function checkResourceAllowed({ requestedResource, configuredResource }: { - requestedResource: URL | string; - configuredResource: URL | string; -}): boolean; -//# sourceMappingURL=auth-utils.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/auth-utils.d.ts.map b/dist/esm/shared/auth-utils.d.ts.map deleted file mode 100644 index 30873de552..0000000000 --- a/dist/esm/shared/auth-utils.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"auth-utils.d.ts","sourceRoot":"","sources":["../../../src/shared/auth-utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,GAAG,GAAG,CAI/D;AAED;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CAAC,EACjC,iBAAiB,EACjB,kBAAkB,EACrB,EAAE;IACC,iBAAiB,EAAE,GAAG,GAAG,MAAM,CAAC;IAChC,kBAAkB,EAAE,GAAG,GAAG,MAAM,CAAC;CACpC,GAAG,OAAO,CAwBV"} \ No newline at end of file diff --git a/dist/esm/shared/auth-utils.js b/dist/esm/shared/auth-utils.js deleted file mode 100644 index 1883885e40..0000000000 --- a/dist/esm/shared/auth-utils.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Utilities for handling OAuth resource URIs. - */ -/** - * Converts a server URL to a resource URL by removing the fragment. - * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". - * Keeps everything else unchanged (scheme, domain, port, path, query). - */ -export function resourceUrlFromServerUrl(url) { - const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href); - resourceURL.hash = ''; // Remove fragment - return resourceURL; -} -/** - * Checks if a requested resource URL matches a configured resource URL. - * A requested resource matches if it has the same scheme, domain, port, - * and its path starts with the configured resource's path. - * - * @param requestedResource The resource URL being requested - * @param configuredResource The resource URL that has been configured - * @returns true if the requested resource matches the configured resource, false otherwise - */ -export function checkResourceAllowed({ requestedResource, configuredResource }) { - const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href); - const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href); - // Compare the origin (scheme, domain, and port) - if (requested.origin !== configured.origin) { - return false; - } - // Handle cases like requested=/foo and configured=/foo/ - if (requested.pathname.length < configured.pathname.length) { - return false; - } - // Check if the requested path starts with the configured path - // Ensure both paths end with / for proper comparison - // This ensures that if we have paths like "/api" and "/api/users", - // we properly detect that "/api/users" is a subpath of "/api" - // By adding a trailing slash if missing, we avoid false positives - // where paths like "/api123" would incorrectly match "/api" - const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/'; - const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/'; - return requestedPath.startsWith(configuredPath); -} -//# sourceMappingURL=auth-utils.js.map \ No newline at end of file diff --git a/dist/esm/shared/auth-utils.js.map b/dist/esm/shared/auth-utils.js.map deleted file mode 100644 index 3ced5af407..0000000000 --- a/dist/esm/shared/auth-utils.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"auth-utils.js","sourceRoot":"","sources":["../../../src/shared/auth-utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH;;;;GAIG;AACH,MAAM,UAAU,wBAAwB,CAAC,GAAiB;IACtD,MAAM,WAAW,GAAG,OAAO,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAC/E,WAAW,CAAC,IAAI,GAAG,EAAE,CAAC,CAAC,kBAAkB;IACzC,OAAO,WAAW,CAAC;AACvB,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,oBAAoB,CAAC,EACjC,iBAAiB,EACjB,kBAAkB,EAIrB;IACG,MAAM,SAAS,GAAG,OAAO,iBAAiB,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;IACvH,MAAM,UAAU,GAAG,OAAO,kBAAkB,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,kBAAkB,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;IAE3H,gDAAgD;IAChD,IAAI,SAAS,CAAC,MAAM,KAAK,UAAU,CAAC,MAAM,EAAE,CAAC;QACzC,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,wDAAwD;IACxD,IAAI,SAAS,CAAC,QAAQ,CAAC,MAAM,GAAG,UAAU,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;QACzD,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,8DAA8D;IAC9D,qDAAqD;IACrD,mEAAmE;IACnE,8DAA8D;IAC9D,kEAAkE;IAClE,4DAA4D;IAC5D,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,GAAG,GAAG,CAAC;IACvG,MAAM,cAAc,GAAG,UAAU,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,GAAG,GAAG,CAAC;IAE3G,OAAO,aAAa,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;AACpD,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/auth.d.ts b/dist/esm/shared/auth.d.ts deleted file mode 100644 index c9e723a002..0000000000 --- a/dist/esm/shared/auth.d.ts +++ /dev/null @@ -1,240 +0,0 @@ -import * as z from 'zod/v4'; -/** - * Reusable URL validation that disallows javascript: scheme - */ -export declare const SafeUrlSchema: z.ZodURL; -/** - * RFC 9728 OAuth Protected Resource Metadata - */ -export declare const OAuthProtectedResourceMetadataSchema: z.ZodObject<{ - resource: z.ZodString; - authorization_servers: z.ZodOptional>; - jwks_uri: z.ZodOptional; - scopes_supported: z.ZodOptional>; - bearer_methods_supported: z.ZodOptional>; - resource_signing_alg_values_supported: z.ZodOptional>; - resource_name: z.ZodOptional; - resource_documentation: z.ZodOptional; - resource_policy_uri: z.ZodOptional; - resource_tos_uri: z.ZodOptional; - tls_client_certificate_bound_access_tokens: z.ZodOptional; - authorization_details_types_supported: z.ZodOptional>; - dpop_signing_alg_values_supported: z.ZodOptional>; - dpop_bound_access_tokens_required: z.ZodOptional; -}, z.core.$loose>; -/** - * RFC 8414 OAuth 2.0 Authorization Server Metadata - */ -export declare const OAuthMetadataSchema: z.ZodObject<{ - issuer: z.ZodString; - authorization_endpoint: z.ZodURL; - token_endpoint: z.ZodURL; - registration_endpoint: z.ZodOptional; - scopes_supported: z.ZodOptional>; - response_types_supported: z.ZodArray; - response_modes_supported: z.ZodOptional>; - grant_types_supported: z.ZodOptional>; - token_endpoint_auth_methods_supported: z.ZodOptional>; - token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; - service_documentation: z.ZodOptional; - revocation_endpoint: z.ZodOptional; - revocation_endpoint_auth_methods_supported: z.ZodOptional>; - revocation_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; - introspection_endpoint: z.ZodOptional; - introspection_endpoint_auth_methods_supported: z.ZodOptional>; - introspection_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; - code_challenge_methods_supported: z.ZodOptional>; - client_id_metadata_document_supported: z.ZodOptional; -}, z.core.$loose>; -/** - * OpenID Connect Discovery 1.0 Provider Metadata - * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata - */ -export declare const OpenIdProviderMetadataSchema: z.ZodObject<{ - issuer: z.ZodString; - authorization_endpoint: z.ZodURL; - token_endpoint: z.ZodURL; - userinfo_endpoint: z.ZodOptional; - jwks_uri: z.ZodURL; - registration_endpoint: z.ZodOptional; - scopes_supported: z.ZodOptional>; - response_types_supported: z.ZodArray; - response_modes_supported: z.ZodOptional>; - grant_types_supported: z.ZodOptional>; - acr_values_supported: z.ZodOptional>; - subject_types_supported: z.ZodArray; - id_token_signing_alg_values_supported: z.ZodArray; - id_token_encryption_alg_values_supported: z.ZodOptional>; - id_token_encryption_enc_values_supported: z.ZodOptional>; - userinfo_signing_alg_values_supported: z.ZodOptional>; - userinfo_encryption_alg_values_supported: z.ZodOptional>; - userinfo_encryption_enc_values_supported: z.ZodOptional>; - request_object_signing_alg_values_supported: z.ZodOptional>; - request_object_encryption_alg_values_supported: z.ZodOptional>; - request_object_encryption_enc_values_supported: z.ZodOptional>; - token_endpoint_auth_methods_supported: z.ZodOptional>; - token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; - display_values_supported: z.ZodOptional>; - claim_types_supported: z.ZodOptional>; - claims_supported: z.ZodOptional>; - service_documentation: z.ZodOptional; - claims_locales_supported: z.ZodOptional>; - ui_locales_supported: z.ZodOptional>; - claims_parameter_supported: z.ZodOptional; - request_parameter_supported: z.ZodOptional; - request_uri_parameter_supported: z.ZodOptional; - require_request_uri_registration: z.ZodOptional; - op_policy_uri: z.ZodOptional; - op_tos_uri: z.ZodOptional; - client_id_metadata_document_supported: z.ZodOptional; -}, z.core.$loose>; -/** - * OpenID Connect Discovery metadata that may include OAuth 2.0 fields - * This schema represents the real-world scenario where OIDC providers - * return a mix of OpenID Connect and OAuth 2.0 metadata fields - */ -export declare const OpenIdProviderDiscoveryMetadataSchema: z.ZodObject<{ - code_challenge_methods_supported: z.ZodOptional>; - issuer: z.ZodString; - authorization_endpoint: z.ZodURL; - token_endpoint: z.ZodURL; - userinfo_endpoint: z.ZodOptional; - jwks_uri: z.ZodURL; - registration_endpoint: z.ZodOptional; - scopes_supported: z.ZodOptional>; - response_types_supported: z.ZodArray; - response_modes_supported: z.ZodOptional>; - grant_types_supported: z.ZodOptional>; - acr_values_supported: z.ZodOptional>; - subject_types_supported: z.ZodArray; - id_token_signing_alg_values_supported: z.ZodArray; - id_token_encryption_alg_values_supported: z.ZodOptional>; - id_token_encryption_enc_values_supported: z.ZodOptional>; - userinfo_signing_alg_values_supported: z.ZodOptional>; - userinfo_encryption_alg_values_supported: z.ZodOptional>; - userinfo_encryption_enc_values_supported: z.ZodOptional>; - request_object_signing_alg_values_supported: z.ZodOptional>; - request_object_encryption_alg_values_supported: z.ZodOptional>; - request_object_encryption_enc_values_supported: z.ZodOptional>; - token_endpoint_auth_methods_supported: z.ZodOptional>; - token_endpoint_auth_signing_alg_values_supported: z.ZodOptional>; - display_values_supported: z.ZodOptional>; - claim_types_supported: z.ZodOptional>; - claims_supported: z.ZodOptional>; - service_documentation: z.ZodOptional; - claims_locales_supported: z.ZodOptional>; - ui_locales_supported: z.ZodOptional>; - claims_parameter_supported: z.ZodOptional; - request_parameter_supported: z.ZodOptional; - request_uri_parameter_supported: z.ZodOptional; - require_request_uri_registration: z.ZodOptional; - op_policy_uri: z.ZodOptional; - op_tos_uri: z.ZodOptional; - client_id_metadata_document_supported: z.ZodOptional; -}, z.core.$strip>; -/** - * OAuth 2.1 token response - */ -export declare const OAuthTokensSchema: z.ZodObject<{ - access_token: z.ZodString; - id_token: z.ZodOptional; - token_type: z.ZodString; - expires_in: z.ZodOptional; - scope: z.ZodOptional; - refresh_token: z.ZodOptional; -}, z.core.$strip>; -/** - * OAuth 2.1 error response - */ -export declare const OAuthErrorResponseSchema: z.ZodObject<{ - error: z.ZodString; - error_description: z.ZodOptional; - error_uri: z.ZodOptional; -}, z.core.$strip>; -/** - * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri - */ -export declare const OptionalSafeUrlSchema: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata - */ -export declare const OAuthClientMetadataSchema: z.ZodObject<{ - redirect_uris: z.ZodArray; - token_endpoint_auth_method: z.ZodOptional; - grant_types: z.ZodOptional>; - response_types: z.ZodOptional>; - client_name: z.ZodOptional; - client_uri: z.ZodOptional; - logo_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; - scope: z.ZodOptional; - contacts: z.ZodOptional>; - tos_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; - policy_uri: z.ZodOptional; - jwks_uri: z.ZodOptional; - jwks: z.ZodOptional; - software_id: z.ZodOptional; - software_version: z.ZodOptional; - software_statement: z.ZodOptional; -}, z.core.$strip>; -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration client information - */ -export declare const OAuthClientInformationSchema: z.ZodObject<{ - client_id: z.ZodString; - client_secret: z.ZodOptional; - client_id_issued_at: z.ZodOptional; - client_secret_expires_at: z.ZodOptional; -}, z.core.$strip>; -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) - */ -export declare const OAuthClientInformationFullSchema: z.ZodObject<{ - redirect_uris: z.ZodArray; - token_endpoint_auth_method: z.ZodOptional; - grant_types: z.ZodOptional>; - response_types: z.ZodOptional>; - client_name: z.ZodOptional; - client_uri: z.ZodOptional; - logo_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; - scope: z.ZodOptional; - contacts: z.ZodOptional>; - tos_uri: z.ZodUnion<[z.ZodOptional, z.ZodPipe, z.ZodTransform>]>; - policy_uri: z.ZodOptional; - jwks_uri: z.ZodOptional; - jwks: z.ZodOptional; - software_id: z.ZodOptional; - software_version: z.ZodOptional; - software_statement: z.ZodOptional; - client_id: z.ZodString; - client_secret: z.ZodOptional; - client_id_issued_at: z.ZodOptional; - client_secret_expires_at: z.ZodOptional; -}, z.core.$strip>; -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration error response - */ -export declare const OAuthClientRegistrationErrorSchema: z.ZodObject<{ - error: z.ZodString; - error_description: z.ZodOptional; -}, z.core.$strip>; -/** - * RFC 7009 OAuth 2.0 Token Revocation request - */ -export declare const OAuthTokenRevocationRequestSchema: z.ZodObject<{ - token: z.ZodString; - token_type_hint: z.ZodOptional; -}, z.core.$strip>; -export type OAuthMetadata = z.infer; -export type OpenIdProviderMetadata = z.infer; -export type OpenIdProviderDiscoveryMetadata = z.infer; -export type OAuthTokens = z.infer; -export type OAuthErrorResponse = z.infer; -export type OAuthClientMetadata = z.infer; -export type OAuthClientInformation = z.infer; -export type OAuthClientInformationFull = z.infer; -export type OAuthClientInformationMixed = OAuthClientInformation | OAuthClientInformationFull; -export type OAuthClientRegistrationError = z.infer; -export type OAuthTokenRevocationRequest = z.infer; -export type OAuthProtectedResourceMetadata = z.infer; -export type AuthorizationServerMetadata = OAuthMetadata | OpenIdProviderDiscoveryMetadata; -//# sourceMappingURL=auth.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/auth.d.ts.map b/dist/esm/shared/auth.d.ts.map deleted file mode 100644 index 031a88fb92..0000000000 --- a/dist/esm/shared/auth.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../../src/shared/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B;;GAEG;AACH,eAAO,MAAM,aAAa,UAmBrB,CAAC;AAEN;;GAEG;AACH,eAAO,MAAM,oCAAoC;;;;;;;;;;;;;;;iBAe/C,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;iBAoB9B,CAAC;AAEH;;;GAGG;AACH,eAAO,MAAM,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAqCvC,CAAC;AAEH;;;;GAIG;AACH,eAAO,MAAM,qCAAqC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAKhD,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,iBAAiB;;;;;;;iBASlB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kC,CAAC,CAAC;AAC9F,MAAM,MAAM,2BAA2B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,iCAAiC,CAAC,CAAC;AAC5F,MAAM,MAAM,8BAA8B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oCAAoC,CAAC,CAAC;AAGlG,MAAM,MAAM,2BAA2B,GAAG,aAAa,GAAG,+BAA+B,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/auth.js b/dist/esm/shared/auth.js deleted file mode 100644 index 1d54e5855c..0000000000 --- a/dist/esm/shared/auth.js +++ /dev/null @@ -1,198 +0,0 @@ -import * as z from 'zod/v4'; -/** - * Reusable URL validation that disallows javascript: scheme - */ -export const SafeUrlSchema = z - .url() - .superRefine((val, ctx) => { - if (!URL.canParse(val)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'URL must be parseable', - fatal: true - }); - return z.NEVER; - } -}) - .refine(url => { - const u = new URL(url); - return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:'; -}, { message: 'URL cannot use javascript:, data:, or vbscript: scheme' }); -/** - * RFC 9728 OAuth Protected Resource Metadata - */ -export const OAuthProtectedResourceMetadataSchema = z.looseObject({ - resource: z.string().url(), - authorization_servers: z.array(SafeUrlSchema).optional(), - jwks_uri: z.string().url().optional(), - scopes_supported: z.array(z.string()).optional(), - bearer_methods_supported: z.array(z.string()).optional(), - resource_signing_alg_values_supported: z.array(z.string()).optional(), - resource_name: z.string().optional(), - resource_documentation: z.string().optional(), - resource_policy_uri: z.string().url().optional(), - resource_tos_uri: z.string().url().optional(), - tls_client_certificate_bound_access_tokens: z.boolean().optional(), - authorization_details_types_supported: z.array(z.string()).optional(), - dpop_signing_alg_values_supported: z.array(z.string()).optional(), - dpop_bound_access_tokens_required: z.boolean().optional() -}); -/** - * RFC 8414 OAuth 2.0 Authorization Server Metadata - */ -export const OAuthMetadataSchema = z.looseObject({ - issuer: z.string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: z.array(z.string()).optional(), - response_types_supported: z.array(z.string()), - response_modes_supported: z.array(z.string()).optional(), - grant_types_supported: z.array(z.string()).optional(), - token_endpoint_auth_methods_supported: z.array(z.string()).optional(), - token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - service_documentation: SafeUrlSchema.optional(), - revocation_endpoint: SafeUrlSchema.optional(), - revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(), - revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - introspection_endpoint: z.string().optional(), - introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(), - introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - code_challenge_methods_supported: z.array(z.string()).optional(), - client_id_metadata_document_supported: z.boolean().optional() -}); -/** - * OpenID Connect Discovery 1.0 Provider Metadata - * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata - */ -export const OpenIdProviderMetadataSchema = z.looseObject({ - issuer: z.string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - userinfo_endpoint: SafeUrlSchema.optional(), - jwks_uri: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: z.array(z.string()).optional(), - response_types_supported: z.array(z.string()), - response_modes_supported: z.array(z.string()).optional(), - grant_types_supported: z.array(z.string()).optional(), - acr_values_supported: z.array(z.string()).optional(), - subject_types_supported: z.array(z.string()), - id_token_signing_alg_values_supported: z.array(z.string()), - id_token_encryption_alg_values_supported: z.array(z.string()).optional(), - id_token_encryption_enc_values_supported: z.array(z.string()).optional(), - userinfo_signing_alg_values_supported: z.array(z.string()).optional(), - userinfo_encryption_alg_values_supported: z.array(z.string()).optional(), - userinfo_encryption_enc_values_supported: z.array(z.string()).optional(), - request_object_signing_alg_values_supported: z.array(z.string()).optional(), - request_object_encryption_alg_values_supported: z.array(z.string()).optional(), - request_object_encryption_enc_values_supported: z.array(z.string()).optional(), - token_endpoint_auth_methods_supported: z.array(z.string()).optional(), - token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - display_values_supported: z.array(z.string()).optional(), - claim_types_supported: z.array(z.string()).optional(), - claims_supported: z.array(z.string()).optional(), - service_documentation: z.string().optional(), - claims_locales_supported: z.array(z.string()).optional(), - ui_locales_supported: z.array(z.string()).optional(), - claims_parameter_supported: z.boolean().optional(), - request_parameter_supported: z.boolean().optional(), - request_uri_parameter_supported: z.boolean().optional(), - require_request_uri_registration: z.boolean().optional(), - op_policy_uri: SafeUrlSchema.optional(), - op_tos_uri: SafeUrlSchema.optional(), - client_id_metadata_document_supported: z.boolean().optional() -}); -/** - * OpenID Connect Discovery metadata that may include OAuth 2.0 fields - * This schema represents the real-world scenario where OIDC providers - * return a mix of OpenID Connect and OAuth 2.0 metadata fields - */ -export const OpenIdProviderDiscoveryMetadataSchema = z.object({ - ...OpenIdProviderMetadataSchema.shape, - ...OAuthMetadataSchema.pick({ - code_challenge_methods_supported: true - }).shape -}); -/** - * OAuth 2.1 token response - */ -export const OAuthTokensSchema = z - .object({ - access_token: z.string(), - id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect - token_type: z.string(), - expires_in: z.number().optional(), - scope: z.string().optional(), - refresh_token: z.string().optional() -}) - .strip(); -/** - * OAuth 2.1 error response - */ -export const OAuthErrorResponseSchema = z.object({ - error: z.string(), - error_description: z.string().optional(), - error_uri: z.string().optional() -}); -/** - * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri - */ -export const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined)); -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata - */ -export const OAuthClientMetadataSchema = z - .object({ - redirect_uris: z.array(SafeUrlSchema), - token_endpoint_auth_method: z.string().optional(), - grant_types: z.array(z.string()).optional(), - response_types: z.array(z.string()).optional(), - client_name: z.string().optional(), - client_uri: SafeUrlSchema.optional(), - logo_uri: OptionalSafeUrlSchema, - scope: z.string().optional(), - contacts: z.array(z.string()).optional(), - tos_uri: OptionalSafeUrlSchema, - policy_uri: z.string().optional(), - jwks_uri: SafeUrlSchema.optional(), - jwks: z.any().optional(), - software_id: z.string().optional(), - software_version: z.string().optional(), - software_statement: z.string().optional() -}) - .strip(); -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration client information - */ -export const OAuthClientInformationSchema = z - .object({ - client_id: z.string(), - client_secret: z.string().optional(), - client_id_issued_at: z.number().optional(), - client_secret_expires_at: z.number().optional() -}) - .strip(); -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) - */ -export const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration error response - */ -export const OAuthClientRegistrationErrorSchema = z - .object({ - error: z.string(), - error_description: z.string().optional() -}) - .strip(); -/** - * RFC 7009 OAuth 2.0 Token Revocation request - */ -export const OAuthTokenRevocationRequestSchema = z - .object({ - token: z.string(), - token_type_hint: z.string().optional() -}) - .strip(); -//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/dist/esm/shared/auth.js.map b/dist/esm/shared/auth.js.map deleted file mode 100644 index ee296c28b9..0000000000 --- a/dist/esm/shared/auth.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/shared/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAE5B;;GAEG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,CAAC;KACzB,GAAG,EAAE;KACL,WAAW,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;IACtB,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACrB,GAAG,CAAC,QAAQ,CAAC;YACT,IAAI,EAAE,CAAC,CAAC,YAAY,CAAC,MAAM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AE,CAAC,CAAC,MAAM,EAAE;IACjB,iBAAiB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CAC3C,CAAC;KACD,KAAK,EAAE,CAAC;AAEb;;GAEG;AACH,MAAM,CAAC,MAAM,iCAAiC,GAAG,CAAC;KAC7C,MAAM,CAAC;IACJ,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE;IACjB,eAAe,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;CACzC,CAAC;KACD,KAAK,EAAE,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/metadataUtils.d.ts b/dist/esm/shared/metadataUtils.d.ts deleted file mode 100644 index c0e738bab0..0000000000 --- a/dist/esm/shared/metadataUtils.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { BaseMetadata } from '../types.js'; -/** - * Utilities for working with BaseMetadata objects. - */ -/** - * Gets the display name for an object with BaseMetadata. - * For tools, the precedence is: title → annotations.title → name - * For other objects: title → name - * This implements the spec requirement: "if no title is provided, name should be used for display purposes" - */ -export declare function getDisplayName(metadata: BaseMetadata & { - annotations?: { - title?: string; - }; -}): string; -//# sourceMappingURL=metadataUtils.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/metadataUtils.d.ts.map b/dist/esm/shared/metadataUtils.d.ts.map deleted file mode 100644 index 596805eb34..0000000000 --- a/dist/esm/shared/metadataUtils.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"metadataUtils.d.ts","sourceRoot":"","sources":["../../../src/shared/metadataUtils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAE3C;;GAEG;AAEH;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,YAAY,GAAG;IAAE,WAAW,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,GAAG,MAAM,CAapG"} \ No newline at end of file diff --git a/dist/esm/shared/metadataUtils.js b/dist/esm/shared/metadataUtils.js deleted file mode 100644 index 61b37d9d8f..0000000000 --- a/dist/esm/shared/metadataUtils.js +++ /dev/null @@ -1,23 +0,0 @@ -/** - * Utilities for working with BaseMetadata objects. - */ -/** - * Gets the display name for an object with BaseMetadata. - * For tools, the precedence is: title → annotations.title → name - * For other objects: title → name - * This implements the spec requirement: "if no title is provided, name should be used for display purposes" - */ -export function getDisplayName(metadata) { - var _a; - // First check for title (not undefined and not empty string) - if (metadata.title !== undefined && metadata.title !== '') { - return metadata.title; - } - // Then check for annotations.title (only present in Tool objects) - if ((_a = metadata.annotations) === null || _a === void 0 ? void 0 : _a.title) { - return metadata.annotations.title; - } - // Finally fall back to name - return metadata.name; -} -//# sourceMappingURL=metadataUtils.js.map \ No newline at end of file diff --git a/dist/esm/shared/metadataUtils.js.map b/dist/esm/shared/metadataUtils.js.map deleted file mode 100644 index a206833d99..0000000000 --- a/dist/esm/shared/metadataUtils.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"metadataUtils.js","sourceRoot":"","sources":["../../../src/shared/metadataUtils.ts"],"names":[],"mappings":"AAEA;;GAEG;AAEH;;;;;GAKG;AACH,MAAM,UAAU,cAAc,CAAC,QAA6D;;IACxF,6DAA6D;IAC7D,IAAI,QAAQ,CAAC,KAAK,KAAK,SAAS,IAAI,QAAQ,CAAC,KAAK,KAAK,EAAE,EAAE,CAAC;QACxD,OAAO,QAAQ,CAAC,KAAK,CAAC;IAC1B,CAAC;IAED,kEAAkE;IAClE,IAAI,MAAA,QAAQ,CAAC,WAAW,0CAAE,KAAK,EAAE,CAAC;QAC9B,OAAO,QAAQ,CAAC,WAAW,CAAC,KAAK,CAAC;IACtC,CAAC;IAED,4BAA4B;IAC5B,OAAO,QAAQ,CAAC,IAAI,CAAC;AACzB,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/protocol.d.ts b/dist/esm/shared/protocol.d.ts deleted file mode 100644 index fb23686184..0000000000 --- a/dist/esm/shared/protocol.d.ts +++ /dev/null @@ -1,226 +0,0 @@ -import { AnySchema, AnyObjectSchema, SchemaOutput } from '../server/zod-compat.js'; -import { ClientCapabilities, JSONRPCRequest, Notification, Progress, Request, RequestId, Result, ServerCapabilities, RequestMeta, RequestInfo } from '../types.js'; -import { Transport, TransportSendOptions } from './transport.js'; -import { AuthInfo } from '../server/auth/types.js'; -/** - * Callback for progress notifications. - */ -export type ProgressCallback = (progress: Progress) => void; -/** - * Additional initialization options. - */ -export type ProtocolOptions = { - /** - * Whether to restrict emitted requests to only those that the remote side has indicated that they can handle, through their advertised capabilities. - * - * Note that this DOES NOT affect checking of _local_ side capabilities, as it is considered a logic error to mis-specify those. - * - * Currently this defaults to false, for backwards compatibility with SDK versions that did not advertise capabilities correctly. In future, this will default to true. - */ - enforceStrictCapabilities?: boolean; - /** - * An array of notification method names that should be automatically debounced. - * Any notifications with a method in this list will be coalesced if they - * occur in the same tick of the event loop. - * e.g., ['notifications/tools/list_changed'] - */ - debouncedNotificationMethods?: string[]; -}; -/** - * The default request timeout, in miliseconds. - */ -export declare const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; -/** - * Options that can be given per request. - */ -export type RequestOptions = { - /** - * If set, requests progress notifications from the remote end (if supported). When progress notifications are received, this callback will be invoked. - */ - onprogress?: ProgressCallback; - /** - * Can be used to cancel an in-flight request. This will cause an AbortError to be raised from request(). - */ - signal?: AbortSignal; - /** - * A timeout (in milliseconds) for this request. If exceeded, an McpError with code `RequestTimeout` will be raised from request(). - * - * If not specified, `DEFAULT_REQUEST_TIMEOUT_MSEC` will be used as the timeout. - */ - timeout?: number; - /** - * If true, receiving a progress notification will reset the request timeout. - * This is useful for long-running operations that send periodic progress updates. - * Default: false - */ - resetTimeoutOnProgress?: boolean; - /** - * Maximum total time (in milliseconds) to wait for a response. - * If exceeded, an McpError with code `RequestTimeout` will be raised, regardless of progress notifications. - * If not specified, there is no maximum total timeout. - */ - maxTotalTimeout?: number; -} & TransportSendOptions; -/** - * Options that can be given per notification. - */ -export type NotificationOptions = { - /** - * May be used to indicate to the transport which incoming request to associate this outgoing notification with. - */ - relatedRequestId?: RequestId; -}; -/** - * Extra data given to request handlers. - */ -export type RequestHandlerExtra = { - /** - * An abort signal used to communicate if the request was cancelled from the sender's side. - */ - signal: AbortSignal; - /** - * Information about a validated access token, provided to request handlers. - */ - authInfo?: AuthInfo; - /** - * The session ID from the transport, if available. - */ - sessionId?: string; - /** - * Metadata from the original request. - */ - _meta?: RequestMeta; - /** - * The JSON-RPC ID of the request being handled. - * This can be useful for tracking or logging purposes. - */ - requestId: RequestId; - /** - * The original HTTP request. - */ - requestInfo?: RequestInfo; - /** - * Sends a notification that relates to the current request being handled. - * - * This is used by certain transports to correctly associate related messages. - */ - sendNotification: (notification: SendNotificationT) => Promise; - /** - * Sends a request that relates to the current request being handled. - * - * This is used by certain transports to correctly associate related messages. - */ - sendRequest: (request: SendRequestT, resultSchema: U, options?: RequestOptions) => Promise>; -}; -/** - * Implements MCP protocol framing on top of a pluggable transport, including - * features like request/response linking, notifications, and progress. - */ -export declare abstract class Protocol { - private _options?; - private _transport?; - private _requestMessageId; - private _requestHandlers; - private _requestHandlerAbortControllers; - private _notificationHandlers; - private _responseHandlers; - private _progressHandlers; - private _timeoutInfo; - private _pendingDebouncedNotifications; - /** - * Callback for when the connection is closed for any reason. - * - * This is invoked when close() is called as well. - */ - onclose?: () => void; - /** - * Callback for when an error occurs. - * - * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. - */ - onerror?: (error: Error) => void; - /** - * A handler to invoke for any request types that do not have their own handler installed. - */ - fallbackRequestHandler?: (request: JSONRPCRequest, extra: RequestHandlerExtra) => Promise; - /** - * A handler to invoke for any notification types that do not have their own handler installed. - */ - fallbackNotificationHandler?: (notification: Notification) => Promise; - constructor(_options?: ProtocolOptions | undefined); - private _setupTimeout; - private _resetTimeout; - private _cleanupTimeout; - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. - */ - connect(transport: Transport): Promise; - private _onclose; - private _onerror; - private _onnotification; - private _onrequest; - private _onprogress; - private _onresponse; - get transport(): Transport | undefined; - /** - * Closes the connection. - */ - close(): Promise; - /** - * A method to check if a capability is supported by the remote side, for the given method to be called. - * - * This should be implemented by subclasses. - */ - protected abstract assertCapabilityForMethod(method: SendRequestT['method']): void; - /** - * A method to check if a notification is supported by the local side, for the given method to be sent. - * - * This should be implemented by subclasses. - */ - protected abstract assertNotificationCapability(method: SendNotificationT['method']): void; - /** - * A method to check if a request handler is supported by the local side, for the given method to be handled. - * - * This should be implemented by subclasses. - */ - protected abstract assertRequestHandlerCapability(method: string): void; - /** - * Sends a request and wait for a response. - * - * Do not use this method to emit notifications! Use notification() instead. - */ - request(request: SendRequestT, resultSchema: T, options?: RequestOptions): Promise>; - /** - * Emits a notification, which is a one-way message that does not expect a response. - */ - notification(notification: SendNotificationT, options?: NotificationOptions): Promise; - /** - * Registers a handler to invoke when this protocol object receives a request with the given method. - * - * Note that this will replace any previous request handler for the same method. - */ - setRequestHandler(requestSchema: T, handler: (request: SchemaOutput, extra: RequestHandlerExtra) => SendResultT | Promise): void; - /** - * Removes the request handler for the given method. - */ - removeRequestHandler(method: string): void; - /** - * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. - */ - assertCanSetRequestHandler(method: string): void; - /** - * Registers a handler to invoke when this protocol object receives a notification with the given method. - * - * Note that this will replace any previous notification handler for the same method. - */ - setNotificationHandler(notificationSchema: T, handler: (notification: SchemaOutput) => void | Promise): void; - /** - * Removes the notification handler for the given method. - */ - removeNotificationHandler(method: string): void; -} -export declare function mergeCapabilities(base: ServerCapabilities, additional: Partial): ServerCapabilities; -export declare function mergeCapabilities(base: ClientCapabilities, additional: Partial): ClientCapabilities; -//# sourceMappingURL=protocol.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/protocol.d.ts.map b/dist/esm/shared/protocol.d.ts.map deleted file mode 100644 index 4aa2bd57cb..0000000000 --- a/dist/esm/shared/protocol.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../../../src/shared/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,YAAY,EAAa,MAAM,yBAAyB,CAAC;AAC9F,OAAO,EAEH,kBAAkB,EAQlB,cAAc,EAGd,YAAY,EAEZ,QAAQ,EAGR,OAAO,EACP,SAAS,EACT,MAAM,EACN,kBAAkB,EAClB,WAAW,EAEX,WAAW,EACd,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAE,MAAM,yBAAyB,CAAC;AAGnD;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG,CAAC,QAAQ,EAAE,QAAQ,KAAK,IAAI,CAAC;AAE5D;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG;IAC1B;;;;;;OAMG;IACH,yBAAyB,CAAC,EAAE,OAAO,CAAC;IACpC;;;;;OAKG;IACH,4BAA4B,CAAC,EAAE,MAAM,EAAE,CAAC;CAC3C,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,4BAA4B,QAAQ,CAAC;AAElD;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG;IACzB;;OAEG;IACH,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAE9B;;OAEG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;IAErB;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IAEjB;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,OAAO,CAAC;IAEjC;;;;OAIG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;CAC5B,GAAG,oBAAoB,CAAC;AAEzB;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG;IAC9B;;OAEG;IACH,gBAAgB,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AAG,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC;IA6FxH;;OAEG;IACG,YAAY,CAAC,YAAY,EAAE,iBAAiB,EAAE,OAAO,CAAC,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC;IAqDjG;;;;OAIG;IACH,iBAAiB,CAAC,CAAC,SAAS,eAAe,EACvC,aAAa,EAAE,CAAC,EAChB,OAAO,EAAE,CACL,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,EACxB,KAAK,EAAE,mBAAmB,CAAC,YAAY,EAAE,iBAAiB,CAAC,KAC1D,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,GACxC,IAAI;IAUP;;OAEG;IACH,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAI1C;;OAEG;IACH,0BAA0B,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAMhD;;;;OAIG;IACH,sBAAsB,CAAC,CAAC,SAAS,eAAe,EAC5C,kBAAkB,EAAE,CAAC,EACrB,OAAO,EAAE,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC,CAAC,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GACjE,IAAI;IAQP;;OAEG;IACH,yBAAyB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;CAGlD;AAMD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,kBAAkB,CAAC;AACzH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,kBAAkB,EAAE,UAAU,EAAE,OAAO,CAAC,kBAAkB,CAAC,GAAG,kBAAkB,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/protocol.js b/dist/esm/shared/protocol.js deleted file mode 100644 index 504119c82c..0000000000 --- a/dist/esm/shared/protocol.js +++ /dev/null @@ -1,437 +0,0 @@ -import { safeParse } from '../server/zod-compat.js'; -import { CancelledNotificationSchema, ErrorCode, isJSONRPCError, isJSONRPCRequest, isJSONRPCResponse, isJSONRPCNotification, McpError, PingRequestSchema, ProgressNotificationSchema } from '../types.js'; -import { getMethodLiteral, parseWithCompat } from '../server/zod-json-schema-compat.js'; -/** - * The default request timeout, in miliseconds. - */ -export const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; -/** - * Implements MCP protocol framing on top of a pluggable transport, including - * features like request/response linking, notifications, and progress. - */ -export class Protocol { - constructor(_options) { - this._options = _options; - this._requestMessageId = 0; - this._requestHandlers = new Map(); - this._requestHandlerAbortControllers = new Map(); - this._notificationHandlers = new Map(); - this._responseHandlers = new Map(); - this._progressHandlers = new Map(); - this._timeoutInfo = new Map(); - this._pendingDebouncedNotifications = new Set(); - this.setNotificationHandler(CancelledNotificationSchema, notification => { - const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); - controller === null || controller === void 0 ? void 0 : controller.abort(notification.params.reason); - }); - this.setNotificationHandler(ProgressNotificationSchema, notification => { - this._onprogress(notification); - }); - this.setRequestHandler(PingRequestSchema, - // Automatic pong by default. - _request => ({})); - } - _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { - this._timeoutInfo.set(messageId, { - timeoutId: setTimeout(onTimeout, timeout), - startTime: Date.now(), - timeout, - maxTotalTimeout, - resetTimeoutOnProgress, - onTimeout - }); - } - _resetTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (!info) - return false; - const totalElapsed = Date.now() - info.startTime; - if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { - this._timeoutInfo.delete(messageId); - throw McpError.fromError(ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', { - maxTotalTimeout: info.maxTotalTimeout, - totalElapsed - }); - } - clearTimeout(info.timeoutId); - info.timeoutId = setTimeout(info.onTimeout, info.timeout); - return true; - } - _cleanupTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (info) { - clearTimeout(info.timeoutId); - this._timeoutInfo.delete(messageId); - } - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. - */ - async connect(transport) { - var _a, _b, _c; - this._transport = transport; - const _onclose = (_a = this.transport) === null || _a === void 0 ? void 0 : _a.onclose; - this._transport.onclose = () => { - _onclose === null || _onclose === void 0 ? void 0 : _onclose(); - this._onclose(); - }; - const _onerror = (_b = this.transport) === null || _b === void 0 ? void 0 : _b.onerror; - this._transport.onerror = (error) => { - _onerror === null || _onerror === void 0 ? void 0 : _onerror(error); - this._onerror(error); - }; - const _onmessage = (_c = this._transport) === null || _c === void 0 ? void 0 : _c.onmessage; - this._transport.onmessage = (message, extra) => { - _onmessage === null || _onmessage === void 0 ? void 0 : _onmessage(message, extra); - if (isJSONRPCResponse(message) || isJSONRPCError(message)) { - this._onresponse(message); - } - else if (isJSONRPCRequest(message)) { - this._onrequest(message, extra); - } - else if (isJSONRPCNotification(message)) { - this._onnotification(message); - } - else { - this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); - } - }; - await this._transport.start(); - } - _onclose() { - var _a; - const responseHandlers = this._responseHandlers; - this._responseHandlers = new Map(); - this._progressHandlers.clear(); - this._pendingDebouncedNotifications.clear(); - this._transport = undefined; - (_a = this.onclose) === null || _a === void 0 ? void 0 : _a.call(this); - const error = McpError.fromError(ErrorCode.ConnectionClosed, 'Connection closed'); - for (const handler of responseHandlers.values()) { - handler(error); - } - } - _onerror(error) { - var _a; - (_a = this.onerror) === null || _a === void 0 ? void 0 : _a.call(this, error); - } - _onnotification(notification) { - var _a; - const handler = (_a = this._notificationHandlers.get(notification.method)) !== null && _a !== void 0 ? _a : this.fallbackNotificationHandler; - // Ignore notifications not being subscribed to. - if (handler === undefined) { - return; - } - // Starting with Promise.resolve() puts any synchronous errors into the monad as well. - Promise.resolve() - .then(() => handler(notification)) - .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`))); - } - _onrequest(request, extra) { - var _a, _b; - const handler = (_a = this._requestHandlers.get(request.method)) !== null && _a !== void 0 ? _a : this.fallbackRequestHandler; - // Capture the current transport at request time to ensure responses go to the correct client - const capturedTransport = this._transport; - if (handler === undefined) { - capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({ - jsonrpc: '2.0', - id: request.id, - error: { - code: ErrorCode.MethodNotFound, - message: 'Method not found' - } - }).catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`))); - return; - } - const abortController = new AbortController(); - this._requestHandlerAbortControllers.set(request.id, abortController); - const fullExtra = { - signal: abortController.signal, - sessionId: capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId, - _meta: (_b = request.params) === null || _b === void 0 ? void 0 : _b._meta, - sendNotification: notification => this.notification(notification, { relatedRequestId: request.id }), - sendRequest: (r, resultSchema, options) => this.request(r, resultSchema, { ...options, relatedRequestId: request.id }), - authInfo: extra === null || extra === void 0 ? void 0 : extra.authInfo, - requestId: request.id, - requestInfo: extra === null || extra === void 0 ? void 0 : extra.requestInfo - }; - // Starting with Promise.resolve() puts any synchronous errors into the monad as well. - Promise.resolve() - .then(() => handler(request, fullExtra)) - .then(result => { - if (abortController.signal.aborted) { - return; - } - return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({ - result, - jsonrpc: '2.0', - id: request.id - }); - }, error => { - var _a; - if (abortController.signal.aborted) { - return; - } - return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({ - jsonrpc: '2.0', - id: request.id, - error: { - code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode.InternalError, - message: (_a = error.message) !== null && _a !== void 0 ? _a : 'Internal error', - ...(error['data'] !== undefined && { data: error['data'] }) - } - }); - }) - .catch(error => this._onerror(new Error(`Failed to send response: ${error}`))) - .finally(() => { - this._requestHandlerAbortControllers.delete(request.id); - }); - } - _onprogress(notification) { - const { progressToken, ...params } = notification.params; - const messageId = Number(progressToken); - const handler = this._progressHandlers.get(messageId); - if (!handler) { - this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); - return; - } - const responseHandler = this._responseHandlers.get(messageId); - const timeoutInfo = this._timeoutInfo.get(messageId); - if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { - try { - this._resetTimeout(messageId); - } - catch (error) { - responseHandler(error); - return; - } - } - handler(params); - } - _onresponse(response) { - const messageId = Number(response.id); - const handler = this._responseHandlers.get(messageId); - if (handler === undefined) { - this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); - return; - } - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - if (isJSONRPCResponse(response)) { - handler(response); - } - else { - const error = McpError.fromError(response.error.code, response.error.message, response.error.data); - handler(error); - } - } - get transport() { - return this._transport; - } - /** - * Closes the connection. - */ - async close() { - var _a; - await ((_a = this._transport) === null || _a === void 0 ? void 0 : _a.close()); - } - /** - * Sends a request and wait for a response. - * - * Do not use this method to emit notifications! Use notification() instead. - */ - request(request, resultSchema, options) { - const { relatedRequestId, resumptionToken, onresumptiontoken } = options !== null && options !== void 0 ? options : {}; - return new Promise((resolve, reject) => { - var _a, _b, _c, _d, _e, _f; - if (!this._transport) { - reject(new Error('Not connected')); - return; - } - if (((_a = this._options) === null || _a === void 0 ? void 0 : _a.enforceStrictCapabilities) === true) { - this.assertCapabilityForMethod(request.method); - } - (_b = options === null || options === void 0 ? void 0 : options.signal) === null || _b === void 0 ? void 0 : _b.throwIfAborted(); - const messageId = this._requestMessageId++; - const jsonrpcRequest = { - ...request, - jsonrpc: '2.0', - id: messageId - }; - if (options === null || options === void 0 ? void 0 : options.onprogress) { - this._progressHandlers.set(messageId, options.onprogress); - jsonrpcRequest.params = { - ...request.params, - _meta: { - ...(((_c = request.params) === null || _c === void 0 ? void 0 : _c._meta) || {}), - progressToken: messageId - } - }; - } - const cancel = (reason) => { - var _a; - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - (_a = this._transport) === null || _a === void 0 ? void 0 : _a.send({ - jsonrpc: '2.0', - method: 'notifications/cancelled', - params: { - requestId: messageId, - reason: String(reason) - } - }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`))); - reject(reason); - }; - this._responseHandlers.set(messageId, response => { - var _a; - if ((_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.aborted) { - return; - } - if (response instanceof Error) { - return reject(response); - } - try { - const parseResult = safeParse(resultSchema, response.result); - if (!parseResult.success) { - // Type guard: if success is false, error is guaranteed to exist - reject(parseResult.error); - } - else { - resolve(parseResult.data); - } - } - catch (error) { - reject(error); - } - }); - (_d = options === null || options === void 0 ? void 0 : options.signal) === null || _d === void 0 ? void 0 : _d.addEventListener('abort', () => { - var _a; - cancel((_a = options === null || options === void 0 ? void 0 : options.signal) === null || _a === void 0 ? void 0 : _a.reason); - }); - const timeout = (_e = options === null || options === void 0 ? void 0 : options.timeout) !== null && _e !== void 0 ? _e : DEFAULT_REQUEST_TIMEOUT_MSEC; - const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, 'Request timed out', { timeout })); - this._setupTimeout(messageId, timeout, options === null || options === void 0 ? void 0 : options.maxTotalTimeout, timeoutHandler, (_f = options === null || options === void 0 ? void 0 : options.resetTimeoutOnProgress) !== null && _f !== void 0 ? _f : false); - this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => { - this._cleanupTimeout(messageId); - reject(error); - }); - }); - } - /** - * Emits a notification, which is a one-way message that does not expect a response. - */ - async notification(notification, options) { - var _a, _b; - if (!this._transport) { - throw new Error('Not connected'); - } - this.assertNotificationCapability(notification.method); - const debouncedMethods = (_b = (_a = this._options) === null || _a === void 0 ? void 0 : _a.debouncedNotificationMethods) !== null && _b !== void 0 ? _b : []; - // A notification can only be debounced if it's in the list AND it's "simple" - // (i.e., has no parameters and no related request ID that could be lost). - const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !(options === null || options === void 0 ? void 0 : options.relatedRequestId); - if (canDebounce) { - // If a notification of this type is already scheduled, do nothing. - if (this._pendingDebouncedNotifications.has(notification.method)) { - return; - } - // Mark this notification type as pending. - this._pendingDebouncedNotifications.add(notification.method); - // Schedule the actual send to happen in the next microtask. - // This allows all synchronous calls in the current event loop tick to be coalesced. - Promise.resolve().then(() => { - var _a; - // Un-mark the notification so the next one can be scheduled. - this._pendingDebouncedNotifications.delete(notification.method); - // SAFETY CHECK: If the connection was closed while this was pending, abort. - if (!this._transport) { - return; - } - const jsonrpcNotification = { - ...notification, - jsonrpc: '2.0' - }; - // Send the notification, but don't await it here to avoid blocking. - // Handle potential errors with a .catch(). - (_a = this._transport) === null || _a === void 0 ? void 0 : _a.send(jsonrpcNotification, options).catch(error => this._onerror(error)); - }); - // Return immediately. - return; - } - const jsonrpcNotification = { - ...notification, - jsonrpc: '2.0' - }; - await this._transport.send(jsonrpcNotification, options); - } - /** - * Registers a handler to invoke when this protocol object receives a request with the given method. - * - * Note that this will replace any previous request handler for the same method. - */ - setRequestHandler(requestSchema, handler) { - const method = getMethodLiteral(requestSchema); - this.assertRequestHandlerCapability(method); - this._requestHandlers.set(method, (request, extra) => { - const parsed = parseWithCompat(requestSchema, request); - return Promise.resolve(handler(parsed, extra)); - }); - } - /** - * Removes the request handler for the given method. - */ - removeRequestHandler(method) { - this._requestHandlers.delete(method); - } - /** - * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. - */ - assertCanSetRequestHandler(method) { - if (this._requestHandlers.has(method)) { - throw new Error(`A request handler for ${method} already exists, which would be overridden`); - } - } - /** - * Registers a handler to invoke when this protocol object receives a notification with the given method. - * - * Note that this will replace any previous notification handler for the same method. - */ - setNotificationHandler(notificationSchema, handler) { - const method = getMethodLiteral(notificationSchema); - this._notificationHandlers.set(method, notification => { - const parsed = parseWithCompat(notificationSchema, notification); - return Promise.resolve(handler(parsed)); - }); - } - /** - * Removes the notification handler for the given method. - */ - removeNotificationHandler(method) { - this._notificationHandlers.delete(method); - } -} -function isPlainObject(value) { - return value !== null && typeof value === 'object' && !Array.isArray(value); -} -export function mergeCapabilities(base, additional) { - const result = { ...base }; - for (const key in additional) { - const k = key; - const addValue = additional[k]; - if (addValue === undefined) - continue; - const baseValue = result[k]; - if (isPlainObject(baseValue) && isPlainObject(addValue)) { - result[k] = { ...baseValue, ...addValue }; - } - else { - result[k] = addValue; - } - } - return result; -} -//# sourceMappingURL=protocol.js.map \ No newline at end of file diff --git a/dist/esm/shared/protocol.js.map b/dist/esm/shared/protocol.js.map deleted file mode 100644 index 79583f349f..0000000000 --- a/dist/esm/shared/protocol.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../../src/shared/protocol.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4C,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAC9F,OAAO,EACH,2BAA2B,EAE3B,SAAS,EACT,cAAc,EACd,gBAAgB,EAChB,iBAAiB,EACjB,qBAAqB,EAKrB,QAAQ,EAER,iBAAiB,EAGjB,0BAA0B,EAQ7B,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAE,MAAM,qCAAqC,CAAC;AA4BxF;;GAEG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,KAAK,CAAC;AA8GlD;;;GAGG;AACH,MAAM,OAAgB,QAAQ;IAsC1B,YAAoB,QAA0B;QAA1B,aAAQ,GAAR,QAAQ,CAAkB;QApCtC,sBAAiB,GAAG,CAAC,CAAC;QACtB,qBAAgB,GAGpB,IAAI,GAAG,EAAE,CAAC;QACN,oCAA+B,GAAoC,IAAI,GAAG,EAAE,CAAC;QAC7E,0BAAqB,GAAsE,IAAI,GAAG,EAAE,CAAC;QACrG,sBAAiB,GAA6D,IAAI,GAAG,EAAE,CAAC;QACxF,sBAAiB,GAAkC,IAAI,GAAG,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I,aAAa,CAAC,SAAS,CAAC,IAAI,aAAa,CAAC,QAAQ,CAAC,EAAE,CAAC;YACtD,MAAM,CAAC,CAAC,CAAC,GAAG,EAAE,GAAI,SAAqC,EAAE,GAAI,QAAoC,EAAiB,CAAC;QACvH,CAAC;aAAM,CAAC;YACJ,MAAM,CAAC,CAAC,CAAC,GAAG,QAAuB,CAAC;QACxC,CAAC;IACL,CAAC;IACD,OAAO,MAAM,CAAC;AAClB,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/stdio.d.ts b/dist/esm/shared/stdio.d.ts deleted file mode 100644 index 0830a48bc7..0000000000 --- a/dist/esm/shared/stdio.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { JSONRPCMessage } from '../types.js'; -/** - * Buffers a continuous stdio stream into discrete JSON-RPC messages. - */ -export declare class ReadBuffer { - private _buffer?; - append(chunk: Buffer): void; - readMessage(): JSONRPCMessage | null; - clear(): void; -} -export declare function deserializeMessage(line: string): JSONRPCMessage; -export declare function serializeMessage(message: JSONRPCMessage): string; -//# sourceMappingURL=stdio.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/stdio.d.ts.map b/dist/esm/shared/stdio.d.ts.map deleted file mode 100644 index 8f97f2ab10..0000000000 --- a/dist/esm/shared/stdio.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"stdio.d.ts","sourceRoot":"","sources":["../../../src/shared/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAwB,MAAM,aAAa,CAAC;AAEnE;;GAEG;AACH,qBAAa,UAAU;IACnB,OAAO,CAAC,OAAO,CAAC,CAAS;IAEzB,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAI3B,WAAW,IAAI,cAAc,GAAG,IAAI;IAepC,KAAK,IAAI,IAAI;CAGhB;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,CAE/D;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,cAAc,GAAG,MAAM,CAEhE"} \ No newline at end of file diff --git a/dist/esm/shared/stdio.js b/dist/esm/shared/stdio.js deleted file mode 100644 index 30f299f5a7..0000000000 --- a/dist/esm/shared/stdio.js +++ /dev/null @@ -1,31 +0,0 @@ -import { JSONRPCMessageSchema } from '../types.js'; -/** - * Buffers a continuous stdio stream into discrete JSON-RPC messages. - */ -export class ReadBuffer { - append(chunk) { - this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; - } - readMessage() { - if (!this._buffer) { - return null; - } - const index = this._buffer.indexOf('\n'); - if (index === -1) { - return null; - } - const line = this._buffer.toString('utf8', 0, index).replace(/\r$/, ''); - this._buffer = this._buffer.subarray(index + 1); - return deserializeMessage(line); - } - clear() { - this._buffer = undefined; - } -} -export function deserializeMessage(line) { - return JSONRPCMessageSchema.parse(JSON.parse(line)); -} -export function serializeMessage(message) { - return JSON.stringify(message) + '\n'; -} -//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/dist/esm/shared/stdio.js.map b/dist/esm/shared/stdio.js.map deleted file mode 100644 index 19fdf08d83..0000000000 --- a/dist/esm/shared/stdio.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"stdio.js","sourceRoot":"","sources":["../../../src/shared/stdio.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnE;;GAEG;AACH,MAAM,OAAO,UAAU;IAGnB,MAAM,CAAC,KAAa;QAChB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC;IAC/E,CAAC;IAED,WAAW;QACP,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;YAChB,OAAO,IAAI,CAAC;QAChB,CAAC;QAED,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACzC,IAAI,KAAK,KAAK,CAAC,CAAC,EAAE,CAAC;YACf,OAAO,IAAI,CAAC;QAChB,CAAC;QAED,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QACxE,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC;QAChD,OAAO,kBAAkB,CAAC,IAAI,CAAC,CAAC;IACpC,CAAC;IAED,KAAK;QACD,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;IAC7B,CAAC;CACJ;AAED,MAAM,UAAU,kBAAkB,CAAC,IAAY;IAC3C,OAAO,oBAAoB,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;AACxD,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,OAAuB;IACpD,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;AAC1C,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/toolNameValidation.d.ts b/dist/esm/shared/toolNameValidation.d.ts deleted file mode 100644 index 3cf94bf78e..0000000000 --- a/dist/esm/shared/toolNameValidation.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Tool name validation utilities according to SEP: Specify Format for Tool Names - * - * Tool names SHOULD be between 1 and 128 characters in length (inclusive). - * Tool names are case-sensitive. - * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits - * (0-9), underscore (_), dash (-), and dot (.). - * Tool names SHOULD NOT contain spaces, commas, or other special characters. - */ -/** - * Validates a tool name according to the SEP specification - * @param name - The tool name to validate - * @returns An object containing validation result and any warnings - */ -export declare function validateToolName(name: string): { - isValid: boolean; - warnings: string[]; -}; -/** - * Issues warnings for non-conforming tool names - * @param name - The tool name that triggered the warnings - * @param warnings - Array of warning messages - */ -export declare function issueToolNameWarning(name: string, warnings: string[]): void; -/** - * Validates a tool name and issues warnings for non-conforming names - * @param name - The tool name to validate - * @returns true if the name is valid, false otherwise - */ -export declare function validateAndWarnToolName(name: string): boolean; -//# sourceMappingURL=toolNameValidation.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/toolNameValidation.d.ts.map b/dist/esm/shared/toolNameValidation.d.ts.map deleted file mode 100644 index d81f0156e6..0000000000 --- a/dist/esm/shared/toolNameValidation.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"toolNameValidation.d.ts","sourceRoot":"","sources":["../../../src/shared/toolNameValidation.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAOH;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG;IAC5C,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,EAAE,MAAM,EAAE,CAAC;CACtB,CA0DA;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,IAAI,CAY3E;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAO7D"} \ No newline at end of file diff --git a/dist/esm/shared/toolNameValidation.js b/dist/esm/shared/toolNameValidation.js deleted file mode 100644 index 34b6d19c56..0000000000 --- a/dist/esm/shared/toolNameValidation.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Tool name validation utilities according to SEP: Specify Format for Tool Names - * - * Tool names SHOULD be between 1 and 128 characters in length (inclusive). - * Tool names are case-sensitive. - * Allowed characters: uppercase and lowercase ASCII letters (A-Z, a-z), digits - * (0-9), underscore (_), dash (-), and dot (.). - * Tool names SHOULD NOT contain spaces, commas, or other special characters. - */ -/** - * Regular expression for valid tool names according to SEP-986 specification - */ -const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; -/** - * Validates a tool name according to the SEP specification - * @param name - The tool name to validate - * @returns An object containing validation result and any warnings - */ -export function validateToolName(name) { - const warnings = []; - // Check length - if (name.length === 0) { - return { - isValid: false, - warnings: ['Tool name cannot be empty'] - }; - } - if (name.length > 128) { - return { - isValid: false, - warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] - }; - } - // Check for specific problematic patterns (these are warnings, not validation failures) - if (name.includes(' ')) { - warnings.push('Tool name contains spaces, which may cause parsing issues'); - } - if (name.includes(',')) { - warnings.push('Tool name contains commas, which may cause parsing issues'); - } - // Check for potentially confusing patterns (leading/trailing dashes, dots, slashes) - if (name.startsWith('-') || name.endsWith('-')) { - warnings.push('Tool name starts or ends with a dash, which may cause parsing issues in some contexts'); - } - if (name.startsWith('.') || name.endsWith('.')) { - warnings.push('Tool name starts or ends with a dot, which may cause parsing issues in some contexts'); - } - // Check for invalid characters - if (!TOOL_NAME_REGEX.test(name)) { - const invalidChars = name - .split('') - .filter(char => !/[A-Za-z0-9._-]/.test(char)) - .filter((char, index, arr) => arr.indexOf(char) === index); // Remove duplicates - warnings.push(`Tool name contains invalid characters: ${invalidChars.map(c => `"${c}"`).join(', ')}`, 'Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)'); - return { - isValid: false, - warnings - }; - } - return { - isValid: true, - warnings - }; -} -/** - * Issues warnings for non-conforming tool names - * @param name - The tool name that triggered the warnings - * @param warnings - Array of warning messages - */ -export function issueToolNameWarning(name, warnings) { - if (warnings.length > 0) { - console.warn(`Tool name validation warning for "${name}":`); - for (const warning of warnings) { - console.warn(` - ${warning}`); - } - console.warn('Tool registration will proceed, but this may cause compatibility issues.'); - console.warn('Consider updating the tool name to conform to the MCP tool naming standard.'); - console.warn('See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.'); - } -} -/** - * Validates a tool name and issues warnings for non-conforming names - * @param name - The tool name to validate - * @returns true if the name is valid, false otherwise - */ -export function validateAndWarnToolName(name) { - const result = validateToolName(name); - // Always issue warnings for any validation issues (both invalid names and warnings) - issueToolNameWarning(name, result.warnings); - return result.isValid; -} -//# sourceMappingURL=toolNameValidation.js.map \ No newline at end of file diff --git a/dist/esm/shared/toolNameValidation.js.map b/dist/esm/shared/toolNameValidation.js.map deleted file mode 100644 index 9fdfcea843..0000000000 --- a/dist/esm/shared/toolNameValidation.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"toolNameValidation.js","sourceRoot":"","sources":["../../../src/shared/toolNameValidation.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;GAEG;AACH,MAAM,eAAe,GAAG,yBAAyB,CAAC;AAElD;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAAC,IAAY;IAIzC,MAAM,QAAQ,GAAa,EAAE,CAAC;IAE9B,eAAe;IACf,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACpB,OAAO;YACH,OAAO,EAAE,KAAK;YACd,QAAQ,EAAE,CAAC,2BAA2B,CAAC;SAC1C,CAAC;IACN,CAAC;IAED,IAAI,IAAI,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC;QACpB,OAAO;YACH,OAAO,EAAE,KAAK;YACd,QAAQ,EAAE,CAAC,gEAAgE,IAAI,CAAC,MAAM,GAAG,CAAC;SAC7F,CAAC;IACN,CAAC;IAED,wFAAwF;IACxF,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACrB,QAAQ,CAAC,IAAI,CAAC,2DAA2D,CAAC,CAAC;IAC/E,CAAC;IAED,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;QACrB,QAAQ,CAAC,IAAI,CAAC,2DAA2D,CAAC,CAAC;IAC/E,CAAC;IAED,oFAAoF;IACpF,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,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O,OAAO,EAAE,CAAC,CAAC;QACnC,CAAC;QACD,OAAO,CAAC,IAAI,CAAC,0EAA0E,CAAC,CAAC;QACzF,OAAO,CAAC,IAAI,CAAC,6EAA6E,CAAC,CAAC;QAC5F,OAAO,CAAC,IAAI,CACR,oIAAoI,CACvI,CAAC;IACN,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CAAC,IAAY;IAChD,MAAM,MAAM,GAAG,gBAAgB,CAAC,IAAI,CAAC,CAAC;IAEtC,oFAAoF;IACpF,oBAAoB,CAAC,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,CAAC;IAE5C,OAAO,MAAM,CAAC,OAAO,CAAC;AAC1B,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/transport.d.ts b/dist/esm/shared/transport.d.ts deleted file mode 100644 index 7fb5efab77..0000000000 --- a/dist/esm/shared/transport.d.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types.js'; -export type FetchLike = (url: string | URL, init?: RequestInit) => Promise; -/** - * Normalizes HeadersInit to a plain Record for manipulation. - * Handles Headers objects, arrays of tuples, and plain objects. - */ -export declare function normalizeHeaders(headers: HeadersInit | undefined): Record; -/** - * Creates a fetch function that includes base RequestInit options. - * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. - * - * @param baseFetch - The base fetch function to wrap (defaults to global fetch) - * @param baseInit - The base RequestInit to merge with each request - * @returns A wrapped fetch function that merges base options with call-specific options - */ -export declare function createFetchWithInit(baseFetch?: FetchLike, baseInit?: RequestInit): FetchLike; -/** - * Options for sending a JSON-RPC message. - */ -export type TransportSendOptions = { - /** - * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with. - */ - relatedRequestId?: RequestId; - /** - * The resumption token used to continue long-running requests that were interrupted. - * - * This allows clients to reconnect and continue from where they left off, if supported by the transport. - */ - resumptionToken?: string; - /** - * A callback that is invoked when the resumption token changes, if supported by the transport. - * - * This allows clients to persist the latest token for potential reconnection. - */ - onresumptiontoken?: (token: string) => void; -}; -/** - * Describes the minimal contract for a MCP transport that a client or server can communicate over. - */ -export interface Transport { - /** - * Starts processing messages on the transport, including any connection steps that might need to be taken. - * - * This method should only be called after callbacks are installed, or else messages may be lost. - * - * NOTE: This method should not be called explicitly when using Client, Server, or Protocol classes, as they will implicitly call start(). - */ - start(): Promise; - /** - * Sends a JSON-RPC message (request or response). - * - * If present, `relatedRequestId` is used to indicate to the transport which incoming request to associate this outgoing message with. - */ - send(message: JSONRPCMessage, options?: TransportSendOptions): Promise; - /** - * Closes the connection. - */ - close(): Promise; - /** - * Callback for when the connection is closed for any reason. - * - * This should be invoked when close() is called as well. - */ - onclose?: () => void; - /** - * Callback for when an error occurs. - * - * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. - */ - onerror?: (error: Error) => void; - /** - * Callback for when a message (request or response) is received over the connection. - * - * Includes the requestInfo and authInfo if the transport is authenticated. - * - * The requestInfo can be used to get the original request information (headers, etc.) - */ - onmessage?: (message: T, extra?: MessageExtraInfo) => void; - /** - * The session ID generated for this connection. - */ - sessionId?: string; - /** - * Sets the protocol version used for the connection (called when the initialize response is received). - */ - setProtocolVersion?: (version: string) => void; -} -//# sourceMappingURL=transport.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/transport.d.ts.map b/dist/esm/shared/transport.d.ts.map deleted file mode 100644 index 7a3d837df8..0000000000 --- a/dist/esm/shared/transport.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../../src/shared/transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAE1E,MAAM,MAAM,SAAS,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,EAAE,IAAI,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC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leted file mode 100644 index 486c840dd1..0000000000 --- a/dist/esm/shared/transport.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Normalizes HeadersInit to a plain Record for manipulation. - * Handles Headers objects, arrays of tuples, and plain objects. - */ -export function normalizeHeaders(headers) { - if (!headers) - return {}; - if (headers instanceof Headers) { - return Object.fromEntries(headers.entries()); - } - if (Array.isArray(headers)) { - return Object.fromEntries(headers); - } - return { ...headers }; -} -/** - * Creates a fetch function that includes base RequestInit options. - * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. - * - * @param baseFetch - The base fetch function to wrap (defaults to global fetch) - * @param baseInit - The base RequestInit to merge with each request - * @returns A wrapped fetch function that merges base options with call-specific options - */ -export function createFetchWithInit(baseFetch = fetch, baseInit) { - if (!baseInit) { - return baseFetch; - } - // Return a wrapped fetch that merges base RequestInit with call-specific init - return async (url, init) => { - const mergedInit = { - ...baseInit, - ...init, - // Headers need special handling - merge instead of replace - headers: (init === null || init === void 0 ? void 0 : init.headers) ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers - }; - return baseFetch(url, mergedInit); - }; -} -//# sourceMappingURL=transport.js.map \ No newline at end of file diff --git a/dist/esm/shared/transport.js.map b/dist/esm/shared/transport.js.map deleted file mode 100644 index 026dddb82e..0000000000 --- a/dist/esm/shared/transport.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"transport.js","sourceRoot":"","sources":["../../../src/shared/transport.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAgC;IAC7D,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,CAAC;IAExB,IAAI,OAAO,YAAY,OAAO,EAAE,CAAC;QAC7B,OAAO,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC;IACjD,CAAC;IAED,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACzB,OAAO,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,EAAE,GAAI,OAAkC,EAAE,CAAC;AACtD,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,mBAAmB,CAAC,YAAuB,KAAK,EAAE,QAAsB;IACpF,IAAI,CAAC,QAAQ,EAAE,CAAC;QACZ,OAAO,SAAS,CAAC;IACrB,CAAC;IAED,8EAA8E;IAC9E,OAAO,KAAK,EAAE,GAAiB,EAAE,IAAkB,EAAqB,EAAE;QACtE,MAAM,UAAU,GAAgB;YAC5B,GAAG,QAAQ;YACX,GAAG,IAAI;YACP,2DAA2D;YAC3D,OAAO,EAAE,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,EAAC,CAAC,CAAC,EAAE,GAAG,gBAAgB,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,GAAG,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO;SAC3H,CAAC;QACF,OAAO,SAAS,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC;IACtC,CAAC,CAAC;AACN,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/uriTemplate.d.ts b/dist/esm/shared/uriTemplate.d.ts deleted file mode 100644 index 175e329b66..0000000000 --- a/dist/esm/shared/uriTemplate.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -export type Variables = Record; -export declare class UriTemplate { - /** - * Returns true if the given string contains any URI template expressions. - * A template expression is a sequence of characters enclosed in curly braces, - * like {foo} or {?bar}. - */ - static isTemplate(str: string): boolean; - private static validateLength; - private readonly template; - private readonly parts; - get variableNames(): string[]; - constructor(template: string); - toString(): string; - private parse; - private getOperator; - private getNames; - private encodeValue; - private expandPart; - expand(variables: Variables): string; - private escapeRegExp; - private partToRegExp; - match(uri: string): Variables | null; -} -//# sourceMappingURL=uriTemplate.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/uriTemplate.d.ts.map b/dist/esm/shared/uriTemplate.d.ts.map deleted file mode 100644 index 052e91851e..0000000000 --- a/dist/esm/shared/uriTemplate.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"uriTemplate.d.ts","sourceRoot":"","sources":["../../../src/shared/uriTemplate.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC;AAO1D,qBAAa,WAAW;IACpB;;;;OAIG;IACH,MAAM,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAMvC,OAAO,CAAC,MAAM,CAAC,cAAc;IAK7B,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAyF;IAE/G,IAAI,aAAa,IAAI,MAAM,EAAE,CAE5B;gBAEW,QAAQ,EAAE,MAAM;IAM5B,QAAQ,IAAI,MAAM;IAIlB,OAAO,CAAC,KAAK;IA8Cb,OAAO,CAAC,WAAW;IAKnB,OAAO,CAAC,QAAQ;IAShB,OAAO,CAAC,WAAW;IAQnB,OAAO,CAAC,UAAU;IAsDlB,MAAM,CAAC,SAAS,EAAE,SAAS,GAAG,MAAM;IA4BpC,OAAO,CAAC,YAAY;IAIpB,OAAO,CAAC,YAAY;IAkDpB,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI;CAuCvC"} \ No newline at end of file diff --git a/dist/esm/shared/uriTemplate.js b/dist/esm/shared/uriTemplate.js deleted file mode 100644 index 2837ba826d..0000000000 --- a/dist/esm/shared/uriTemplate.js +++ /dev/null @@ -1,239 +0,0 @@ -// Claude-authored implementation of RFC 6570 URI Templates -const MAX_TEMPLATE_LENGTH = 1000000; // 1MB -const MAX_VARIABLE_LENGTH = 1000000; // 1MB -const MAX_TEMPLATE_EXPRESSIONS = 10000; -const MAX_REGEX_LENGTH = 1000000; // 1MB -export class UriTemplate { - /** - * Returns true if the given string contains any URI template expressions. - * A template expression is a sequence of characters enclosed in curly braces, - * like {foo} or {?bar}. - */ - static isTemplate(str) { - // Look for any sequence of characters between curly braces - // that isn't just whitespace - return /\{[^}\s]+\}/.test(str); - } - static validateLength(str, max, context) { - if (str.length > max) { - throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); - } - } - get variableNames() { - return this.parts.flatMap(part => (typeof part === 'string' ? [] : part.names)); - } - constructor(template) { - UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, 'Template'); - this.template = template; - this.parts = this.parse(template); - } - toString() { - return this.template; - } - parse(template) { - const parts = []; - let currentText = ''; - let i = 0; - let expressionCount = 0; - while (i < template.length) { - if (template[i] === '{') { - if (currentText) { - parts.push(currentText); - currentText = ''; - } - const end = template.indexOf('}', i); - if (end === -1) - throw new Error('Unclosed template expression'); - expressionCount++; - if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) { - throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); - } - const expr = template.slice(i + 1, end); - const operator = this.getOperator(expr); - const exploded = expr.includes('*'); - const names = this.getNames(expr); - const name = names[0]; - // Validate variable name length - for (const name of names) { - UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name'); - } - parts.push({ name, operator, names, exploded }); - i = end + 1; - } - else { - currentText += template[i]; - i++; - } - } - if (currentText) { - parts.push(currentText); - } - return parts; - } - getOperator(expr) { - const operators = ['+', '#', '.', '/', '?', '&']; - return operators.find(op => expr.startsWith(op)) || ''; - } - getNames(expr) { - const operator = this.getOperator(expr); - return expr - .slice(operator.length) - .split(',') - .map(name => name.replace('*', '').trim()) - .filter(name => name.length > 0); - } - encodeValue(value, operator) { - UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, 'Variable value'); - if (operator === '+' || operator === '#') { - return encodeURI(value); - } - return encodeURIComponent(value); - } - expandPart(part, variables) { - if (part.operator === '?' || part.operator === '&') { - const pairs = part.names - .map(name => { - const value = variables[name]; - if (value === undefined) - return ''; - const encoded = Array.isArray(value) - ? value.map(v => this.encodeValue(v, part.operator)).join(',') - : this.encodeValue(value.toString(), part.operator); - return `${name}=${encoded}`; - }) - .filter(pair => pair.length > 0); - if (pairs.length === 0) - return ''; - const separator = part.operator === '?' ? '?' : '&'; - return separator + pairs.join('&'); - } - if (part.names.length > 1) { - const values = part.names.map(name => variables[name]).filter(v => v !== undefined); - if (values.length === 0) - return ''; - return values.map(v => (Array.isArray(v) ? v[0] : v)).join(','); - } - const value = variables[part.name]; - if (value === undefined) - return ''; - const values = Array.isArray(value) ? value : [value]; - const encoded = values.map(v => this.encodeValue(v, part.operator)); - switch (part.operator) { - case '': - return encoded.join(','); - case '+': - return encoded.join(','); - case '#': - return '#' + encoded.join(','); - case '.': - return '.' + encoded.join('.'); - case '/': - return '/' + encoded.join('/'); - default: - return encoded.join(','); - } - } - expand(variables) { - let result = ''; - let hasQueryParam = false; - for (const part of this.parts) { - if (typeof part === 'string') { - result += part; - continue; - } - const expanded = this.expandPart(part, variables); - if (!expanded) - continue; - // Convert ? to & if we already have a query parameter - if ((part.operator === '?' || part.operator === '&') && hasQueryParam) { - result += expanded.replace('?', '&'); - } - else { - result += expanded; - } - if (part.operator === '?' || part.operator === '&') { - hasQueryParam = true; - } - } - return result; - } - escapeRegExp(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - } - partToRegExp(part) { - const patterns = []; - // Validate variable name length for matching - for (const name of part.names) { - UriTemplate.validateLength(name, MAX_VARIABLE_LENGTH, 'Variable name'); - } - if (part.operator === '?' || part.operator === '&') { - for (let i = 0; i < part.names.length; i++) { - const name = part.names[i]; - const prefix = i === 0 ? '\\' + part.operator : '&'; - patterns.push({ - pattern: prefix + this.escapeRegExp(name) + '=([^&]+)', - name - }); - } - return patterns; - } - let pattern; - const name = part.name; - switch (part.operator) { - case '': - pattern = part.exploded ? '([^/]+(?:,[^/]+)*)' : '([^/,]+)'; - break; - case '+': - case '#': - pattern = '(.+)'; - break; - case '.': - pattern = '\\.([^/,]+)'; - break; - case '/': - pattern = '/' + (part.exploded ? '([^/]+(?:,[^/]+)*)' : '([^/,]+)'); - break; - default: - pattern = '([^/]+)'; - } - patterns.push({ pattern, name }); - return patterns; - } - match(uri) { - UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, 'URI'); - let pattern = '^'; - const names = []; - for (const part of this.parts) { - if (typeof part === 'string') { - pattern += this.escapeRegExp(part); - } - else { - const patterns = this.partToRegExp(part); - for (const { pattern: partPattern, name } of patterns) { - pattern += partPattern; - names.push({ name, exploded: part.exploded }); - } - } - } - pattern += '$'; - UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, 'Generated regex pattern'); - const regex = new RegExp(pattern); - const match = uri.match(regex); - if (!match) - return null; - const result = {}; - for (let i = 0; i < names.length; i++) { - const { name, exploded } = names[i]; - const value = match[i + 1]; - const cleanName = name.replace('*', ''); - if (exploded && value.includes(',')) { - result[cleanName] = value.split(','); - } - else { - result[cleanName] = value; - } - } - return result; - } -} -//# sourceMappingURL=uriTemplate.js.map \ No newline at end of file diff --git a/dist/esm/shared/uriTemplate.js.map b/dist/esm/shared/uriTemplate.js.map deleted file mode 100644 index 2c02e92aee..0000000000 --- a/dist/esm/shared/uriTemplate.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"uriTemplate.js","sourceRoot":"","sources":["../../../src/shared/uriTemplate.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAI3D,MAAM,mBAAmB,GAAG,OAAO,CAAC,CAAC,MAAM;AAC3C,MAAM,mBAAmB,GAAG,OAAO,CAAC,CAAC,MAAM;AAC3C,MAAM,wBAAwB,GAAG,KAAK,CAAC;AACvC,MAAM,gBAAgB,GAAG,OAAO,CAAC,CAAC,MAAM;AAExC,MAAM,OAAO,WAAW;IACpB;;;;OAIG;IACH,MAAM,CAAC,UAAU,CAAC,GAAW;QACzB,2DAA2D;QAC3D,6BAA6B;QAC7B,OAA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,CAAC;iBAAM,CAAC;gBACJ,MAAM,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC;YAC9B,CAAC;QACL,CAAC;QAED,OAAO,MAAM,CAAC;IAClB,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/shared/zodTestMatrix.d.ts b/dist/esm/shared/zodTestMatrix.d.ts deleted file mode 100644 index 7dafd4ce93..0000000000 --- a/dist/esm/shared/zodTestMatrix.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import * as z3 from 'zod/v3'; -import * as z4 from 'zod/v4'; -export type ZNamespace = typeof z3 & typeof z4; -export declare const zodTestMatrix: readonly [{ - readonly zodVersionLabel: "Zod v3"; - readonly z: ZNamespace; - readonly isV3: true; - readonly isV4: false; -}, { - readonly zodVersionLabel: "Zod v4"; - readonly z: ZNamespace; - readonly isV3: false; - readonly isV4: true; -}]; -export type ZodMatrixEntry = (typeof zodTestMatrix)[number]; -//# sourceMappingURL=zodTestMatrix.d.ts.map \ No newline at end of file diff --git a/dist/esm/shared/zodTestMatrix.d.ts.map b/dist/esm/shared/zodTestMatrix.d.ts.map deleted file mode 100644 index 3842fb1c32..0000000000 --- a/dist/esm/shared/zodTestMatrix.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"zodTestMatrix.d.ts","sourceRoot":"","sources":["../../../src/shared/zodTestMatrix.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC7B,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAG7B,MAAM,MAAM,UAAU,GAAG,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC;AAE/C,eAAO,MAAM,aAAa;;gBAGT,UAAU;;;;;gBAMV,UAAU;;;EAIjB,CAAC;AAEX,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,aAAa,CAAC,CAAC,MAAM,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/shared/zodTestMatrix.js b/dist/esm/shared/zodTestMatrix.js deleted file mode 100644 index aafaed4757..0000000000 --- a/dist/esm/shared/zodTestMatrix.js +++ /dev/null @@ -1,17 +0,0 @@ -import * as z3 from 'zod/v3'; -import * as z4 from 'zod/v4'; -export const zodTestMatrix = [ - { - zodVersionLabel: 'Zod v3', - z: z3, - isV3: true, - isV4: false - }, - { - zodVersionLabel: 'Zod v4', - z: z4, - isV3: false, - isV4: true - } -]; -//# sourceMappingURL=zodTestMatrix.js.map \ No newline at end of file diff --git a/dist/esm/shared/zodTestMatrix.js.map b/dist/esm/shared/zodTestMatrix.js.map deleted file mode 100644 index 581a23a5b7..0000000000 --- a/dist/esm/shared/zodTestMatrix.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"zodTestMatrix.js","sourceRoot":"","sources":["../../../src/shared/zodTestMatrix.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAC7B,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAC;AAK7B,MAAM,CAAC,MAAM,aAAa,GAAG;IACzB;QACI,eAAe,EAAE,QAAQ;QACzB,CAAC,EAAE,EAAgB;QACnB,IAAI,EAAE,IAAa;QACnB,IAAI,EAAE,KAAc;KACvB;IACD;QACI,eAAe,EAAE,QAAQ;QACzB,CAAC,EAAE,EAAgB;QACnB,IAAI,EAAE,KAAc;QACpB,IAAI,EAAE,IAAa;KACtB;CACK,CAAC"} \ No newline at end of file diff --git a/dist/esm/spec.types.d.ts b/dist/esm/spec.types.d.ts deleted file mode 100644 index bf6a90f80c..0000000000 --- a/dist/esm/spec.types.d.ts +++ /dev/null @@ -1,2033 +0,0 @@ -/** - * This file is automatically generated from the Model Context Protocol specification. - * - * Source: https://github.com/modelcontextprotocol/modelcontextprotocol - * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts - * Last updated from commit: 4528444698f76e6d0337e58d2941d5d3485d779d - * - * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. - * To update this file, run: npm run fetch:spec-types - */ -/** - * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. - * - * @category JSON-RPC - */ -export type JSONRPCMessage = JSONRPCRequest | JSONRPCNotification | JSONRPCResponse | JSONRPCError; -/** @internal */ -export declare const LATEST_PROTOCOL_VERSION = "DRAFT-2025-v3"; -/** @internal */ -export declare const JSONRPC_VERSION = "2.0"; -/** - * A progress token, used to associate progress notifications with the original request. - * - * @category Common Types - */ -export type ProgressToken = string | number; -/** - * An opaque token used to represent a cursor for pagination. - * - * @category Common Types - */ -export type Cursor = string; -/** - * Common params for any request. - * - * @internal - */ -export interface RequestParams { - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - /** - * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. - */ - progressToken?: ProgressToken; - [key: string]: unknown; - }; -} -/** @internal */ -export interface Request { - method: string; - params?: { - [key: string]: any; - }; -} -/** @internal */ -export interface NotificationParams { - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** @internal */ -export interface Notification { - method: string; - params?: { - [key: string]: any; - }; -} -/** - * @category Common Types - */ -export interface Result { - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; - [key: string]: unknown; -} -/** - * @category Common Types - */ -export interface Error { - /** - * The error type that occurred. - */ - code: number; - /** - * A short description of the error. The message SHOULD be limited to a concise single sentence. - */ - message: string; - /** - * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). - */ - data?: unknown; -} -/** - * A uniquely identifying ID for a request in JSON-RPC. - * - * @category Common Types - */ -export type RequestId = string | number; -/** - * A request that expects a response. - * - * @category JSON-RPC - */ -export interface JSONRPCRequest extends Request { - jsonrpc: typeof JSONRPC_VERSION; - id: RequestId; -} -/** - * A notification which does not expect a response. - * - * @category JSON-RPC - */ -export interface JSONRPCNotification extends Notification { - jsonrpc: typeof JSONRPC_VERSION; -} -/** - * A successful (non-error) response to a request. - * - * @category JSON-RPC - */ -export interface JSONRPCResponse { - jsonrpc: typeof JSONRPC_VERSION; - id: RequestId; - result: Result; -} -export declare const PARSE_ERROR = -32700; -export declare const INVALID_REQUEST = -32600; -export declare const METHOD_NOT_FOUND = -32601; -export declare const INVALID_PARAMS = -32602; -export declare const INTERNAL_ERROR = -32603; -/** @internal */ -export declare const URL_ELICITATION_REQUIRED = -32042; -/** - * A response to a request that indicates an error occurred. - * - * @category JSON-RPC - */ -export interface JSONRPCError { - jsonrpc: typeof JSONRPC_VERSION; - id: RequestId; - error: Error; -} -/** - * An error response that indicates that the server requires the client to provide additional information via an elicitation request. - * - * @internal - */ -export interface URLElicitationRequiredError extends Omit { - error: Error & { - code: typeof URL_ELICITATION_REQUIRED; - data: { - elicitations: ElicitRequestURLParams[]; - [key: string]: unknown; - }; - }; -} -/** - * A response that indicates success but carries no data. - * - * @category Common Types - */ -export type EmptyResult = Result; -/** - * Parameters for a `notifications/cancelled` notification. - * - * @category `notifications/cancelled` - */ -export interface CancelledNotificationParams extends NotificationParams { - /** - * The ID of the request to cancel. - * - * This MUST correspond to the ID of a request previously issued in the same direction. - */ - requestId: RequestId; - /** - * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. - */ - reason?: string; -} -/** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its `initialize` request. - * - * @category `notifications/cancelled` - */ -export interface CancelledNotification extends JSONRPCNotification { - method: "notifications/cancelled"; - params: CancelledNotificationParams; -} -/** - * Parameters for an `initialize` request. - * - * @category `initialize` - */ -export interface InitializeRequestParams extends RequestParams { - /** - * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. - */ - protocolVersion: string; - capabilities: ClientCapabilities; - clientInfo: Implementation; -} -/** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - * - * @category `initialize` - */ -export interface InitializeRequest extends JSONRPCRequest { - method: "initialize"; - params: InitializeRequestParams; -} -/** - * After receiving an initialize request from the client, the server sends this response. - * - * @category `initialize` - */ -export interface InitializeResult extends Result { - /** - * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. - */ - protocolVersion: string; - capabilities: ServerCapabilities; - serverInfo: Implementation; - /** - * Instructions describing how to use the server and its features. - * - * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. - */ - instructions?: string; -} -/** - * This notification is sent from the client to the server after initialization has finished. - * - * @category `notifications/initialized` - */ -export interface InitializedNotification extends JSONRPCNotification { - method: "notifications/initialized"; - params?: NotificationParams; -} -/** - * 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. - * - * @category `initialize` - */ -export interface ClientCapabilities { - /** - * Experimental, non-standard capabilities that the client supports. - */ - experimental?: { - [key: string]: object; - }; - /** - * Present if the client supports listing roots. - */ - roots?: { - /** - * Whether the client supports notifications for changes to the roots list. - */ - listChanged?: boolean; - }; - /** - * Present if the client supports sampling from an LLM. - */ - sampling?: { - /** - * Whether the client supports context inclusion via includeContext parameter. - * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). - */ - context?: object; - /** - * Whether the client supports tool use via tools and toolChoice parameters. - */ - tools?: object; - }; - /** - * Present if the client supports elicitation from the server. - */ - elicitation?: { - form?: object; - url?: object; - }; -} -/** - * 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. - * - * @category `initialize` - */ -export interface ServerCapabilities { - /** - * Experimental, non-standard capabilities that the server supports. - */ - experimental?: { - [key: string]: object; - }; - /** - * Present if the server supports sending log messages to the client. - */ - logging?: object; - /** - * Present if the server supports argument autocompletion suggestions. - */ - completions?: object; - /** - * Present if the server offers any prompt templates. - */ - prompts?: { - /** - * Whether this server supports notifications for changes to the prompt list. - */ - listChanged?: boolean; - }; - /** - * Present if the server offers any resources to read. - */ - resources?: { - /** - * Whether this server supports subscribing to resource updates. - */ - subscribe?: boolean; - /** - * Whether this server supports notifications for changes to the resource list. - */ - listChanged?: boolean; - }; - /** - * Present if the server offers any tools to call. - */ - tools?: { - /** - * Whether this server supports notifications for changes to the tool list. - */ - listChanged?: boolean; - }; -} -/** - * An optionally-sized icon that can be displayed in a user interface. - * - * @category Common Types - */ -export interface Icon { - /** - * A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a - * `data:` URI with Base64-encoded image data. - * - * Consumers SHOULD takes steps to ensure URLs serving icons are from the - * same domain as the client/server or a trusted domain. - * - * Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain - * executable JavaScript. - * - * @format uri - */ - src: string; - /** - * Optional MIME type override if the source MIME type is missing or generic. - * For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`. - */ - mimeType?: string; - /** - * Optional array of strings that specify sizes at which the icon can be used. - * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. - * - * If not provided, the client should assume that the icon can be used at any size. - */ - sizes?: string[]; - /** - * Optional specifier for the theme this icon is designed for. `light` indicates - * the icon is designed to be used with a light background, and `dark` indicates - * the icon is designed to be used with a dark background. - * - * If not provided, the client should assume the icon can be used with any theme. - */ - theme?: "light" | "dark"; -} -/** - * Base interface to add `icons` property. - * - * @internal - */ -export interface Icons { - /** - * Optional set of sized icons that the client can display in a user interface. - * - * Clients that support rendering icons MUST support at least the following MIME types: - * - `image/png` - PNG images (safe, universal compatibility) - * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) - * - * Clients that support rendering icons SHOULD also support: - * - `image/svg+xml` - SVG images (scalable but requires security precautions) - * - `image/webp` - WebP images (modern, efficient format) - */ - icons?: Icon[]; -} -/** - * Base interface for metadata with name (identifier) and title (display name) properties. - * - * @internal - */ -export interface BaseMetadata { - /** - * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present). - */ - name: string; - /** - * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, - * even by those unfamiliar with domain-specific terminology. - * - * If not provided, the name should be used for display (except for Tool, - * where `annotations.title` should be given precedence over using `name`, - * if present). - */ - title?: string; -} -/** - * Describes the MCP implementation. - * - * @category `initialize` - */ -export interface Implementation extends BaseMetadata, Icons { - version: string; - /** - * An optional URL of the website for this implementation. - * - * @format uri - */ - websiteUrl?: string; -} -/** - * 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. - * - * @category `ping` - */ -export interface PingRequest extends JSONRPCRequest { - method: "ping"; - params?: RequestParams; -} -/** - * Parameters for a `notifications/progress` notification. - * - * @category `notifications/progress` - */ -export interface ProgressNotificationParams extends NotificationParams { - /** - * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. - */ - progressToken: ProgressToken; - /** - * The progress thus far. This should increase every time progress is made, even if the total is unknown. - * - * @TJS-type number - */ - progress: number; - /** - * Total number of items to process (or total progress required), if known. - * - * @TJS-type number - */ - total?: number; - /** - * An optional message describing the current progress. - */ - message?: string; -} -/** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - * - * @category `notifications/progress` - */ -export interface ProgressNotification extends JSONRPCNotification { - method: "notifications/progress"; - params: ProgressNotificationParams; -} -/** - * Common parameters for paginated requests. - * - * @internal - */ -export interface PaginatedRequestParams extends RequestParams { - /** - * An opaque token representing the current pagination position. - * If provided, the server should return results starting after this cursor. - */ - cursor?: Cursor; -} -/** @internal */ -export interface PaginatedRequest extends JSONRPCRequest { - params?: PaginatedRequestParams; -} -/** @internal */ -export interface PaginatedResult extends Result { - /** - * An opaque token representing the pagination position after the last returned result. - * If present, there may be more results available. - */ - nextCursor?: Cursor; -} -/** - * Sent from the client to request a list of resources the server has. - * - * @category `resources/list` - */ -export interface ListResourcesRequest extends PaginatedRequest { - method: "resources/list"; -} -/** - * The server's response to a resources/list request from the client. - * - * @category `resources/list` - */ -export interface ListResourcesResult extends PaginatedResult { - resources: Resource[]; -} -/** - * Sent from the client to request a list of resource templates the server has. - * - * @category `resources/templates/list` - */ -export interface ListResourceTemplatesRequest extends PaginatedRequest { - method: "resources/templates/list"; -} -/** - * The server's response to a resources/templates/list request from the client. - * - * @category `resources/templates/list` - */ -export interface ListResourceTemplatesResult extends PaginatedResult { - resourceTemplates: ResourceTemplate[]; -} -/** - * Common parameters when working with resources. - * - * @internal - */ -export interface ResourceRequestParams extends RequestParams { - /** - * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it. - * - * @format uri - */ - uri: string; -} -/** - * Parameters for a `resources/read` request. - * - * @category `resources/read` - */ -export interface ReadResourceRequestParams extends ResourceRequestParams { -} -/** - * Sent from the client to the server, to read a specific resource URI. - * - * @category `resources/read` - */ -export interface ReadResourceRequest extends JSONRPCRequest { - method: "resources/read"; - params: ReadResourceRequestParams; -} -/** - * The server's response to a resources/read request from the client. - * - * @category `resources/read` - */ -export interface ReadResourceResult extends Result { - contents: (TextResourceContents | BlobResourceContents)[]; -} -/** - * 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. - * - * @category `notifications/resources/list_changed` - */ -export interface ResourceListChangedNotification extends JSONRPCNotification { - method: "notifications/resources/list_changed"; - params?: NotificationParams; -} -/** - * Parameters for a `resources/subscribe` request. - * - * @category `resources/subscribe` - */ -export interface SubscribeRequestParams extends ResourceRequestParams { -} -/** - * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. - * - * @category `resources/subscribe` - */ -export interface SubscribeRequest extends JSONRPCRequest { - method: "resources/subscribe"; - params: SubscribeRequestParams; -} -/** - * Parameters for a `resources/unsubscribe` request. - * - * @category `resources/unsubscribe` - */ -export interface UnsubscribeRequestParams extends ResourceRequestParams { -} -/** - * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. - * - * @category `resources/unsubscribe` - */ -export interface UnsubscribeRequest extends JSONRPCRequest { - method: "resources/unsubscribe"; - params: UnsubscribeRequestParams; -} -/** - * Parameters for a `notifications/resources/updated` notification. - * - * @category `notifications/resources/updated` - */ -export interface ResourceUpdatedNotificationParams extends NotificationParams { - /** - * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. - * - * @format uri - */ - uri: string; -} -/** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. - * - * @category `notifications/resources/updated` - */ -export interface ResourceUpdatedNotification extends JSONRPCNotification { - method: "notifications/resources/updated"; - params: ResourceUpdatedNotificationParams; -} -/** - * A known resource that the server is capable of reading. - * - * @category `resources/list` - */ -export interface Resource extends BaseMetadata, Icons { - /** - * The URI of this resource. - * - * @format uri - */ - uri: string; - /** - * A description of what this resource represents. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description?: string; - /** - * The MIME type of this resource, if known. - */ - mimeType?: string; - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - /** - * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. - * - * This can be used by Hosts to display file sizes and estimate context window usage. - */ - size?: number; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * A template description for resources available on the server. - * - * @category `resources/templates/list` - */ -export interface ResourceTemplate extends BaseMetadata, Icons { - /** - * A URI template (according to RFC 6570) that can be used to construct resource URIs. - * - * @format uri-template - */ - uriTemplate: string; - /** - * A description of what this template is for. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description?: string; - /** - * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. - */ - mimeType?: string; - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * The contents of a specific resource or sub-resource. - * - * @internal - */ -export interface ResourceContents { - /** - * The URI of this resource. - * - * @format uri - */ - uri: string; - /** - * The MIME type of this resource, if known. - */ - mimeType?: string; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * @category Content - */ -export interface TextResourceContents extends ResourceContents { - /** - * The text of the item. This must only be set if the item can actually be represented as text (not binary data). - */ - text: string; -} -/** - * @category Content - */ -export interface BlobResourceContents extends ResourceContents { - /** - * A base64-encoded string representing the binary data of the item. - * - * @format byte - */ - blob: string; -} -/** - * Sent from the client to request a list of prompts and prompt templates the server has. - * - * @category `prompts/list` - */ -export interface ListPromptsRequest extends PaginatedRequest { - method: "prompts/list"; -} -/** - * The server's response to a prompts/list request from the client. - * - * @category `prompts/list` - */ -export interface ListPromptsResult extends PaginatedResult { - prompts: Prompt[]; -} -/** - * Parameters for a `prompts/get` request. - * - * @category `prompts/get` - */ -export interface GetPromptRequestParams extends RequestParams { - /** - * The name of the prompt or prompt template. - */ - name: string; - /** - * Arguments to use for templating the prompt. - */ - arguments?: { - [key: string]: string; - }; -} -/** - * Used by the client to get a prompt provided by the server. - * - * @category `prompts/get` - */ -export interface GetPromptRequest extends JSONRPCRequest { - method: "prompts/get"; - params: GetPromptRequestParams; -} -/** - * The server's response to a prompts/get request from the client. - * - * @category `prompts/get` - */ -export interface GetPromptResult extends Result { - /** - * An optional description for the prompt. - */ - description?: string; - messages: PromptMessage[]; -} -/** - * A prompt or prompt template that the server offers. - * - * @category `prompts/list` - */ -export interface Prompt extends BaseMetadata, Icons { - /** - * An optional description of what this prompt provides - */ - description?: string; - /** - * A list of arguments to use for templating the prompt. - */ - arguments?: PromptArgument[]; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * Describes an argument that a prompt can accept. - * - * @category `prompts/list` - */ -export interface PromptArgument extends BaseMetadata { - /** - * A human-readable description of the argument. - */ - description?: string; - /** - * Whether this argument must be provided. - */ - required?: boolean; -} -/** - * The sender or recipient of messages and data in a conversation. - * - * @category Common Types - */ -export type Role = "user" | "assistant"; -/** - * Describes a message returned as part of a prompt. - * - * This is similar to `SamplingMessage`, but also supports the embedding of - * resources from the MCP server. - * - * @category `prompts/get` - */ -export interface PromptMessage { - role: Role; - content: ContentBlock; -} -/** - * A resource that the server is capable of reading, included in a prompt or tool call result. - * - * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. - * - * @category Content - */ -export interface ResourceLink extends Resource { - type: "resource_link"; -} -/** - * The contents of a resource, embedded into a prompt or tool call result. - * - * It is up to the client how best to render embedded resources for the benefit - * of the LLM and/or the user. - * - * @category Content - */ -export interface EmbeddedResource { - type: "resource"; - resource: TextResourceContents | BlobResourceContents; - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * 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. - * - * @category `notifications/prompts/list_changed` - */ -export interface PromptListChangedNotification extends JSONRPCNotification { - method: "notifications/prompts/list_changed"; - params?: NotificationParams; -} -/** - * Sent from the client to request a list of tools the server has. - * - * @category `tools/list` - */ -export interface ListToolsRequest extends PaginatedRequest { - method: "tools/list"; -} -/** - * The server's response to a tools/list request from the client. - * - * @category `tools/list` - */ -export interface ListToolsResult extends PaginatedResult { - tools: Tool[]; -} -/** - * The server's response to a tool call. - * - * @category `tools/call` - */ -export interface CallToolResult extends Result { - /** - * A list of content objects that represent the unstructured result of the tool call. - */ - content: ContentBlock[]; - /** - * An optional JSON object that represents the structured result of the tool call. - */ - structuredContent?: { - [key: string]: unknown; - }; - /** - * Whether the tool call ended in an error. - * - * If not set, this is assumed to be false (the call was successful). - * - * Any errors that originate from the tool SHOULD be reported inside the result - * object, with `isError` set to true, _not_ as an MCP protocol-level error - * response. Otherwise, the LLM would not be able to see that an error occurred - * and self-correct. - * - * However, any errors in _finding_ the tool, an error indicating that the - * server does not support tool calls, or any other exceptional conditions, - * should be reported as an MCP error response. - */ - isError?: boolean; -} -/** - * Parameters for a `tools/call` request. - * - * @category `tools/call` - */ -export interface CallToolRequestParams extends RequestParams { - /** - * The name of the tool. - */ - name: string; - /** - * Arguments to use for the tool call. - */ - arguments?: { - [key: string]: unknown; - }; -} -/** - * Used by the client to invoke a tool provided by the server. - * - * @category `tools/call` - */ -export interface CallToolRequest extends JSONRPCRequest { - method: "tools/call"; - params: CallToolRequestParams; -} -/** - * 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. - * - * @category `notifications/tools/list_changed` - */ -export interface ToolListChangedNotification extends JSONRPCNotification { - method: "notifications/tools/list_changed"; - params?: NotificationParams; -} -/** - * Security scheme indicating no authentication is required. - * - * @category `tools/list` - */ -export interface NoAuthSecurityScheme { - type: "noauth"; -} -/** - * Security scheme indicating OAuth 2.0 authentication is required. - * - * @category `tools/list` - */ -export interface OAuth2SecurityScheme { - type: "oauth2"; - /** - * Optional list of OAuth 2.0 scopes required for this tool. - */ - scopes?: string[]; -} -/** - * A security scheme that can be used to authenticate tool calls. - * - * @category `tools/list` - */ -export type SecurityScheme = NoAuthSecurityScheme | OAuth2SecurityScheme; -/** - * Additional properties describing a Tool to clients. - * - * NOTE: all properties in ToolAnnotations are **hints**. - * They are not guaranteed to provide a faithful description of - * tool behavior (including descriptive properties like `title`). - * - * Clients should never make tool use decisions based on ToolAnnotations - * received from untrusted servers. - * - * @category `tools/list` - */ -export interface ToolAnnotations { - /** - * A human-readable title for the tool. - */ - title?: string; - /** - * If true, the tool does not modify its environment. - * - * Default: false - */ - readOnlyHint?: boolean; - /** - * If true, the tool may perform destructive updates to its environment. - * If false, the tool performs only additive updates. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: true - */ - destructiveHint?: boolean; - /** - * If true, calling the tool repeatedly with the same arguments - * will have no additional effect on its environment. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: false - */ - idempotentHint?: boolean; - /** - * If true, this tool may interact with an "open world" of external - * entities. If false, the tool's domain of interaction is closed. - * For example, the world of a web search tool is open, whereas that - * of a memory tool is not. - * - * Default: true - */ - openWorldHint?: boolean; -} -/** - * Definition for a tool the client can call. - * - * @category `tools/list` - */ -export interface Tool extends BaseMetadata, Icons { - /** - * A human-readable description of the tool. - * - * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. - */ - description?: string; - /** - * A JSON Schema object defining the expected parameters for the tool. - */ - inputSchema: { - type: "object"; - properties?: { - [key: string]: object; - }; - required?: string[]; - }; - /** - * An optional JSON Schema object defining the structure of the tool's output returned in - * the structuredContent field of a CallToolResult. - */ - outputSchema?: { - type: "object"; - properties?: { - [key: string]: object; - }; - required?: string[]; - }; - /** - * Optional additional tool information. - * - * Display name precedence order is: title, annotations.title, then name. - */ - annotations?: ToolAnnotations; - /** - * Optional list of security schemes supported by this tool. - * If missing, the tool follows the server's default authentication policy. - * If present, lists the supported authentication schemes (e.g., "noauth", "oauth2"). - */ - securitySchemes?: SecurityScheme[]; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * Parameters for a `logging/setLevel` request. - * - * @category `logging/setLevel` - */ -export interface SetLevelRequestParams extends RequestParams { - /** - * 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/message. - */ - level: LoggingLevel; -} -/** - * A request from the client to the server, to enable or adjust logging. - * - * @category `logging/setLevel` - */ -export interface SetLevelRequest extends JSONRPCRequest { - method: "logging/setLevel"; - params: SetLevelRequestParams; -} -/** - * Parameters for a `notifications/message` notification. - * - * @category `notifications/message` - */ -export interface LoggingMessageNotificationParams extends NotificationParams { - /** - * The severity of this log message. - */ - level: LoggingLevel; - /** - * An optional name of the logger issuing this message. - */ - logger?: string; - /** - * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. - */ - data: unknown; -} -/** - * JSONRPCNotification 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. - * - * @category `notifications/message` - */ -export interface LoggingMessageNotification extends JSONRPCNotification { - method: "notifications/message"; - params: LoggingMessageNotificationParams; -} -/** - * The severity of a log message. - * - * These map to syslog message severities, as specified in RFC-5424: - * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 - * - * @category Common Types - */ -export type LoggingLevel = "debug" | "info" | "notice" | "warning" | "error" | "critical" | "alert" | "emergency"; -/** - * Parameters for a `sampling/createMessage` request. - * - * @category `sampling/createMessage` - */ -export interface CreateMessageRequestParams extends RequestParams { - messages: SamplingMessage[]; - /** - * The server's preferences for which model to select. The client MAY ignore these preferences. - */ - modelPreferences?: ModelPreferences; - /** - * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. - */ - systemPrompt?: string; - /** - * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. - * The client MAY ignore this request. - * - * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client - * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. - */ - includeContext?: "none" | "thisServer" | "allServers"; - /** - * @TJS-type number - */ - temperature?: number; - /** - * The requested maximum number of tokens to sample (to prevent runaway completions). - * - * The client MAY choose to sample fewer tokens than the requested maximum. - */ - maxTokens: number; - stopSequences?: string[]; - /** - * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. - */ - metadata?: object; - /** - * Tools that the model may use during generation. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. - */ - tools?: Tool[]; - /** - * Controls how the model uses tools. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. - * Default is `{ mode: "auto" }`. - */ - toolChoice?: ToolChoice; -} -/** - * Controls tool selection behavior for sampling requests. - * - * @category `sampling/createMessage` - */ -export interface ToolChoice { - /** - * Controls the tool use ability of the model: - * - "auto": Model decides whether to use tools (default) - * - "required": Model MUST use at least one tool before completing - * - "none": Model MUST NOT use any tools - */ - mode?: "auto" | "required" | "none"; -} -/** - * 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. - * - * @category `sampling/createMessage` - */ -export interface CreateMessageRequest extends JSONRPCRequest { - method: "sampling/createMessage"; - params: CreateMessageRequestParams; -} -/** - * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. - * - * @category `sampling/createMessage` - */ -export interface CreateMessageResult extends Result, SamplingMessage { - /** - * The name of the model that generated the message. - */ - model: string; - /** - * The reason why sampling stopped, if known. - * - * Standard values: - * - "endTurn": Natural end of the assistant's turn - * - "stopSequence": A stop sequence was encountered - * - "maxTokens": Maximum token limit was reached - * - "toolUse": The model wants to use one or more tools - * - * This field is an open string to allow for provider-specific stop reasons. - */ - stopReason?: "endTurn" | "stopSequence" | "maxTokens" | "toolUse" | string; -} -/** - * Describes a message issued to or received from an LLM API. - * - * @category `sampling/createMessage` - */ -export interface SamplingMessage { - role: Role; - content: SamplingMessageContentBlock | SamplingMessageContentBlock[]; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -export type SamplingMessageContentBlock = TextContent | ImageContent | AudioContent | ToolUseContent | ToolResultContent; -/** - * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed - * - * @category Common Types - */ -export interface Annotations { - /** - * Describes who the intended customer of this object or data is. - * - * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). - */ - audience?: Role[]; - /** - * Describes how important this data is for operating the server. - * - * A value of 1 means "most important," and indicates that the data is - * effectively required, while 0 means "least important," and indicates that - * the data is entirely optional. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - priority?: number; - /** - * The moment the resource was last modified, as an ISO 8601 formatted string. - * - * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"). - * - * Examples: last activity timestamp in an open file, timestamp when the resource - * was attached, etc. - */ - lastModified?: string; -} -/** - * @category Content - */ -export type ContentBlock = TextContent | ImageContent | AudioContent | ResourceLink | EmbeddedResource; -/** - * Text provided to or from an LLM. - * - * @category Content - */ -export interface TextContent { - type: "text"; - /** - * The text content of the message. - */ - text: string; - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * An image provided to or from an LLM. - * - * @category Content - */ -export interface ImageContent { - type: "image"; - /** - * The base64-encoded image data. - * - * @format byte - */ - data: string; - /** - * The MIME type of the image. Different providers may support different image types. - */ - mimeType: string; - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * Audio provided to or from an LLM. - * - * @category Content - */ -export interface AudioContent { - type: "audio"; - /** - * The base64-encoded audio data. - * - * @format byte - */ - data: string; - /** - * The MIME type of the audio. Different providers may support different audio types. - */ - mimeType: string; - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * A request from the assistant to call a tool. - * - * @category `sampling/createMessage` - */ -export interface ToolUseContent { - type: "tool_use"; - /** - * A unique identifier for this tool use. - * - * This ID is used to match tool results to their corresponding tool uses. - */ - id: string; - /** - * The name of the tool to call. - */ - name: string; - /** - * The arguments to pass to the tool, conforming to the tool's input schema. - */ - input: { - [key: string]: unknown; - }; - /** - * Optional metadata about the tool use. Clients SHOULD preserve this field when - * including tool uses in subsequent sampling requests to enable caching optimizations. - * - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * The result of a tool use, provided by the user back to the assistant. - * - * @category `sampling/createMessage` - */ -export interface ToolResultContent { - type: "tool_result"; - /** - * The ID of the tool use this result corresponds to. - * - * This MUST match the ID from a previous ToolUseContent. - */ - toolUseId: string; - /** - * The unstructured result content of the tool use. - * - * This has the same format as CallToolResult.content and can include text, images, - * audio, resource links, and embedded resources. - */ - content: ContentBlock[]; - /** - * An optional structured result object. - * - * If the tool defined an outputSchema, this SHOULD conform to that schema. - */ - structuredContent?: { - [key: string]: unknown; - }; - /** - * Whether the tool use resulted in an error. - * - * If true, the content typically describes the error that occurred. - * Default: false - */ - isError?: boolean; - /** - * Optional metadata about the tool result. Clients SHOULD preserve this field when - * including tool results in subsequent sampling requests to enable caching optimizations. - * - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * The server's preferences for model selection, requested of the client during sampling. - * - * Because LLMs can vary along multiple dimensions, choosing the "best" model is - * rarely straightforward. Different models excel in different areas—some are - * faster but less capable, others are more capable but more expensive, and so - * on. This interface allows servers to express their priorities across multiple - * dimensions to help clients make an appropriate selection for their use case. - * - * These preferences are always advisory. The client MAY ignore them. It is also - * up to the client to decide how to interpret these preferences and how to - * balance them against other considerations. - * - * @category `sampling/createMessage` - */ -export interface ModelPreferences { - /** - * Optional hints to use for model selection. - * - * If multiple hints are specified, the client MUST evaluate them in order - * (such that the first match is taken). - * - * The client SHOULD prioritize these hints over the numeric priorities, but - * MAY still use the priorities to select from ambiguous matches. - */ - hints?: ModelHint[]; - /** - * How much to prioritize cost when selecting a model. A value of 0 means cost - * is not important, while a value of 1 means cost is the most important - * factor. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - costPriority?: number; - /** - * How much to prioritize sampling speed (latency) when selecting a model. A - * value of 0 means speed is not important, while a value of 1 means speed is - * the most important factor. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - speedPriority?: number; - /** - * How much to prioritize intelligence and capabilities when selecting a - * model. A value of 0 means intelligence is not important, while a value of 1 - * means intelligence is the most important factor. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - intelligencePriority?: number; -} -/** - * Hints to use for model selection. - * - * Keys not declared here are currently left unspecified by the spec and are up - * to the client to interpret. - * - * @category `sampling/createMessage` - */ -export interface ModelHint { - /** - * A hint for a model name. - * - * The client SHOULD treat this as a substring of a model name; for example: - * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` - * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. - * - `claude` should match any Claude model - * - * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: - * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` - */ - name?: string; -} -/** - * Parameters for a `completion/complete` request. - * - * @category `completion/complete` - */ -export interface CompleteRequestParams extends RequestParams { - ref: PromptReference | ResourceTemplateReference; - /** - * The argument's information - */ - argument: { - /** - * The name of the argument - */ - name: string; - /** - * The value of the argument to use for completion matching. - */ - value: string; - }; - /** - * Additional, optional context for completions - */ - context?: { - /** - * Previously-resolved variables in a URI template or prompt. - */ - arguments?: { - [key: string]: string; - }; - }; -} -/** - * A request from the client to the server, to ask for completion options. - * - * @category `completion/complete` - */ -export interface CompleteRequest extends JSONRPCRequest { - method: "completion/complete"; - params: CompleteRequestParams; -} -/** - * The server's response to a completion/complete request - * - * @category `completion/complete` - */ -export interface CompleteResult extends Result { - completion: { - /** - * An array of completion values. Must not exceed 100 items. - */ - values: string[]; - /** - * The total number of completion options available. This can exceed the number of values actually sent in the response. - */ - total?: number; - /** - * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. - */ - hasMore?: boolean; - }; -} -/** - * A reference to a resource or resource template definition. - * - * @category `completion/complete` - */ -export interface ResourceTemplateReference { - type: "ref/resource"; - /** - * The URI or URI template of the resource. - * - * @format uri-template - */ - uri: string; -} -/** - * Identifies a prompt. - * - * @category `completion/complete` - */ -export interface PromptReference extends BaseMetadata { - type: "ref/prompt"; -} -/** - * Sent from the server to request a list of root URIs from the client. Roots allow - * servers to ask for specific directories or files to operate on. A common example - * for roots is providing a set of repositories or directories a server should operate - * on. - * - * This request is typically used when the server needs to understand the file system - * structure or access specific locations that the client has permission to read from. - * - * @category `roots/list` - */ -export interface ListRootsRequest extends JSONRPCRequest { - method: "roots/list"; - params?: RequestParams; -} -/** - * The client's response to a roots/list request from the server. - * This result contains an array of Root objects, each representing a root directory - * or file that the server can operate on. - * - * @category `roots/list` - */ -export interface ListRootsResult extends Result { - roots: Root[]; -} -/** - * Represents a root directory or file that the server can operate on. - * - * @category `roots/list` - */ -export interface Root { - /** - * The URI identifying the root. This *must* start with file:// for now. - * This restriction may be relaxed in future versions of the protocol to allow - * other URI schemes. - * - * @format uri - */ - uri: string; - /** - * An optional name for the root. This can be used to provide a human-readable - * identifier for the root, which may be useful for display purposes or for - * referencing the root in other parts of the application. - */ - name?: string; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - [key: string]: unknown; - }; -} -/** - * A notification from the client to the server, informing it that the list of roots has changed. - * This notification should be sent whenever the client adds, removes, or modifies any root. - * The server should then request an updated list of roots using the ListRootsRequest. - * - * @category `notifications/roots/list_changed` - */ -export interface RootsListChangedNotification extends JSONRPCNotification { - method: "notifications/roots/list_changed"; - params?: NotificationParams; -} -/** - * The parameters for a request to elicit non-sensitive information from the user via a form in the client. - * - * @category `elicitation/create` - */ -export interface ElicitRequestFormParams extends RequestParams { - /** - * The elicitation mode. - */ - mode: "form"; - /** - * The message to present to the user describing what information is being requested. - */ - message: string; - /** - * A restricted subset of JSON Schema. - * Only top-level properties are allowed, without nesting. - */ - requestedSchema: { - type: "object"; - properties: { - [key: string]: PrimitiveSchemaDefinition; - }; - required?: string[]; - }; -} -/** - * The parameters for a request to elicit information from the user via a URL in the client. - * - * @category `elicitation/create` - */ -export interface ElicitRequestURLParams extends RequestParams { - /** - * The elicitation mode. - */ - mode: "url"; - /** - * The message to present to the user explaining why the interaction is needed. - */ - message: string; - /** - * The ID of the elicitation, which must be unique within the context of the server. - * The client MUST treat this ID as an opaque value. - */ - elicitationId: string; - /** - * The URL that the user should navigate to. - * - * @format uri - */ - url: string; -} -/** - * The parameters for a request to elicit additional information from the user via the client. - * - * @category `elicitation/create` - */ -export type ElicitRequestParams = ElicitRequestFormParams | ElicitRequestURLParams; -/** - * A request from the server to elicit additional information from the user via the client. - * - * @category `elicitation/create` - */ -export interface ElicitRequest extends JSONRPCRequest { - method: "elicitation/create"; - params: ElicitRequestParams; -} -/** - * Restricted schema definitions that only allow primitive types - * without nested objects or arrays. - * - * @category `elicitation/create` - */ -export type PrimitiveSchemaDefinition = StringSchema | NumberSchema | BooleanSchema | EnumSchema; -/** - * @category `elicitation/create` - */ -export interface StringSchema { - type: "string"; - title?: string; - description?: string; - minLength?: number; - maxLength?: number; - format?: "email" | "uri" | "date" | "date-time"; - default?: string; -} -/** - * @category `elicitation/create` - */ -export interface NumberSchema { - type: "number" | "integer"; - title?: string; - description?: string; - minimum?: number; - maximum?: number; - default?: number; -} -/** - * @category `elicitation/create` - */ -export interface BooleanSchema { - type: "boolean"; - title?: string; - description?: string; - default?: boolean; -} -/** - * Schema for single-selection enumeration without display titles for options. - * - * @category `elicitation/create` - */ -export interface UntitledSingleSelectEnumSchema { - type: "string"; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Array of enum values to choose from. - */ - enum: string[]; - /** - * Optional default value. - */ - default?: string; -} -/** - * Schema for single-selection enumeration with display titles for each option. - * - * @category `elicitation/create` - */ -export interface TitledSingleSelectEnumSchema { - type: "string"; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Array of enum options with values and display labels. - */ - oneOf: Array<{ - /** - * The enum value. - */ - const: string; - /** - * Display label for this option. - */ - title: string; - }>; - /** - * Optional default value. - */ - default?: string; -} -/** - * @category `elicitation/create` - */ -export type SingleSelectEnumSchema = UntitledSingleSelectEnumSchema | TitledSingleSelectEnumSchema; -/** - * Schema for multiple-selection enumeration without display titles for options. - * - * @category `elicitation/create` - */ -export interface UntitledMultiSelectEnumSchema { - type: "array"; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Minimum number of items to select. - */ - minItems?: number; - /** - * Maximum number of items to select. - */ - maxItems?: number; - /** - * Schema for the array items. - */ - items: { - type: "string"; - /** - * Array of enum values to choose from. - */ - enum: string[]; - }; - /** - * Optional default value. - */ - default?: string[]; -} -/** - * Schema for multiple-selection enumeration with display titles for each option. - * - * @category `elicitation/create` - */ -export interface TitledMultiSelectEnumSchema { - type: "array"; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Minimum number of items to select. - */ - minItems?: number; - /** - * Maximum number of items to select. - */ - maxItems?: number; - /** - * Schema for array items with enum options and display labels. - */ - items: { - /** - * Array of enum options with values and display labels. - */ - anyOf: Array<{ - /** - * The constant enum value. - */ - const: string; - /** - * Display title for this option. - */ - title: string; - }>; - }; - /** - * Optional default value. - */ - default?: string[]; -} -/** - * @category `elicitation/create` - */ -export type MultiSelectEnumSchema = UntitledMultiSelectEnumSchema | TitledMultiSelectEnumSchema; -/** - * Use TitledSingleSelectEnumSchema instead. - * This interface will be removed in a future version. - * - * @category `elicitation/create` - */ -export interface LegacyTitledEnumSchema { - type: "string"; - title?: string; - description?: string; - enum: string[]; - /** - * (Legacy) Display names for enum values. - * Non-standard according to JSON schema 2020-12. - */ - enumNames?: string[]; - default?: string; -} -/** - * @category `elicitation/create` - */ -export type EnumSchema = SingleSelectEnumSchema | MultiSelectEnumSchema | LegacyTitledEnumSchema; -/** - * The client's response to an elicitation request. - * - * @category `elicitation/create` - */ -export interface ElicitResult extends Result { - /** - * The user action in response to the elicitation. - * - "accept": User submitted the form/confirmed the action - * - "decline": User explicitly decline the action - * - "cancel": User dismissed without making an explicit choice - */ - action: "accept" | "decline" | "cancel"; - /** - * The submitted form data, only present when action is "accept" and mode was "form". - * Contains values matching the requested schema. - * Omitted for out-of-band mode responses. - */ - content?: { - [key: string]: string | number | boolean | string[]; - }; -} -/** - * An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request. - * - * @category `notifications/elicitation/complete` - */ -export interface ElicitationCompleteNotification extends JSONRPCNotification { - method: "notifications/elicitation/complete"; - params: { - /** - * The ID of the elicitation that completed. - */ - elicitationId: string; - }; -} -/** @internal */ -export type ClientRequest = PingRequest | InitializeRequest | CompleteRequest | SetLevelRequest | GetPromptRequest | ListPromptsRequest | ListResourcesRequest | ListResourceTemplatesRequest | ReadResourceRequest | SubscribeRequest | UnsubscribeRequest | CallToolRequest | ListToolsRequest; -/** @internal */ -export type ClientNotification = CancelledNotification | ProgressNotification | InitializedNotification | RootsListChangedNotification; -/** @internal */ -export type ClientResult = EmptyResult | CreateMessageResult | ListRootsResult | ElicitResult; -/** @internal */ -export type ServerRequest = PingRequest | CreateMessageRequest | ListRootsRequest | ElicitRequest; -/** @internal */ -export type ServerNotification = CancelledNotification | ProgressNotification | LoggingMessageNotification | ResourceUpdatedNotification | ResourceListChangedNotification | ToolListChangedNotification | PromptListChangedNotification | ElicitationCompleteNotification; -/** @internal */ -export type ServerResult = EmptyResult | InitializeResult | CompleteResult | GetPromptResult | ListPromptsResult | ListResourceTemplatesResult | ListResourcesResult | ReadResourceResult | CallToolResult | ListToolsResult; -//# sourceMappingURL=spec.types.d.ts.map \ No newline at end of file diff --git a/dist/esm/spec.types.d.ts.map b/dist/esm/spec.types.d.ts.map deleted file mode 100644 index 3e44f68e82..0000000000 --- a/dist/esm/spec.types.d.ts.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ACrB,WAAW,GACX,oBAAoB,GACpB,gBAAgB,GAChB,aAAa,CAAC;AAElB,gBAAgB;AAChB,MAAM,MAAM,kBAAkB,GAC1B,qBAAqB,GACrB,oBAAoB,GACpB,0BAA0B,GAC1B,2BAA2B,GAC3B,+BAA+B,GAC/B,2BAA2B,GAC3B,6BAA6B,GAC7B,+BAA+B,CAAC;AAEpC,gBAAgB;AAChB,MAAM,MAAM,YAAY,GACpB,WAAW,GACX,gBAAgB,GAChB,cAAc,GACd,eAAe,GACf,iBAAiB,GACjB,2BAA2B,GAC3B,mBAAmB,GACnB,kBAAkB,GAClB,cAAc,GACd,eAAe,CAAC"} \ No newline at end of file diff --git a/dist/esm/spec.types.js b/dist/esm/spec.types.js deleted file mode 100644 index 720ec03b73..0000000000 --- a/dist/esm/spec.types.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * This file is automatically generated from the Model Context Protocol specification. - * - * Source: https://github.com/modelcontextprotocol/modelcontextprotocol - * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts - * Last updated from commit: 4528444698f76e6d0337e58d2941d5d3485d779d - * - * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. - * To update this file, run: npm run fetch:spec-types - */ /* JSON-RPC types */ -/** @internal */ -export const LATEST_PROTOCOL_VERSION = "DRAFT-2025-v3"; -/** @internal */ -export const JSONRPC_VERSION = "2.0"; -// Standard JSON-RPC error codes -export const PARSE_ERROR = -32700; -export const INVALID_REQUEST = -32600; -export const METHOD_NOT_FOUND = -32601; -export const INVALID_PARAMS = -32602; -export const INTERNAL_ERROR = -32603; -// Implementation-specific JSON-RPC error codes [-32000, -32099] -/** @internal */ -export const URL_ELICITATION_REQUIRED = -32042; -//# sourceMappingURL=spec.types.js.map \ No newline at end of file diff --git a/dist/esm/spec.types.js.map b/dist/esm/spec.types.js.map deleted file mode 100644 index d2c9dd0aa6..0000000000 --- a/dist/esm/spec.types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"spec.types.js","sourceRoot":"","sources":["../../src/spec.types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG,CAAA,oBAAoB;AAavB,gBAAgB;AAChB,MAAM,CAAC,MAAM,uBAAuB,GAAG,eAAe,CAAC;AACvD,gBAAgB;AAChB,MAAM,CAAC,MAAM,eAAe,GAAG,KAAK,CAAC;AA4HrC,gCAAgC;AAChC,MAAM,CAAC,MAAM,WAAW,GAAG,CAAC,KAAK,CAAC;AAClC,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,KAAK,CAAC;AACtC,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,KAAK,CAAC;AACvC,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,KAAK,CAAC;AACrC,MAAM,CAAC,MAAM,cAAc,GAAG,CAAC,KAAK,CAAC;AAErC,gEAAgE;AAChE,gBAAgB;AAChB,MAAM,CAAC,MAAM,wBAAwB,GAAG,CAAC,KAAK,CAAC"} \ No newline at end of file diff --git a/dist/esm/types.d.ts b/dist/esm/types.d.ts deleted file mode 100644 index 3864800a99..0000000000 --- a/dist/esm/types.d.ts +++ /dev/null @@ -1,4390 +0,0 @@ -import * as z from 'zod/v4'; -import { AuthInfo } from './server/auth/types.js'; -export declare const LATEST_PROTOCOL_VERSION = "2025-06-18"; -export declare const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; -export declare const SUPPORTED_PROTOCOL_VERSIONS: string[]; -export declare const JSONRPC_VERSION = "2.0"; -/** - * Utility types - */ -type ExpandRecursively = T extends object ? (T extends infer O ? { - [K in keyof O]: ExpandRecursively; -} : never) : T; -/** - * A progress token, used to associate progress notifications with the original request. - */ -export declare const ProgressTokenSchema: z.ZodUnion; -/** - * An opaque token used to represent a cursor for pagination. - */ -export declare const CursorSchema: z.ZodString; -declare const RequestMetaSchema: z.ZodObject<{ - /** - * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. - */ - progressToken: z.ZodOptional>; -}, z.core.$loose>; -/** - * Common params for any request. - */ -declare const BaseRequestParamsSchema: z.ZodObject<{ - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta: z.ZodOptional>; - }, z.core.$loose>>; -}, z.core.$loose>; -export declare const RequestSchema: z.ZodObject<{ - method: z.ZodString; - params: z.ZodOptional>; - }, z.core.$loose>>; - }, z.core.$loose>>; -}, z.core.$strip>; -declare const NotificationsParamsSchema: z.ZodObject<{ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.ZodOptional>; -}, z.core.$loose>; -export declare const NotificationSchema: z.ZodObject<{ - method: z.ZodString; - params: z.ZodOptional>; - }, z.core.$loose>>; -}, z.core.$strip>; -export declare const ResultSchema: z.ZodObject<{ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.ZodOptional>; -}, z.core.$loose>; -/** - * A uniquely identifying ID for a request in JSON-RPC. - */ -export declare const RequestIdSchema: z.ZodUnion; -/** - * A request that expects a response. - */ -export declare const JSONRPCRequestSchema: z.ZodObject<{ - method: z.ZodString; - params: z.ZodOptional>; - }, z.core.$loose>>; - }, z.core.$loose>>; - jsonrpc: z.ZodLiteral<"2.0">; - id: z.ZodUnion; -}, z.core.$strict>; -export declare const isJSONRPCRequest: (value: unknown) => value is JSONRPCRequest; -/** - * A notification which does not expect a response. - */ -export declare const JSONRPCNotificationSchema: z.ZodObject<{ - method: z.ZodString; - params: z.ZodOptional>; - }, z.core.$loose>>; - jsonrpc: z.ZodLiteral<"2.0">; -}, z.core.$strict>; -export declare const isJSONRPCNotification: (value: unknown) => value is JSONRPCNotification; -/** - * A successful (non-error) response to a request. - */ -export declare const JSONRPCResponseSchema: z.ZodObject<{ - jsonrpc: z.ZodLiteral<"2.0">; - id: z.ZodUnion; - result: z.ZodObject<{ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.ZodOptional>; - }, z.core.$loose>; -}, z.core.$strict>; -export declare const isJSONRPCResponse: (value: unknown) => value is JSONRPCResponse; -/** - * Error codes defined by the JSON-RPC specification. - */ -export declare enum ErrorCode { - ConnectionClosed = -32000, - RequestTimeout = -32001, - ParseError = -32700, - InvalidRequest = -32600, - MethodNotFound = -32601, - InvalidParams = -32602, - InternalError = -32603, - UrlElicitationRequired = -32042 -} -/** - * A response to a request that indicates an error occurred. - */ -export declare const JSONRPCErrorSchema: z.ZodObject<{ - jsonrpc: z.ZodLiteral<"2.0">; - id: z.ZodUnion; - error: z.ZodObject<{ - code: z.ZodNumber; - message: z.ZodString; - data: z.ZodOptional; - }, z.core.$strip>; -}, z.core.$strict>; -export declare const isJSONRPCError: (value: unknown) => value is JSONRPCError; -export declare const JSONRPCMessageSchema: z.ZodUnion>; - }, z.core.$loose>>; - }, z.core.$loose>>; - jsonrpc: z.ZodLiteral<"2.0">; - id: z.ZodUnion; -}, z.core.$strict>, z.ZodObject<{ - method: z.ZodString; - params: z.ZodOptional>; - }, z.core.$loose>>; - jsonrpc: z.ZodLiteral<"2.0">; -}, z.core.$strict>, z.ZodObject<{ - jsonrpc: z.ZodLiteral<"2.0">; - id: z.ZodUnion; - result: z.ZodObject<{ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.ZodOptional>; - }, z.core.$loose>; -}, z.core.$strict>, z.ZodObject<{ - jsonrpc: z.ZodLiteral<"2.0">; - id: z.ZodUnion; - error: z.ZodObject<{ - code: z.ZodNumber; - message: z.ZodString; - data: z.ZodOptional; - }, z.core.$strip>; -}, z.core.$strict>]>; -/** - * A response that indicates success but carries no data. - */ -export declare const EmptyResultSchema: z.ZodObject<{ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.ZodOptional>; -}, z.core.$strict>; -export declare const CancelledNotificationParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - requestId: z.ZodUnion; - reason: z.ZodOptional; -}, z.core.$loose>; -/** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its `initialize` request. - */ -export declare const CancelledNotificationSchema: z.ZodObject<{ - method: z.ZodLiteral<"notifications/cancelled">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - requestId: z.ZodUnion; - reason: z.ZodOptional; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * Icon schema for use in tools, prompts, resources, and implementations. - */ -export declare const IconSchema: z.ZodObject<{ - src: z.ZodString; - mimeType: z.ZodOptional; - sizes: z.ZodOptional>; -}, z.core.$strip>; -/** - * Base schema to add `icons` property. - * - */ -export declare const IconsSchema: z.ZodObject<{ - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; -}, z.core.$strip>; -/** - * Base metadata interface for common properties across resources, tools, prompts, and implementations. - */ -export declare const BaseMetadataSchema: z.ZodObject<{ - name: z.ZodString; - title: z.ZodOptional; -}, z.core.$strip>; -/** - * Describes the name and version of an MCP implementation. - */ -export declare const ImplementationSchema: z.ZodObject<{ - version: z.ZodString; - websiteUrl: z.ZodOptional; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; -}, z.core.$strip>; -/** - * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. - */ -export declare const ClientCapabilitiesSchema: z.ZodObject<{ - experimental: z.ZodOptional>>; - sampling: z.ZodOptional>; - tools: z.ZodOptional>; - }, z.core.$strip>>; - elicitation: z.ZodOptional, z.ZodIntersection; - }, z.core.$strip>, z.ZodRecord>>; - url: z.ZodOptional>; - }, z.core.$strip>, z.ZodOptional>>>>; - roots: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$strip>; -export declare const InitializeRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - protocolVersion: z.ZodString; - capabilities: z.ZodObject<{ - experimental: z.ZodOptional>>; - sampling: z.ZodOptional>; - tools: z.ZodOptional>; - }, z.core.$strip>>; - elicitation: z.ZodOptional, z.ZodIntersection; - }, z.core.$strip>, z.ZodRecord>>; - url: z.ZodOptional>; - }, z.core.$strip>, z.ZodOptional>>>>; - roots: z.ZodOptional; - }, z.core.$strip>>; - }, z.core.$strip>; - clientInfo: z.ZodObject<{ - version: z.ZodString; - websiteUrl: z.ZodOptional; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>; -}, z.core.$loose>; -/** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - */ -export declare const InitializeRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"initialize">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - protocolVersion: z.ZodString; - capabilities: z.ZodObject<{ - experimental: z.ZodOptional>>; - sampling: z.ZodOptional>; - tools: z.ZodOptional>; - }, z.core.$strip>>; - elicitation: z.ZodOptional, z.ZodIntersection; - }, z.core.$strip>, z.ZodRecord>>; - url: z.ZodOptional>; - }, z.core.$strip>, z.ZodOptional>>>>; - roots: z.ZodOptional; - }, z.core.$strip>>; - }, z.core.$strip>; - clientInfo: z.ZodObject<{ - version: z.ZodString; - websiteUrl: z.ZodOptional; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>; - }, z.core.$loose>; -}, z.core.$strip>; -export declare const isInitializeRequest: (value: unknown) => value is InitializeRequest; -/** - * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. - */ -export declare const ServerCapabilitiesSchema: z.ZodObject<{ - experimental: z.ZodOptional>>; - logging: z.ZodOptional>; - completions: z.ZodOptional>; - prompts: z.ZodOptional; - }, z.core.$strip>>; - resources: z.ZodOptional; - listChanged: z.ZodOptional; - }, z.core.$strip>>; - tools: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$strip>; -/** - * After receiving an initialize request from the client, the server sends this response. - */ -export declare const InitializeResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - protocolVersion: z.ZodString; - capabilities: z.ZodObject<{ - experimental: z.ZodOptional>>; - logging: z.ZodOptional>; - completions: z.ZodOptional>; - prompts: z.ZodOptional; - }, z.core.$strip>>; - resources: z.ZodOptional; - listChanged: z.ZodOptional; - }, z.core.$strip>>; - tools: z.ZodOptional; - }, z.core.$strip>>; - }, z.core.$strip>; - serverInfo: z.ZodObject<{ - version: z.ZodString; - websiteUrl: z.ZodOptional; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>; - instructions: z.ZodOptional; -}, z.core.$loose>; -/** - * This notification is sent from the client to the server after initialization has finished. - */ -export declare const InitializedNotificationSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/initialized">; -}, z.core.$strip>; -export declare const isInitializedNotification: (value: unknown) => value is InitializedNotification; -/** - * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. - */ -export declare const PingRequestSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - }, z.core.$loose>>; - method: z.ZodLiteral<"ping">; -}, z.core.$strip>; -export declare const ProgressSchema: z.ZodObject<{ - progress: z.ZodNumber; - total: z.ZodOptional; - message: z.ZodOptional; -}, z.core.$strip>; -export declare const ProgressNotificationParamsSchema: z.ZodObject<{ - progressToken: z.ZodUnion; - progress: z.ZodNumber; - total: z.ZodOptional; - message: z.ZodOptional; - _meta: z.ZodOptional>; -}, z.core.$strip>; -/** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - * - * @category notifications/progress - */ -export declare const ProgressNotificationSchema: z.ZodObject<{ - method: z.ZodLiteral<"notifications/progress">; - params: z.ZodObject<{ - progressToken: z.ZodUnion; - progress: z.ZodNumber; - total: z.ZodOptional; - message: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$strip>; -}, z.core.$strip>; -export declare const PaginatedRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; -}, z.core.$loose>; -export declare const PaginatedRequestSchema: z.ZodObject<{ - method: z.ZodString; - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; -}, z.core.$strip>; -export declare const PaginatedResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; -}, z.core.$loose>; -/** - * The contents of a specific resource or sub-resource. - */ -export declare const ResourceContentsSchema: z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; -}, z.core.$strip>; -export declare const TextResourceContentsSchema: z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - text: z.ZodString; -}, z.core.$strip>; -export declare const BlobResourceContentsSchema: z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; -}, z.core.$strip>; -/** - * A known resource that the server is capable of reading. - */ -export declare const ResourceSchema: z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; -}, z.core.$strip>; -/** - * A template description for resources available on the server. - */ -export declare const ResourceTemplateSchema: z.ZodObject<{ - uriTemplate: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; -}, z.core.$strip>; -/** - * Sent from the client to request a list of resources the server has. - */ -export declare const ListResourcesRequestSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"resources/list">; -}, z.core.$strip>; -/** - * The server's response to a resources/list request from the client. - */ -export declare const ListResourcesResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - resources: z.ZodArray; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>; -/** - * Sent from the client to request a list of resource templates the server has. - */ -export declare const ListResourceTemplatesRequestSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"resources/templates/list">; -}, z.core.$strip>; -/** - * The server's response to a resources/templates/list request from the client. - */ -export declare const ListResourceTemplatesResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - resourceTemplates: z.ZodArray; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>; -export declare const ResourceRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; -}, z.core.$loose>; -/** - * Parameters for a `resources/read` request. - */ -export declare const ReadResourceRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; -}, z.core.$loose>; -/** - * Sent from the client to the server, to read a specific resource URI. - */ -export declare const ReadResourceRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"resources/read">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * The server's response to a resources/read request from the client. - */ -export declare const ReadResourceResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - contents: z.ZodArray; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>>; -}, z.core.$loose>; -/** - * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. - */ -export declare const ResourceListChangedNotificationSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/resources/list_changed">; -}, z.core.$strip>; -export declare const SubscribeRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; -}, z.core.$loose>; -/** - * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. - */ -export declare const SubscribeRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"resources/subscribe">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>; -export declare const UnsubscribeRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; -}, z.core.$loose>; -/** - * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. - */ -export declare const UnsubscribeRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"resources/unsubscribe">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * Parameters for a `notifications/resources/updated` notification. - */ -export declare const ResourceUpdatedNotificationParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - uri: z.ZodString; -}, z.core.$loose>; -/** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. - */ -export declare const ResourceUpdatedNotificationSchema: z.ZodObject<{ - method: z.ZodLiteral<"notifications/resources/updated">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * Describes an argument that a prompt can accept. - */ -export declare const PromptArgumentSchema: z.ZodObject<{ - name: z.ZodString; - description: z.ZodOptional; - required: z.ZodOptional; -}, z.core.$strip>; -/** - * A prompt or prompt template that the server offers. - */ -export declare const PromptSchema: z.ZodObject<{ - description: z.ZodOptional; - arguments: z.ZodOptional; - required: z.ZodOptional; - }, z.core.$strip>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; -}, z.core.$strip>; -/** - * Sent from the client to request a list of prompts and prompt templates the server has. - */ -export declare const ListPromptsRequestSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"prompts/list">; -}, z.core.$strip>; -/** - * The server's response to a prompts/list request from the client. - */ -export declare const ListPromptsResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - prompts: z.ZodArray; - arguments: z.ZodOptional; - required: z.ZodOptional; - }, z.core.$strip>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>; -/** - * Parameters for a `prompts/get` request. - */ -export declare const GetPromptRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - name: z.ZodString; - arguments: z.ZodOptional>; -}, z.core.$loose>; -/** - * Used by the client to get a prompt provided by the server. - */ -export declare const GetPromptRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"prompts/get">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - name: z.ZodString; - arguments: z.ZodOptional>; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * Text provided to or from an LLM. - */ -export declare const TextContentSchema: z.ZodObject<{ - type: z.ZodLiteral<"text">; - text: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>; -/** - * An image provided to or from an LLM. - */ -export declare const ImageContentSchema: z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>; -/** - * An Audio provided to or from an LLM. - */ -export declare const AudioContentSchema: z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>; -/** - * A tool call request from an assistant (LLM). - * Represents the assistant's request to use a tool. - */ -export declare const ToolUseContentSchema: z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; -}, z.core.$loose>; -/** - * The contents of a resource, embedded into a prompt or tool call result. - */ -export declare const EmbeddedResourceSchema: z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; -}, z.core.$strip>; -/** - * A resource that the server is capable of reading, included in a prompt or tool call result. - * - * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. - */ -export declare const ResourceLinkSchema: z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; -}, z.core.$strip>; -/** - * A content block that can be used in prompts and tool results. - */ -export declare const ContentBlockSchema: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; -}, z.core.$strip>]>; -/** - * Describes a message returned as part of a prompt. - */ -export declare const PromptMessageSchema: z.ZodObject<{ - role: z.ZodEnum<{ - user: "user"; - assistant: "assistant"; - }>; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>; -}, z.core.$strip>; -/** - * The server's response to a prompts/get request from the client. - */ -export declare const GetPromptResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - description: z.ZodOptional; - messages: z.ZodArray; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>; - }, z.core.$strip>>; -}, z.core.$loose>; -/** - * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. - */ -export declare const PromptListChangedNotificationSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/prompts/list_changed">; -}, z.core.$strip>; -/** - * Security scheme indicating no authentication is required. - */ -export declare const NoAuthSecuritySchemeSchema: z.ZodObject<{ - type: z.ZodLiteral<"noauth">; -}, z.core.$strip>; -/** - * Security scheme indicating OAuth 2.0 authentication is required. - */ -export declare const OAuth2SecuritySchemeSchema: z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; -}, z.core.$strip>; -/** - * A security scheme that can be used to authenticate tool calls. - */ -export declare const SecuritySchemeSchema: z.ZodUnion; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; -}, z.core.$strip>]>; -/** - * Additional properties describing a Tool to clients. - * - * NOTE: all properties in ToolAnnotations are **hints**. - * They are not guaranteed to provide a faithful description of - * tool behavior (including descriptive properties like `title`). - * - * Clients should never make tool use decisions based on ToolAnnotations - * received from untrusted servers. - */ -export declare const ToolAnnotationsSchema: z.ZodObject<{ - title: z.ZodOptional; - readOnlyHint: z.ZodOptional; - destructiveHint: z.ZodOptional; - idempotentHint: z.ZodOptional; - openWorldHint: z.ZodOptional; -}, z.core.$strip>; -/** - * Definition for a tool the client can call. - */ -export declare const ToolSchema: z.ZodObject<{ - description: z.ZodOptional; - inputSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>; - outputSchema: z.ZodOptional; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>>; - annotations: z.ZodOptional; - readOnlyHint: z.ZodOptional; - destructiveHint: z.ZodOptional; - idempotentHint: z.ZodOptional; - openWorldHint: z.ZodOptional; - }, z.core.$strip>>; - securitySchemes: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; - }, z.core.$strip>]>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; -}, z.core.$strip>; -/** - * Sent from the client to request a list of tools the server has. - */ -export declare const ListToolsRequestSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"tools/list">; -}, z.core.$strip>; -/** - * The server's response to a tools/list request from the client. - */ -export declare const ListToolsResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - tools: z.ZodArray; - inputSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>; - outputSchema: z.ZodOptional; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>>; - annotations: z.ZodOptional; - readOnlyHint: z.ZodOptional; - destructiveHint: z.ZodOptional; - idempotentHint: z.ZodOptional; - openWorldHint: z.ZodOptional; - }, z.core.$strip>>; - securitySchemes: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; - }, z.core.$strip>]>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>; -/** - * The server's response to a tool call. - */ -export declare const CallToolResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; -}, z.core.$loose>; -/** - * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. - */ -export declare const CompatibilityCallToolResultSchema: z.ZodUnion<[z.ZodObject<{ - _meta: z.ZodOptional>; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - toolResult: z.ZodUnknown; -}, z.core.$loose>]>; -/** - * Parameters for a `tools/call` request. - */ -export declare const CallToolRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - name: z.ZodString; - arguments: z.ZodOptional>; -}, z.core.$loose>; -/** - * Used by the client to invoke a tool provided by the server. - */ -export declare const CallToolRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"tools/call">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - name: z.ZodString; - arguments: z.ZodOptional>; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. - */ -export declare const ToolListChangedNotificationSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/tools/list_changed">; -}, z.core.$strip>; -/** - * The severity of a log message. - */ -export declare const LoggingLevelSchema: z.ZodEnum<{ - error: "error"; - debug: "debug"; - info: "info"; - notice: "notice"; - warning: "warning"; - critical: "critical"; - alert: "alert"; - emergency: "emergency"; -}>; -/** - * Parameters for a `logging/setLevel` request. - */ -export declare const SetLevelRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - level: z.ZodEnum<{ - error: "error"; - debug: "debug"; - info: "info"; - notice: "notice"; - warning: "warning"; - critical: "critical"; - alert: "alert"; - emergency: "emergency"; - }>; -}, z.core.$loose>; -/** - * A request from the client to the server, to enable or adjust logging. - */ -export declare const SetLevelRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"logging/setLevel">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - level: z.ZodEnum<{ - error: "error"; - debug: "debug"; - info: "info"; - notice: "notice"; - warning: "warning"; - critical: "critical"; - alert: "alert"; - emergency: "emergency"; - }>; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * Parameters for a `notifications/message` notification. - */ -export declare const LoggingMessageNotificationParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - level: z.ZodEnum<{ - error: "error"; - debug: "debug"; - info: "info"; - notice: "notice"; - warning: "warning"; - critical: "critical"; - alert: "alert"; - emergency: "emergency"; - }>; - logger: z.ZodOptional; - data: z.ZodUnknown; -}, z.core.$loose>; -/** - * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. - */ -export declare const LoggingMessageNotificationSchema: z.ZodObject<{ - method: z.ZodLiteral<"notifications/message">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - level: z.ZodEnum<{ - error: "error"; - debug: "debug"; - info: "info"; - notice: "notice"; - warning: "warning"; - critical: "critical"; - alert: "alert"; - emergency: "emergency"; - }>; - logger: z.ZodOptional; - data: z.ZodUnknown; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * Hints to use for model selection. - */ -export declare const ModelHintSchema: z.ZodObject<{ - name: z.ZodOptional; -}, z.core.$strip>; -/** - * The server's preferences for model selection, requested of the client during sampling. - */ -export declare const ModelPreferencesSchema: z.ZodObject<{ - hints: z.ZodOptional; - }, z.core.$strip>>>; - costPriority: z.ZodOptional; - speedPriority: z.ZodOptional; - intelligencePriority: z.ZodOptional; -}, z.core.$strip>; -/** - * Controls tool usage behavior in sampling requests. - */ -export declare const ToolChoiceSchema: z.ZodObject<{ - mode: z.ZodOptional>; -}, z.core.$strip>; -/** - * The result of a tool execution, provided by the user (server). - * Represents the outcome of invoking a tool requested via ToolUseContent. - */ -export declare const ToolResultContentSchema: z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; -}, z.core.$loose>; -/** - * Content block types allowed in sampling messages. - * This includes text, image, audio, tool use requests, and tool results. - */ -export declare const SamplingMessageContentBlockSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ - type: z.ZodLiteral<"text">; - text: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; -}, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; -}, z.core.$loose>]>; -/** - * Describes a message issued to or received from an LLM API. - */ -export declare const SamplingMessageSchema: z.ZodObject<{ - role: z.ZodEnum<{ - user: "user"; - assistant: "assistant"; - }>; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>, z.ZodArray; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>>]>; - _meta: z.ZodOptional>; -}, z.core.$loose>; -/** - * Parameters for a `sampling/createMessage` request. - */ -export declare const CreateMessageRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - messages: z.ZodArray; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>, z.ZodArray; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>>]>; - _meta: z.ZodOptional>; - }, z.core.$loose>>; - modelPreferences: z.ZodOptional; - }, z.core.$strip>>>; - costPriority: z.ZodOptional; - speedPriority: z.ZodOptional; - intelligencePriority: z.ZodOptional; - }, z.core.$strip>>; - systemPrompt: z.ZodOptional; - includeContext: z.ZodOptional>; - temperature: z.ZodOptional; - maxTokens: z.ZodNumber; - stopSequences: z.ZodOptional>; - metadata: z.ZodOptional>; - tools: z.ZodOptional; - inputSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>; - outputSchema: z.ZodOptional; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>>; - annotations: z.ZodOptional; - readOnlyHint: z.ZodOptional; - destructiveHint: z.ZodOptional; - idempotentHint: z.ZodOptional; - openWorldHint: z.ZodOptional; - }, z.core.$strip>>; - securitySchemes: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; - }, z.core.$strip>]>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>>; - toolChoice: z.ZodOptional>; - }, z.core.$strip>>; -}, z.core.$loose>; -/** - * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. - */ -export declare const CreateMessageRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"sampling/createMessage">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - messages: z.ZodArray; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>, z.ZodArray; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>>]>; - _meta: z.ZodOptional>; - }, z.core.$loose>>; - modelPreferences: z.ZodOptional; - }, z.core.$strip>>>; - costPriority: z.ZodOptional; - speedPriority: z.ZodOptional; - intelligencePriority: z.ZodOptional; - }, z.core.$strip>>; - systemPrompt: z.ZodOptional; - includeContext: z.ZodOptional>; - temperature: z.ZodOptional; - maxTokens: z.ZodNumber; - stopSequences: z.ZodOptional>; - metadata: z.ZodOptional>; - tools: z.ZodOptional; - inputSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>; - outputSchema: z.ZodOptional; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>>; - annotations: z.ZodOptional; - readOnlyHint: z.ZodOptional; - destructiveHint: z.ZodOptional; - idempotentHint: z.ZodOptional; - openWorldHint: z.ZodOptional; - }, z.core.$strip>>; - securitySchemes: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; - }, z.core.$strip>]>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>>; - toolChoice: z.ZodOptional>; - }, z.core.$strip>>; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. - */ -export declare const CreateMessageResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - model: z.ZodString; - stopReason: z.ZodOptional, z.ZodString]>>; - role: z.ZodEnum<{ - user: "user"; - assistant: "assistant"; - }>; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>, z.ZodArray; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>>]>; -}, z.core.$loose>; -/** - * Primitive schema definition for boolean fields. - */ -export declare const BooleanSchemaSchema: z.ZodObject<{ - type: z.ZodLiteral<"boolean">; - title: z.ZodOptional; - description: z.ZodOptional; - default: z.ZodOptional; -}, z.core.$strip>; -/** - * Primitive schema definition for string fields. - */ -export declare const StringSchemaSchema: z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - minLength: z.ZodOptional; - maxLength: z.ZodOptional; - format: z.ZodOptional>; - default: z.ZodOptional; -}, z.core.$strip>; -/** - * Primitive schema definition for number fields. - */ -export declare const NumberSchemaSchema: z.ZodObject<{ - type: z.ZodEnum<{ - number: "number"; - integer: "integer"; - }>; - title: z.ZodOptional; - description: z.ZodOptional; - minimum: z.ZodOptional; - maximum: z.ZodOptional; - default: z.ZodOptional; -}, z.core.$strip>; -/** - * Schema for single-selection enumeration without display titles for options. - */ -export declare const UntitledSingleSelectEnumSchemaSchema: z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; -}, z.core.$strip>; -/** - * Schema for single-selection enumeration with display titles for each option. - */ -export declare const TitledSingleSelectEnumSchemaSchema: z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; -}, z.core.$strip>; -/** - * Use TitledSingleSelectEnumSchema instead. - * This interface will be removed in a future version. - */ -export declare const LegacyTitledEnumSchemaSchema: z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - enumNames: z.ZodOptional>; - default: z.ZodOptional; -}, z.core.$strip>; -export declare const SingleSelectEnumSchemaSchema: z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; -}, z.core.$strip>]>; -/** - * Schema for multiple-selection enumeration without display titles for options. - */ -export declare const UntitledMultiSelectEnumSchemaSchema: z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>; -/** - * Schema for multiple-selection enumeration with display titles for each option. - */ -export declare const TitledMultiSelectEnumSchemaSchema: z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>; -/** - * Combined schema for multiple-selection enumeration - */ -export declare const MultiSelectEnumSchemaSchema: z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>]>; -/** - * Primitive schema definition for enum fields. - */ -export declare const EnumSchemaSchema: z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - enumNames: z.ZodOptional>; - default: z.ZodOptional; -}, z.core.$strip>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; -}, z.core.$strip>]>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>]>]>; -/** - * Union of all primitive schema definitions. - */ -export declare const PrimitiveSchemaDefinitionSchema: z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - enumNames: z.ZodOptional>; - default: z.ZodOptional; -}, z.core.$strip>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; -}, z.core.$strip>]>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; -}, z.core.$strip>]>]>, z.ZodObject<{ - type: z.ZodLiteral<"boolean">; - title: z.ZodOptional; - description: z.ZodOptional; - default: z.ZodOptional; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - minLength: z.ZodOptional; - maxLength: z.ZodOptional; - format: z.ZodOptional>; - default: z.ZodOptional; -}, z.core.$strip>, z.ZodObject<{ - type: z.ZodEnum<{ - number: "number"; - integer: "integer"; - }>; - title: z.ZodOptional; - description: z.ZodOptional; - minimum: z.ZodOptional; - maximum: z.ZodOptional; - default: z.ZodOptional; -}, z.core.$strip>]>; -/** - * Parameters for an `elicitation/create` request for form-based elicitation. - */ -export declare const ElicitRequestFormParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"form">; - message: z.ZodString; - requestedSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodRecord; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - enumNames: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; - }, z.core.$strip>]>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>]>]>, z.ZodObject<{ - type: z.ZodLiteral<"boolean">; - title: z.ZodOptional; - description: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - minLength: z.ZodOptional; - maxLength: z.ZodOptional; - format: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodEnum<{ - number: "number"; - integer: "integer"; - }>; - title: z.ZodOptional; - description: z.ZodOptional; - minimum: z.ZodOptional; - maximum: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>]>>; - required: z.ZodOptional>; - }, z.core.$strip>; -}, z.core.$loose>; -/** - * Parameters for an `elicitation/create` request for URL-based elicitation. - */ -export declare const ElicitRequestURLParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"url">; - message: z.ZodString; - elicitationId: z.ZodString; - url: z.ZodString; -}, z.core.$loose>; -/** - * The parameters for a request to elicit additional information from the user via the client. - */ -export declare const ElicitRequestParamsSchema: z.ZodUnion>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"form">; - message: z.ZodString; - requestedSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodRecord; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - enumNames: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; - }, z.core.$strip>]>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>]>]>, z.ZodObject<{ - type: z.ZodLiteral<"boolean">; - title: z.ZodOptional; - description: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - minLength: z.ZodOptional; - maxLength: z.ZodOptional; - format: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodEnum<{ - number: "number"; - integer: "integer"; - }>; - title: z.ZodOptional; - description: z.ZodOptional; - minimum: z.ZodOptional; - maximum: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>]>>; - required: z.ZodOptional>; - }, z.core.$strip>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"url">; - message: z.ZodString; - elicitationId: z.ZodString; - url: z.ZodString; -}, z.core.$loose>]>; -/** - * A request from the server to elicit user input via the client. - * The client should present the message and form fields to the user (form mode) - * or navigate to a URL (URL mode). - */ -export declare const ElicitRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"elicitation/create">; - params: z.ZodUnion>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"form">; - message: z.ZodString; - requestedSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodRecord; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - enumNames: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; - }, z.core.$strip>]>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>]>]>, z.ZodObject<{ - type: z.ZodLiteral<"boolean">; - title: z.ZodOptional; - description: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - minLength: z.ZodOptional; - maxLength: z.ZodOptional; - format: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodEnum<{ - number: "number"; - integer: "integer"; - }>; - title: z.ZodOptional; - description: z.ZodOptional; - minimum: z.ZodOptional; - maximum: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>]>>; - required: z.ZodOptional>; - }, z.core.$strip>; - }, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"url">; - message: z.ZodString; - elicitationId: z.ZodString; - url: z.ZodString; - }, z.core.$loose>]>; -}, z.core.$strip>; -/** - * Parameters for a `notifications/elicitation/complete` notification. - * - * @category notifications/elicitation/complete - */ -export declare const ElicitationCompleteNotificationParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - elicitationId: z.ZodString; -}, z.core.$loose>; -/** - * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. - * - * @category notifications/elicitation/complete - */ -export declare const ElicitationCompleteNotificationSchema: z.ZodObject<{ - method: z.ZodLiteral<"notifications/elicitation/complete">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - elicitationId: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>; -/** - * The client's response to an elicitation/create request from the server. - */ -export declare const ElicitResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - action: z.ZodEnum<{ - accept: "accept"; - decline: "decline"; - cancel: "cancel"; - }>; - content: z.ZodOptional]>>>; -}, z.core.$loose>; -/** - * A reference to a resource or resource template definition. - */ -export declare const ResourceTemplateReferenceSchema: z.ZodObject<{ - type: z.ZodLiteral<"ref/resource">; - uri: z.ZodString; -}, z.core.$strip>; -/** - * @deprecated Use ResourceTemplateReferenceSchema instead - */ -export declare const ResourceReferenceSchema: z.ZodObject<{ - type: z.ZodLiteral<"ref/resource">; - uri: z.ZodString; -}, z.core.$strip>; -/** - * Identifies a prompt. - */ -export declare const PromptReferenceSchema: z.ZodObject<{ - type: z.ZodLiteral<"ref/prompt">; - name: z.ZodString; -}, z.core.$strip>; -/** - * Parameters for a `completion/complete` request. - */ -export declare const CompleteRequestParamsSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - ref: z.ZodUnion; - name: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"ref/resource">; - uri: z.ZodString; - }, z.core.$strip>]>; - argument: z.ZodObject<{ - name: z.ZodString; - value: z.ZodString; - }, z.core.$strip>; - context: z.ZodOptional>; - }, z.core.$strip>>; -}, z.core.$loose>; -/** - * A request from the client to the server, to ask for completion options. - */ -export declare const CompleteRequestSchema: z.ZodObject<{ - method: z.ZodLiteral<"completion/complete">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - ref: z.ZodUnion; - name: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"ref/resource">; - uri: z.ZodString; - }, z.core.$strip>]>; - argument: z.ZodObject<{ - name: z.ZodString; - value: z.ZodString; - }, z.core.$strip>; - context: z.ZodOptional>; - }, z.core.$strip>>; - }, z.core.$loose>; -}, z.core.$strip>; -export declare function assertCompleteRequestPrompt(request: CompleteRequest): asserts request is CompleteRequestPrompt; -export declare function assertCompleteRequestResourceTemplate(request: CompleteRequest): asserts request is CompleteRequestResourceTemplate; -/** - * The server's response to a completion/complete request - */ -export declare const CompleteResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - completion: z.ZodObject<{ - /** - * An array of completion values. Must not exceed 100 items. - */ - values: z.ZodArray; - /** - * The total number of completion options available. This can exceed the number of values actually sent in the response. - */ - total: z.ZodOptional; - /** - * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. - */ - hasMore: z.ZodOptional; - }, z.core.$loose>; -}, z.core.$loose>; -/** - * Represents a root directory or file that the server can operate on. - */ -export declare const RootSchema: z.ZodObject<{ - uri: z.ZodString; - name: z.ZodOptional; - _meta: z.ZodOptional>; -}, z.core.$strip>; -/** - * Sent from the server to request a list of root URIs from the client. - */ -export declare const ListRootsRequestSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - }, z.core.$loose>>; - method: z.ZodLiteral<"roots/list">; -}, z.core.$strip>; -/** - * The client's response to a roots/list request from the server. - */ -export declare const ListRootsResultSchema: z.ZodObject<{ - _meta: z.ZodOptional>; - roots: z.ZodArray; - _meta: z.ZodOptional>; - }, z.core.$strip>>; -}, z.core.$loose>; -/** - * A notification from the client to the server, informing it that the list of roots has changed. - */ -export declare const RootsListChangedNotificationSchema: z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/roots/list_changed">; -}, z.core.$strip>; -export declare const ClientRequestSchema: z.ZodUnion>; - }, z.core.$loose>>; - }, z.core.$loose>>; - method: z.ZodLiteral<"ping">; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"initialize">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - protocolVersion: z.ZodString; - capabilities: z.ZodObject<{ - experimental: z.ZodOptional>>; - sampling: z.ZodOptional>; - tools: z.ZodOptional>; - }, z.core.$strip>>; - elicitation: z.ZodOptional, z.ZodIntersection; - }, z.core.$strip>, z.ZodRecord>>; - url: z.ZodOptional>; - }, z.core.$strip>, z.ZodOptional>>>>; - roots: z.ZodOptional; - }, z.core.$strip>>; - }, z.core.$strip>; - clientInfo: z.ZodObject<{ - version: z.ZodString; - websiteUrl: z.ZodOptional; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"completion/complete">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - ref: z.ZodUnion; - name: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"ref/resource">; - uri: z.ZodString; - }, z.core.$strip>]>; - argument: z.ZodObject<{ - name: z.ZodString; - value: z.ZodString; - }, z.core.$strip>; - context: z.ZodOptional>; - }, z.core.$strip>>; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"logging/setLevel">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - level: z.ZodEnum<{ - error: "error"; - debug: "debug"; - info: "info"; - notice: "notice"; - warning: "warning"; - critical: "critical"; - alert: "alert"; - emergency: "emergency"; - }>; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"prompts/get">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - name: z.ZodString; - arguments: z.ZodOptional>; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"prompts/list">; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"resources/list">; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"resources/templates/list">; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"resources/read">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"resources/subscribe">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"resources/unsubscribe">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"tools/call">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - name: z.ZodString; - arguments: z.ZodOptional>; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - cursor: z.ZodOptional; - }, z.core.$loose>>; - method: z.ZodLiteral<"tools/list">; -}, z.core.$strip>]>; -export declare const ClientNotificationSchema: z.ZodUnion; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - requestId: z.ZodUnion; - reason: z.ZodOptional; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"notifications/progress">; - params: z.ZodObject<{ - progressToken: z.ZodUnion; - progress: z.ZodNumber; - total: z.ZodOptional; - message: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$strip>; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/initialized">; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/roots/list_changed">; -}, z.core.$strip>]>; -export declare const ClientResultSchema: z.ZodUnion>; -}, z.core.$strict>, z.ZodObject<{ - _meta: z.ZodOptional>; - model: z.ZodString; - stopReason: z.ZodOptional, z.ZodString]>>; - role: z.ZodEnum<{ - user: "user"; - assistant: "assistant"; - }>; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>, z.ZodArray; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>>]>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - action: z.ZodEnum<{ - accept: "accept"; - decline: "decline"; - cancel: "cancel"; - }>; - content: z.ZodOptional]>>>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - roots: z.ZodArray; - _meta: z.ZodOptional>; - }, z.core.$strip>>; -}, z.core.$loose>]>; -export declare const ServerRequestSchema: z.ZodUnion>; - }, z.core.$loose>>; - }, z.core.$loose>>; - method: z.ZodLiteral<"ping">; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"sampling/createMessage">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - messages: z.ZodArray; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>, z.ZodArray; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"tool_use">; - name: z.ZodString; - id: z.ZodString; - input: z.ZodObject<{}, z.core.$loose>; - _meta: z.ZodOptional>; - }, z.core.$loose>, z.ZodObject<{ - type: z.ZodLiteral<"tool_result">; - toolUseId: z.ZodString; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$loose>]>>]>; - _meta: z.ZodOptional>; - }, z.core.$loose>>; - modelPreferences: z.ZodOptional; - }, z.core.$strip>>>; - costPriority: z.ZodOptional; - speedPriority: z.ZodOptional; - intelligencePriority: z.ZodOptional; - }, z.core.$strip>>; - systemPrompt: z.ZodOptional; - includeContext: z.ZodOptional>; - temperature: z.ZodOptional; - maxTokens: z.ZodNumber; - stopSequences: z.ZodOptional>; - metadata: z.ZodOptional>; - tools: z.ZodOptional; - inputSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>; - outputSchema: z.ZodOptional; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>>; - annotations: z.ZodOptional; - readOnlyHint: z.ZodOptional; - destructiveHint: z.ZodOptional; - idempotentHint: z.ZodOptional; - openWorldHint: z.ZodOptional; - }, z.core.$strip>>; - securitySchemes: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; - }, z.core.$strip>]>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>>; - toolChoice: z.ZodOptional>; - }, z.core.$strip>>; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"elicitation/create">; - params: z.ZodUnion>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"form">; - message: z.ZodString; - requestedSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodRecord; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - enumNames: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - enum: z.ZodArray; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - oneOf: z.ZodArray>; - default: z.ZodOptional; - }, z.core.$strip>]>, z.ZodUnion; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - type: z.ZodLiteral<"string">; - enum: z.ZodArray; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"array">; - title: z.ZodOptional; - description: z.ZodOptional; - minItems: z.ZodOptional; - maxItems: z.ZodOptional; - items: z.ZodObject<{ - anyOf: z.ZodArray>; - }, z.core.$strip>; - default: z.ZodOptional>; - }, z.core.$strip>]>]>, z.ZodObject<{ - type: z.ZodLiteral<"boolean">; - title: z.ZodOptional; - description: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"string">; - title: z.ZodOptional; - description: z.ZodOptional; - minLength: z.ZodOptional; - maxLength: z.ZodOptional; - format: z.ZodOptional>; - default: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodEnum<{ - number: "number"; - integer: "integer"; - }>; - title: z.ZodOptional; - description: z.ZodOptional; - minimum: z.ZodOptional; - maximum: z.ZodOptional; - default: z.ZodOptional; - }, z.core.$strip>]>>; - required: z.ZodOptional>; - }, z.core.$strip>; - }, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - }, z.core.$loose>>; - mode: z.ZodLiteral<"url">; - message: z.ZodString; - elicitationId: z.ZodString; - url: z.ZodString; - }, z.core.$loose>]>; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - }, z.core.$loose>>; - method: z.ZodLiteral<"roots/list">; -}, z.core.$strip>]>; -export declare const ServerNotificationSchema: z.ZodUnion; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - requestId: z.ZodUnion; - reason: z.ZodOptional; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"notifications/progress">; - params: z.ZodObject<{ - progressToken: z.ZodUnion; - progress: z.ZodNumber; - total: z.ZodOptional; - message: z.ZodOptional; - _meta: z.ZodOptional>; - }, z.core.$strip>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"notifications/message">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - level: z.ZodEnum<{ - error: "error"; - debug: "debug"; - info: "info"; - notice: "notice"; - warning: "warning"; - critical: "critical"; - alert: "alert"; - emergency: "emergency"; - }>; - logger: z.ZodOptional; - data: z.ZodUnknown; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"notifications/resources/updated">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - uri: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/resources/list_changed">; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/tools/list_changed">; -}, z.core.$strip>, z.ZodObject<{ - params: z.ZodOptional>; - }, z.core.$loose>>; - method: z.ZodLiteral<"notifications/prompts/list_changed">; -}, z.core.$strip>, z.ZodObject<{ - method: z.ZodLiteral<"notifications/elicitation/complete">; - params: z.ZodObject<{ - _meta: z.ZodOptional>; - elicitationId: z.ZodString; - }, z.core.$loose>; -}, z.core.$strip>]>; -export declare const ServerResultSchema: z.ZodUnion>; -}, z.core.$strict>, z.ZodObject<{ - _meta: z.ZodOptional>; - protocolVersion: z.ZodString; - capabilities: z.ZodObject<{ - experimental: z.ZodOptional>>; - logging: z.ZodOptional>; - completions: z.ZodOptional>; - prompts: z.ZodOptional; - }, z.core.$strip>>; - resources: z.ZodOptional; - listChanged: z.ZodOptional; - }, z.core.$strip>>; - tools: z.ZodOptional; - }, z.core.$strip>>; - }, z.core.$strip>; - serverInfo: z.ZodObject<{ - version: z.ZodString; - websiteUrl: z.ZodOptional; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>; - instructions: z.ZodOptional; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - completion: z.ZodObject<{ - /** - * An array of completion values. Must not exceed 100 items. - */ - values: z.ZodArray; - /** - * The total number of completion options available. This can exceed the number of values actually sent in the response. - */ - total: z.ZodOptional; - /** - * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. - */ - hasMore: z.ZodOptional; - }, z.core.$loose>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - description: z.ZodOptional; - messages: z.ZodArray; - content: z.ZodUnion; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>; - }, z.core.$strip>>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - prompts: z.ZodArray; - arguments: z.ZodOptional; - required: z.ZodOptional; - }, z.core.$strip>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - resources: z.ZodArray; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - resourceTemplates: z.ZodArray; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - contents: z.ZodArray; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>>; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - content: z.ZodDefault; - text: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"image">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"audio">; - data: z.ZodString; - mimeType: z.ZodString; - _meta: z.ZodOptional>; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - description: z.ZodOptional; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - type: z.ZodLiteral<"resource_link">; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"resource">; - resource: z.ZodUnion; - _meta: z.ZodOptional>; - text: z.ZodString; - }, z.core.$strip>, z.ZodObject<{ - uri: z.ZodString; - mimeType: z.ZodOptional; - _meta: z.ZodOptional>; - blob: z.ZodString; - }, z.core.$strip>]>; - _meta: z.ZodOptional>; - }, z.core.$strip>]>>>; - structuredContent: z.ZodOptional>; - isError: z.ZodOptional; -}, z.core.$loose>, z.ZodObject<{ - _meta: z.ZodOptional>; - nextCursor: z.ZodOptional; - tools: z.ZodArray; - inputSchema: z.ZodObject<{ - type: z.ZodLiteral<"object">; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>; - outputSchema: z.ZodOptional; - properties: z.ZodOptional>>; - required: z.ZodOptional>; - }, z.core.$catchall>>; - annotations: z.ZodOptional; - readOnlyHint: z.ZodOptional; - destructiveHint: z.ZodOptional; - idempotentHint: z.ZodOptional; - openWorldHint: z.ZodOptional; - }, z.core.$strip>>; - securitySchemes: z.ZodOptional; - }, z.core.$strip>, z.ZodObject<{ - type: z.ZodLiteral<"oauth2">; - scopes: z.ZodOptional>; - }, z.core.$strip>]>>>; - _meta: z.ZodOptional>; - icons: z.ZodOptional; - sizes: z.ZodOptional>; - }, z.core.$strip>>>; - name: z.ZodString; - title: z.ZodOptional; - }, z.core.$strip>>; -}, z.core.$loose>]>; -export declare class McpError extends Error { - readonly code: number; - readonly data?: unknown; - constructor(code: number, message: string, data?: unknown); - /** - * Factory method to create the appropriate error type based on the error code and data - */ - static fromError(code: number, message: string, data?: unknown): McpError; -} -/** - * Specialized error type when a tool requires a URL mode elicitation. - * 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. - */ -export declare class UrlElicitationRequiredError extends McpError { - constructor(elicitations: ElicitRequestURLParams[], message?: string); - get elicitations(): ElicitRequestURLParams[]; -} -type Primitive = string | number | boolean | bigint | null | undefined; -type Flatten = T extends Primitive ? T : T extends Array ? Array> : T extends Set ? Set> : T extends Map ? Map, Flatten> : T extends object ? { - [K in keyof T]: Flatten; -} : T; -type Infer = Flatten>; -/** - * Headers that are compatible with both Node.js and the browser. - */ -export type IsomorphicHeaders = Record; -/** - * Information about the incoming request. - */ -export interface RequestInfo { - /** - * The headers of the request. - */ - headers: IsomorphicHeaders; -} -/** - * Extra information about a message. - */ -export interface MessageExtraInfo { - /** - * The request information. - */ - requestInfo?: RequestInfo; - /** - * The authentication information. - */ - authInfo?: AuthInfo; -} -export type ProgressToken = Infer; -export type Cursor = Infer; -export type Request = Infer; -export type RequestMeta = Infer; -export type Notification = Infer; -export type Result = Infer; -export type RequestId = Infer; -export type JSONRPCRequest = Infer; -export type JSONRPCNotification = Infer; -export type JSONRPCResponse = Infer; -export type JSONRPCError = Infer; -export type JSONRPCMessage = Infer; -export type RequestParams = Infer; -export type NotificationParams = Infer; -export type EmptyResult = Infer; -export type CancelledNotificationParams = Infer; -export type CancelledNotification = Infer; -export type Icon = Infer; -export type Icons = Infer; -export type BaseMetadata = Infer; -export type Implementation = Infer; -export type ClientCapabilities = Infer; -export type InitializeRequestParams = Infer; -export type InitializeRequest = Infer; -export type ServerCapabilities = Infer; -export type InitializeResult = Infer; -export type InitializedNotification = Infer; -export type PingRequest = Infer; -export type Progress = Infer; -export type ProgressNotificationParams = Infer; -export type ProgressNotification = Infer; -export type PaginatedRequestParams = Infer; -export type PaginatedRequest = Infer; -export type PaginatedResult = Infer; -export type ResourceContents = Infer; -export type TextResourceContents = Infer; -export type BlobResourceContents = Infer; -export type Resource = Infer; -export type ResourceTemplate = Infer; -export type ListResourcesRequest = Infer; -export type ListResourcesResult = Infer; -export type ListResourceTemplatesRequest = Infer; -export type ListResourceTemplatesResult = Infer; -export type ResourceRequestParams = Infer; -export type ReadResourceRequestParams = Infer; -export type ReadResourceRequest = Infer; -export type ReadResourceResult = Infer; -export type ResourceListChangedNotification = Infer; -export type SubscribeRequestParams = Infer; -export type SubscribeRequest = Infer; -export type UnsubscribeRequestParams = Infer; -export type UnsubscribeRequest = Infer; -export type ResourceUpdatedNotificationParams = Infer; -export type ResourceUpdatedNotification = Infer; -export type PromptArgument = Infer; -export type Prompt = Infer; -export type ListPromptsRequest = Infer; -export type ListPromptsResult = Infer; -export type GetPromptRequestParams = Infer; -export type GetPromptRequest = Infer; -export type TextContent = Infer; -export type ImageContent = Infer; -export type AudioContent = Infer; -export type ToolUseContent = Infer; -export type ToolResultContent = Infer; -export type EmbeddedResource = Infer; -export type ResourceLink = Infer; -export type ContentBlock = Infer; -export type PromptMessage = Infer; -export type GetPromptResult = Infer; -export type PromptListChangedNotification = Infer; -export type NoAuthSecurityScheme = Infer; -export type OAuth2SecurityScheme = Infer; -export type SecurityScheme = Infer; -export type ToolAnnotations = Infer; -export type Tool = Infer; -export type ListToolsRequest = Infer; -export type ListToolsResult = Infer; -export type CallToolRequestParams = Infer; -export type CallToolResult = Infer; -export type CompatibilityCallToolResult = Infer; -export type CallToolRequest = Infer; -export type ToolListChangedNotification = Infer; -export type LoggingLevel = Infer; -export type SetLevelRequestParams = Infer; -export type SetLevelRequest = Infer; -export type LoggingMessageNotificationParams = Infer; -export type LoggingMessageNotification = Infer; -export type ToolChoice = Infer; -export type ModelHint = Infer; -export type ModelPreferences = Infer; -export type SamplingMessageContentBlock = Infer; -export type SamplingMessage = Infer; -export type CreateMessageRequestParams = Infer; -export type CreateMessageRequest = Infer; -export type CreateMessageResult = Infer; -export type BooleanSchema = Infer; -export type StringSchema = Infer; -export type NumberSchema = Infer; -export type EnumSchema = Infer; -export type UntitledSingleSelectEnumSchema = Infer; -export type TitledSingleSelectEnumSchema = Infer; -export type LegacyTitledEnumSchema = Infer; -export type UntitledMultiSelectEnumSchema = Infer; -export type TitledMultiSelectEnumSchema = Infer; -export type SingleSelectEnumSchema = Infer; -export type MultiSelectEnumSchema = Infer; -export type PrimitiveSchemaDefinition = Infer; -export type ElicitRequestParams = Infer; -export type ElicitRequestFormParams = Infer; -export type ElicitRequestURLParams = Infer; -export type ElicitRequest = Infer; -export type ElicitationCompleteNotificationParams = Infer; -export type ElicitationCompleteNotification = Infer; -export type ElicitResult = Infer; -export type ResourceTemplateReference = Infer; -/** - * @deprecated Use ResourceTemplateReference instead - */ -export type ResourceReference = ResourceTemplateReference; -export type PromptReference = Infer; -export type CompleteRequestParams = Infer; -export type CompleteRequest = Infer; -export type CompleteRequestResourceTemplate = ExpandRecursively; -export type CompleteRequestPrompt = ExpandRecursively; -export type CompleteResult = Infer; -export type Root = Infer; -export type ListRootsRequest = Infer; -export type ListRootsResult = Infer; -export type RootsListChangedNotification = Infer; -export type ClientRequest = Infer; -export type ClientNotification = Infer; -export type ClientResult = Infer; -export type ServerRequest = Infer; -export type ServerNotification = Infer; -export type ServerResult = Infer; -export {}; -//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/esm/types.d.ts.map b/dist/esm/types.d.ts.map deleted file mode 100644 index 39761f83d0..0000000000 --- a/dist/esm/types.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAC5B,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAElD,eAAO,MAAM,uBAAuB,eAAe,CAAC;AACpD,eAAO,MAAM,mCAAmC,eAAe,CAAC;AAChE,eAAO,MAAM,2BAA2B,UAAsE,CAAC;A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,CAAC,OAAO,oBAAoB,CAAC,CAAC;AAGhE,MAAM,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,UAAU,CAAC,CAAC;AAC5C,MAAM,MAAM,gBAAgB,GAAG,KAAK,CAAC,OAAO,sBAAsB,CAAC,CAAC;AACpE,MAAM,MAAM,eAAe,GAAG,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAClE,MAAM,MAAM,4BAA4B,GAAG,KAAK,CAAC,OAAO,kCAAkC,CAAC,CAAC;AAG5F,MAAM,MAAM,aAAa,GAAG,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAC9D,MAAM,MAAM,kBAAkB,GAAG,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;AACxE,MAAM,MAAM,YAAY,GAAG,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAG5D,MAAM,MAAM,aAAa,GAAG,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAC9D,MAAM,MAAM,kBAAkB,GAAG,KAAK,CAAC,OAAO,wBAAwB,CAAC,CAAC;AACxE,MAAM,MAAM,YAAY,GAAG,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC"} \ No newline at end of file diff --git a/dist/esm/types.js b/dist/esm/types.js deleted file mode 100644 index 933121d8c3..0000000000 --- a/dist/esm/types.js +++ /dev/null @@ -1,1659 +0,0 @@ -import * as z from 'zod/v4'; -export const LATEST_PROTOCOL_VERSION = '2025-06-18'; -export const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26'; -export const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-03-26', '2024-11-05', '2024-10-07']; -/* JSON-RPC types */ -export const JSONRPC_VERSION = '2.0'; -/** - * Assert 'object' type schema. - * - * @internal - */ -const AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function')); -/** - * A progress token, used to associate progress notifications with the original request. - */ -export const ProgressTokenSchema = z.union([z.string(), z.number().int()]); -/** - * An opaque token used to represent a cursor for pagination. - */ -export const CursorSchema = z.string(); -const RequestMetaSchema = z.looseObject({ - /** - * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. - */ - progressToken: ProgressTokenSchema.optional() -}); -/** - * Common params for any request. - */ -const BaseRequestParamsSchema = z.looseObject({ - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta: RequestMetaSchema.optional() -}); -export const RequestSchema = z.object({ - method: z.string(), - params: BaseRequestParamsSchema.optional() -}); -const NotificationsParamsSchema = z.looseObject({ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -export const NotificationSchema = z.object({ - method: z.string(), - params: NotificationsParamsSchema.optional() -}); -export const ResultSchema = z.looseObject({ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * A uniquely identifying ID for a request in JSON-RPC. - */ -export const RequestIdSchema = z.union([z.string(), z.number().int()]); -/** - * A request that expects a response. - */ -export const JSONRPCRequestSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema, - ...RequestSchema.shape -}) - .strict(); -export const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; -/** - * A notification which does not expect a response. - */ -export const JSONRPCNotificationSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - ...NotificationSchema.shape -}) - .strict(); -export const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; -/** - * A successful (non-error) response to a request. - */ -export const JSONRPCResponseSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema, - result: ResultSchema -}) - .strict(); -export const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; -/** - * Error codes defined by the JSON-RPC specification. - */ -export var ErrorCode; -(function (ErrorCode) { - // SDK error codes - ErrorCode[ErrorCode["ConnectionClosed"] = -32000] = "ConnectionClosed"; - ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout"; - // Standard JSON-RPC error codes - ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError"; - ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest"; - ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound"; - ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams"; - ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError"; - // MCP-specific error codes - ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; -})(ErrorCode || (ErrorCode = {})); -/** - * A response to a request that indicates an error occurred. - */ -export const JSONRPCErrorSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema, - error: z.object({ - /** - * The error type that occurred. - */ - code: z.number().int(), - /** - * A short description of the error. The message SHOULD be limited to a concise single sentence. - */ - message: z.string(), - /** - * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). - */ - data: z.optional(z.unknown()) - }) -}) - .strict(); -export const isJSONRPCError = (value) => JSONRPCErrorSchema.safeParse(value).success; -export const JSONRPCMessageSchema = z.union([JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResponseSchema, JSONRPCErrorSchema]); -/* Empty result */ -/** - * A response that indicates success but carries no data. - */ -export const EmptyResultSchema = ResultSchema.strict(); -export const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The ID of the request to cancel. - * - * This MUST correspond to the ID of a request previously issued in the same direction. - */ - requestId: RequestIdSchema, - /** - * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. - */ - reason: z.string().optional() -}); -/* Cancellation */ -/** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its `initialize` request. - */ -export const CancelledNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/cancelled'), - params: CancelledNotificationParamsSchema -}); -/* Base Metadata */ -/** - * Icon schema for use in tools, prompts, resources, and implementations. - */ -export const IconSchema = z.object({ - /** - * URL or data URI for the icon. - */ - src: z.string(), - /** - * Optional MIME type for the icon. - */ - mimeType: z.string().optional(), - /** - * Optional array of strings that specify sizes at which the icon can be used. - * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. - * - * If not provided, the client should assume that the icon can be used at any size. - */ - sizes: z.array(z.string()).optional() -}); -/** - * Base schema to add `icons` property. - * - */ -export const IconsSchema = z.object({ - /** - * Optional set of sized icons that the client can display in a user interface. - * - * Clients that support rendering icons MUST support at least the following MIME types: - * - `image/png` - PNG images (safe, universal compatibility) - * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) - * - * Clients that support rendering icons SHOULD also support: - * - `image/svg+xml` - SVG images (scalable but requires security precautions) - * - `image/webp` - WebP images (modern, efficient format) - */ - icons: z.array(IconSchema).optional() -}); -/** - * Base metadata interface for common properties across resources, tools, prompts, and implementations. - */ -export const BaseMetadataSchema = z.object({ - /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ - name: z.string(), - /** - * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, - * even by those unfamiliar with domain-specific terminology. - * - * If not provided, the name should be used for display (except for Tool, - * where `annotations.title` should be given precedence over using `name`, - * if present). - */ - title: z.string().optional() -}); -/* Initialization */ -/** - * Describes the name and version of an MCP implementation. - */ -export const ImplementationSchema = BaseMetadataSchema.extend({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - version: z.string(), - /** - * An optional URL of the website for this implementation. - */ - websiteUrl: z.string().optional() -}); -const FormElicitationCapabilitySchema = z.intersection(z.object({ - applyDefaults: z.boolean().optional() -}), z.record(z.string(), z.unknown())); -const ElicitationCapabilitySchema = z.preprocess(value => { - if (value && typeof value === 'object' && !Array.isArray(value)) { - if (Object.keys(value).length === 0) { - return { form: {} }; - } - } - return value; -}, z.intersection(z.object({ - form: FormElicitationCapabilitySchema.optional(), - url: AssertObjectSchema.optional() -}), z.record(z.string(), z.unknown()).optional())); -/** - * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. - */ -export const ClientCapabilitiesSchema = z.object({ - /** - * Experimental, non-standard capabilities that the client supports. - */ - experimental: z.record(z.string(), AssertObjectSchema).optional(), - /** - * Present if the client supports sampling from an LLM. - */ - sampling: z - .object({ - /** - * Present if the client supports context inclusion via includeContext parameter. - * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). - */ - context: AssertObjectSchema.optional(), - /** - * Present if the client supports tool use via tools and toolChoice parameters. - */ - tools: AssertObjectSchema.optional() - }) - .optional(), - /** - * Present if the client supports eliciting user input. - */ - elicitation: ElicitationCapabilitySchema.optional(), - /** - * Present if the client supports listing roots. - */ - roots: z - .object({ - /** - * Whether the client supports issuing notifications for changes to the roots list. - */ - listChanged: z.boolean().optional() - }) - .optional() -}); -export const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. - */ - protocolVersion: z.string(), - capabilities: ClientCapabilitiesSchema, - clientInfo: ImplementationSchema -}); -/** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - */ -export const InitializeRequestSchema = RequestSchema.extend({ - method: z.literal('initialize'), - params: InitializeRequestParamsSchema -}); -export const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; -/** - * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. - */ -export const ServerCapabilitiesSchema = z.object({ - /** - * Experimental, non-standard capabilities that the server supports. - */ - experimental: z.record(z.string(), AssertObjectSchema).optional(), - /** - * Present if the server supports sending log messages to the client. - */ - logging: AssertObjectSchema.optional(), - /** - * Present if the server supports sending completions to the client. - */ - completions: AssertObjectSchema.optional(), - /** - * Present if the server offers any prompt templates. - */ - prompts: z.optional(z.object({ - /** - * Whether this server supports issuing notifications for changes to the prompt list. - */ - listChanged: z.optional(z.boolean()) - })), - /** - * Present if the server offers any resources to read. - */ - resources: z - .object({ - /** - * Whether this server supports clients subscribing to resource updates. - */ - subscribe: z.boolean().optional(), - /** - * Whether this server supports issuing notifications for changes to the resource list. - */ - listChanged: z.boolean().optional() - }) - .optional(), - /** - * Present if the server offers any tools to call. - */ - tools: z - .object({ - /** - * Whether this server supports issuing notifications for changes to the tool list. - */ - listChanged: z.boolean().optional() - }) - .optional() -}); -/** - * After receiving an initialize request from the client, the server sends this response. - */ -export const InitializeResultSchema = ResultSchema.extend({ - /** - * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. - */ - protocolVersion: z.string(), - capabilities: ServerCapabilitiesSchema, - serverInfo: ImplementationSchema, - /** - * Instructions describing how to use the server and its features. - * - * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. - */ - instructions: z.string().optional() -}); -/** - * This notification is sent from the client to the server after initialization has finished. - */ -export const InitializedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/initialized') -}); -export const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; -/* Ping */ -/** - * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. - */ -export const PingRequestSchema = RequestSchema.extend({ - method: z.literal('ping') -}); -/* Progress notifications */ -export const ProgressSchema = z.object({ - /** - * The progress thus far. This should increase every time progress is made, even if the total is unknown. - */ - progress: z.number(), - /** - * Total number of items to process (or total progress required), if known. - */ - total: z.optional(z.number()), - /** - * An optional message describing the current progress. - */ - message: z.optional(z.string()) -}); -export const ProgressNotificationParamsSchema = z.object({ - ...NotificationsParamsSchema.shape, - ...ProgressSchema.shape, - /** - * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. - */ - progressToken: ProgressTokenSchema -}); -/** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - * - * @category notifications/progress - */ -export const ProgressNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/progress'), - params: ProgressNotificationParamsSchema -}); -export const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * An opaque token representing the current pagination position. - * If provided, the server should return results starting after this cursor. - */ - cursor: CursorSchema.optional() -}); -/* Pagination */ -export const PaginatedRequestSchema = RequestSchema.extend({ - params: PaginatedRequestParamsSchema.optional() -}); -export const PaginatedResultSchema = ResultSchema.extend({ - /** - * An opaque token representing the pagination position after the last returned result. - * If present, there may be more results available. - */ - nextCursor: z.optional(CursorSchema) -}); -/* Resources */ -/** - * The contents of a specific resource or sub-resource. - */ -export const ResourceContentsSchema = z.object({ - /** - * The URI of this resource. - */ - uri: z.string(), - /** - * The MIME type of this resource, if known. - */ - mimeType: z.optional(z.string()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -export const TextResourceContentsSchema = ResourceContentsSchema.extend({ - /** - * The text of the item. This must only be set if the item can actually be represented as text (not binary data). - */ - text: z.string() -}); -/** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ -const Base64Schema = z.string().refine(val => { - try { - // atob throws a DOMException if the string contains characters - // that are not part of the Base64 character set. - atob(val); - return true; - } - catch (_a) { - return false; - } -}, { message: 'Invalid Base64 string' }); -export const BlobResourceContentsSchema = ResourceContentsSchema.extend({ - /** - * A base64-encoded string representing the binary data of the item. - */ - blob: Base64Schema -}); -/** - * A known resource that the server is capable of reading. - */ -export const ResourceSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * The URI of this resource. - */ - uri: z.string(), - /** - * A description of what this resource represents. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description: z.optional(z.string()), - /** - * The MIME type of this resource, if known. - */ - mimeType: z.optional(z.string()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.looseObject({})) -}); -/** - * A template description for resources available on the server. - */ -export const ResourceTemplateSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * A URI template (according to RFC 6570) that can be used to construct resource URIs. - */ - uriTemplate: z.string(), - /** - * A description of what this template is for. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description: z.optional(z.string()), - /** - * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. - */ - mimeType: z.optional(z.string()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.looseObject({})) -}); -/** - * Sent from the client to request a list of resources the server has. - */ -export const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('resources/list') -}); -/** - * The server's response to a resources/list request from the client. - */ -export const ListResourcesResultSchema = PaginatedResultSchema.extend({ - resources: z.array(ResourceSchema) -}); -/** - * Sent from the client to request a list of resource templates the server has. - */ -export const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('resources/templates/list') -}); -/** - * The server's response to a resources/templates/list request from the client. - */ -export const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ - resourceTemplates: z.array(ResourceTemplateSchema) -}); -export const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. - * - * @format uri - */ - uri: z.string() -}); -/** - * Parameters for a `resources/read` request. - */ -export const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; -/** - * Sent from the client to the server, to read a specific resource URI. - */ -export const ReadResourceRequestSchema = RequestSchema.extend({ - method: z.literal('resources/read'), - params: ReadResourceRequestParamsSchema -}); -/** - * The server's response to a resources/read request from the client. - */ -export const ReadResourceResultSchema = ResultSchema.extend({ - contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) -}); -/** - * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. - */ -export const ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/resources/list_changed') -}); -export const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** - * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. - */ -export const SubscribeRequestSchema = RequestSchema.extend({ - method: z.literal('resources/subscribe'), - params: SubscribeRequestParamsSchema -}); -export const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** - * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. - */ -export const UnsubscribeRequestSchema = RequestSchema.extend({ - method: z.literal('resources/unsubscribe'), - params: UnsubscribeRequestParamsSchema -}); -/** - * Parameters for a `notifications/resources/updated` notification. - */ -export const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. - */ - uri: z.string() -}); -/** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. - */ -export const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/resources/updated'), - params: ResourceUpdatedNotificationParamsSchema -}); -/* Prompts */ -/** - * Describes an argument that a prompt can accept. - */ -export const PromptArgumentSchema = z.object({ - /** - * The name of the argument. - */ - name: z.string(), - /** - * A human-readable description of the argument. - */ - description: z.optional(z.string()), - /** - * Whether this argument must be provided. - */ - required: z.optional(z.boolean()) -}); -/** - * A prompt or prompt template that the server offers. - */ -export const PromptSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * An optional description of what this prompt provides - */ - description: z.optional(z.string()), - /** - * A list of arguments to use for templating the prompt. - */ - arguments: z.optional(z.array(PromptArgumentSchema)), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.looseObject({})) -}); -/** - * Sent from the client to request a list of prompts and prompt templates the server has. - */ -export const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('prompts/list') -}); -/** - * The server's response to a prompts/list request from the client. - */ -export const ListPromptsResultSchema = PaginatedResultSchema.extend({ - prompts: z.array(PromptSchema) -}); -/** - * Parameters for a `prompts/get` request. - */ -export const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The name of the prompt or prompt template. - */ - name: z.string(), - /** - * Arguments to use for templating the prompt. - */ - arguments: z.record(z.string(), z.string()).optional() -}); -/** - * Used by the client to get a prompt provided by the server. - */ -export const GetPromptRequestSchema = RequestSchema.extend({ - method: z.literal('prompts/get'), - params: GetPromptRequestParamsSchema -}); -/** - * Text provided to or from an LLM. - */ -export const TextContentSchema = z.object({ - type: z.literal('text'), - /** - * The text content of the message. - */ - text: z.string(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * An image provided to or from an LLM. - */ -export const ImageContentSchema = z.object({ - type: z.literal('image'), - /** - * The base64-encoded image data. - */ - data: Base64Schema, - /** - * The MIME type of the image. Different providers may support different image types. - */ - mimeType: z.string(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * An Audio provided to or from an LLM. - */ -export const AudioContentSchema = z.object({ - type: z.literal('audio'), - /** - * The base64-encoded audio data. - */ - data: Base64Schema, - /** - * The MIME type of the audio. Different providers may support different audio types. - */ - mimeType: z.string(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * A tool call request from an assistant (LLM). - * Represents the assistant's request to use a tool. - */ -export const ToolUseContentSchema = z - .object({ - type: z.literal('tool_use'), - /** - * The name of the tool to invoke. - * Must match a tool name from the request's tools array. - */ - name: z.string(), - /** - * Unique identifier for this tool call. - * Used to correlate with ToolResultContent in subsequent messages. - */ - id: z.string(), - /** - * Arguments to pass to the tool. - * Must conform to the tool's inputSchema. - */ - input: z.object({}).passthrough(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) -}) - .passthrough(); -/** - * The contents of a resource, embedded into a prompt or tool call result. - */ -export const EmbeddedResourceSchema = z.object({ - type: z.literal('resource'), - resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * A resource that the server is capable of reading, included in a prompt or tool call result. - * - * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. - */ -export const ResourceLinkSchema = ResourceSchema.extend({ - type: z.literal('resource_link') -}); -/** - * A content block that can be used in prompts and tool results. - */ -export const ContentBlockSchema = z.union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ResourceLinkSchema, - EmbeddedResourceSchema -]); -/** - * Describes a message returned as part of a prompt. - */ -export const PromptMessageSchema = z.object({ - role: z.enum(['user', 'assistant']), - content: ContentBlockSchema -}); -/** - * The server's response to a prompts/get request from the client. - */ -export const GetPromptResultSchema = ResultSchema.extend({ - /** - * An optional description for the prompt. - */ - description: z.optional(z.string()), - messages: z.array(PromptMessageSchema) -}); -/** - * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. - */ -export const PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/prompts/list_changed') -}); -/* Tools */ -/** - * Security scheme indicating no authentication is required. - */ -export const NoAuthSecuritySchemeSchema = z.object({ - type: z.literal('noauth') -}); -/** - * Security scheme indicating OAuth 2.0 authentication is required. - */ -export const OAuth2SecuritySchemeSchema = z.object({ - type: z.literal('oauth2'), - /** - * Optional list of OAuth 2.0 scopes required for this tool. - */ - scopes: z - .array(z.string().min(1)) - .refine((arr) => new Set(arr).size === arr.length, { - message: 'Scopes must be unique' - }) - .optional() -}); -/** - * A security scheme that can be used to authenticate tool calls. - */ -export const SecuritySchemeSchema = z.union([NoAuthSecuritySchemeSchema, OAuth2SecuritySchemeSchema]); -/** - * Additional properties describing a Tool to clients. - * - * NOTE: all properties in ToolAnnotations are **hints**. - * They are not guaranteed to provide a faithful description of - * tool behavior (including descriptive properties like `title`). - * - * Clients should never make tool use decisions based on ToolAnnotations - * received from untrusted servers. - */ -export const ToolAnnotationsSchema = z.object({ - /** - * A human-readable title for the tool. - */ - title: z.string().optional(), - /** - * If true, the tool does not modify its environment. - * - * Default: false - */ - readOnlyHint: z.boolean().optional(), - /** - * If true, the tool may perform destructive updates to its environment. - * If false, the tool performs only additive updates. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: true - */ - destructiveHint: z.boolean().optional(), - /** - * If true, calling the tool repeatedly with the same arguments - * will have no additional effect on the its environment. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: false - */ - idempotentHint: z.boolean().optional(), - /** - * If true, this tool may interact with an "open world" of external - * entities. If false, the tool's domain of interaction is closed. - * For example, the world of a web search tool is open, whereas that - * of a memory tool is not. - * - * Default: true - */ - openWorldHint: z.boolean().optional() -}); -/** - * Definition for a tool the client can call. - */ -export const ToolSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * A human-readable description of the tool. - */ - description: z.string().optional(), - /** - * A JSON Schema 2020-12 object defining the expected parameters for the tool. - * Must have type: 'object' at the root level per MCP spec. - */ - inputSchema: z - .object({ - type: z.literal('object'), - properties: z.record(z.string(), AssertObjectSchema).optional(), - required: z.array(z.string()).optional() - }) - .catchall(z.unknown()), - /** - * An optional JSON Schema 2020-12 object defining the structure of the tool's output - * returned in the structuredContent field of a CallToolResult. - * Must have type: 'object' at the root level per MCP spec. - */ - outputSchema: z - .object({ - type: z.literal('object'), - properties: z.record(z.string(), AssertObjectSchema).optional(), - required: z.array(z.string()).optional() - }) - .catchall(z.unknown()) - .optional(), - /** - * Optional additional tool information. - */ - annotations: z.optional(ToolAnnotationsSchema), - /** - * Optional list of security schemes supported by this tool. - * If missing, the tool follows the server's default authentication policy. - * If present, lists the supported authentication schemes (e.g., "noauth", "oauth2"). - */ - securitySchemes: z.array(SecuritySchemeSchema).optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * Sent from the client to request a list of tools the server has. - */ -export const ListToolsRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('tools/list') -}); -/** - * The server's response to a tools/list request from the client. - */ -export const ListToolsResultSchema = PaginatedResultSchema.extend({ - tools: z.array(ToolSchema) -}); -/** - * The server's response to a tool call. - */ -export const CallToolResultSchema = ResultSchema.extend({ - /** - * A list of content objects that represent the result of the tool call. - * - * If the Tool does not define an outputSchema, this field MUST be present in the result. - * For backwards compatibility, this field is always present, but it may be empty. - */ - content: z.array(ContentBlockSchema).default([]), - /** - * An object containing structured tool output. - * - * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. - */ - structuredContent: z.record(z.string(), z.unknown()).optional(), - /** - * Whether the tool call ended in an error. - * - * If not set, this is assumed to be false (the call was successful). - * - * Any errors that originate from the tool SHOULD be reported inside the result - * object, with `isError` set to true, _not_ as an MCP protocol-level error - * response. Otherwise, the LLM would not be able to see that an error occurred - * and self-correct. - * - * However, any errors in _finding_ the tool, an error indicating that the - * server does not support tool calls, or any other exceptional conditions, - * should be reported as an MCP error response. - */ - isError: z.optional(z.boolean()) -}); -/** - * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. - */ -export const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ - toolResult: z.unknown() -})); -/** - * Parameters for a `tools/call` request. - */ -export const CallToolRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The name of the tool to call. - */ - name: z.string(), - /** - * Arguments to pass to the tool. - */ - arguments: z.optional(z.record(z.string(), z.unknown())) -}); -/** - * Used by the client to invoke a tool provided by the server. - */ -export const CallToolRequestSchema = RequestSchema.extend({ - method: z.literal('tools/call'), - params: CallToolRequestParamsSchema -}); -/** - * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. - */ -export const ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/tools/list_changed') -}); -/* Logging */ -/** - * The severity of a log message. - */ -export const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); -/** - * Parameters for a `logging/setLevel` request. - */ -export const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. - */ - level: LoggingLevelSchema -}); -/** - * A request from the client to the server, to enable or adjust logging. - */ -export const SetLevelRequestSchema = RequestSchema.extend({ - method: z.literal('logging/setLevel'), - params: SetLevelRequestParamsSchema -}); -/** - * Parameters for a `notifications/message` notification. - */ -export const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The severity of this log message. - */ - level: LoggingLevelSchema, - /** - * An optional name of the logger issuing this message. - */ - logger: z.string().optional(), - /** - * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. - */ - data: z.unknown() -}); -/** - * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. - */ -export const LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/message'), - params: LoggingMessageNotificationParamsSchema -}); -/* Sampling */ -/** - * Hints to use for model selection. - */ -export const ModelHintSchema = z.object({ - /** - * A hint for a model name. - */ - name: z.string().optional() -}); -/** - * The server's preferences for model selection, requested of the client during sampling. - */ -export const ModelPreferencesSchema = z.object({ - /** - * Optional hints to use for model selection. - */ - hints: z.optional(z.array(ModelHintSchema)), - /** - * How much to prioritize cost when selecting a model. - */ - costPriority: z.optional(z.number().min(0).max(1)), - /** - * How much to prioritize sampling speed (latency) when selecting a model. - */ - speedPriority: z.optional(z.number().min(0).max(1)), - /** - * How much to prioritize intelligence and capabilities when selecting a model. - */ - intelligencePriority: z.optional(z.number().min(0).max(1)) -}); -/** - * Controls tool usage behavior in sampling requests. - */ -export const ToolChoiceSchema = z.object({ - /** - * Controls when tools are used: - * - "auto": Model decides whether to use tools (default) - * - "required": Model MUST use at least one tool before completing - * - "none": Model MUST NOT use any tools - */ - mode: z.optional(z.enum(['auto', 'required', 'none'])) -}); -/** - * The result of a tool execution, provided by the user (server). - * Represents the outcome of invoking a tool requested via ToolUseContent. - */ -export const ToolResultContentSchema = z - .object({ - type: z.literal('tool_result'), - toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'), - content: z.array(ContentBlockSchema).default([]), - structuredContent: z.object({}).passthrough().optional(), - isError: z.optional(z.boolean()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) -}) - .passthrough(); -/** - * Content block types allowed in sampling messages. - * This includes text, image, audio, tool use requests, and tool results. - */ -export const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ToolUseContentSchema, - ToolResultContentSchema -]); -/** - * Describes a message issued to or received from an LLM API. - */ -export const SamplingMessageSchema = z - .object({ - role: z.enum(['user', 'assistant']), - content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.object({}).passthrough()) -}) - .passthrough(); -/** - * Parameters for a `sampling/createMessage` request. - */ -export const CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({ - messages: z.array(SamplingMessageSchema), - /** - * The server's preferences for which model to select. The client MAY modify or omit this request. - */ - modelPreferences: ModelPreferencesSchema.optional(), - /** - * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. - */ - systemPrompt: z.string().optional(), - /** - * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. - * The client MAY ignore this request. - * - * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client - * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. - */ - includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(), - temperature: z.number().optional(), - /** - * The requested maximum number of tokens to sample (to prevent runaway completions). - * - * The client MAY choose to sample fewer tokens than the requested maximum. - */ - maxTokens: z.number().int(), - stopSequences: z.array(z.string()).optional(), - /** - * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. - */ - metadata: AssertObjectSchema.optional(), - /** - * Tools that the model may use during generation. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. - */ - tools: z.optional(z.array(ToolSchema)), - /** - * Controls how the model uses tools. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. - * Default is `{ mode: "auto" }`. - */ - toolChoice: z.optional(ToolChoiceSchema) -}); -/** - * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. - */ -export const CreateMessageRequestSchema = RequestSchema.extend({ - method: z.literal('sampling/createMessage'), - params: CreateMessageRequestParamsSchema -}); -/** - * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. - */ -export const CreateMessageResultSchema = ResultSchema.extend({ - /** - * The name of the model that generated the message. - */ - model: z.string(), - /** - * The reason why sampling stopped, if known. - * - * Standard values: - * - "endTurn": Natural end of the assistant's turn - * - "stopSequence": A stop sequence was encountered - * - "maxTokens": Maximum token limit was reached - * - "toolUse": The model wants to use one or more tools - * - * This field is an open string to allow for provider-specific stop reasons. - */ - stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())), - role: z.enum(['user', 'assistant']), - /** - * Response content. May be ToolUseContent if stopReason is "toolUse". - */ - content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]) -}); -/* Elicitation */ -/** - * Primitive schema definition for boolean fields. - */ -export const BooleanSchemaSchema = z.object({ - type: z.literal('boolean'), - title: z.string().optional(), - description: z.string().optional(), - default: z.boolean().optional() -}); -/** - * Primitive schema definition for string fields. - */ -export const StringSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - minLength: z.number().optional(), - maxLength: z.number().optional(), - format: z.enum(['email', 'uri', 'date', 'date-time']).optional(), - default: z.string().optional() -}); -/** - * Primitive schema definition for number fields. - */ -export const NumberSchemaSchema = z.object({ - type: z.enum(['number', 'integer']), - title: z.string().optional(), - description: z.string().optional(), - minimum: z.number().optional(), - maximum: z.number().optional(), - default: z.number().optional() -}); -/** - * Schema for single-selection enumeration without display titles for options. - */ -export const UntitledSingleSelectEnumSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - enum: z.array(z.string()), - default: z.string().optional() -}); -/** - * Schema for single-selection enumeration with display titles for each option. - */ -export const TitledSingleSelectEnumSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - oneOf: z.array(z.object({ - const: z.string(), - title: z.string() - })), - default: z.string().optional() -}); -/** - * Use TitledSingleSelectEnumSchema instead. - * This interface will be removed in a future version. - */ -export const LegacyTitledEnumSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - enum: z.array(z.string()), - enumNames: z.array(z.string()).optional(), - default: z.string().optional() -}); -// Combined single selection enumeration -export const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); -/** - * Schema for multiple-selection enumeration without display titles for options. - */ -export const UntitledMultiSelectEnumSchemaSchema = z.object({ - type: z.literal('array'), - title: z.string().optional(), - description: z.string().optional(), - minItems: z.number().optional(), - maxItems: z.number().optional(), - items: z.object({ - type: z.literal('string'), - enum: z.array(z.string()) - }), - default: z.array(z.string()).optional() -}); -/** - * Schema for multiple-selection enumeration with display titles for each option. - */ -export const TitledMultiSelectEnumSchemaSchema = z.object({ - type: z.literal('array'), - title: z.string().optional(), - description: z.string().optional(), - minItems: z.number().optional(), - maxItems: z.number().optional(), - items: z.object({ - anyOf: z.array(z.object({ - const: z.string(), - title: z.string() - })) - }), - default: z.array(z.string()).optional() -}); -/** - * Combined schema for multiple-selection enumeration - */ -export const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); -/** - * Primitive schema definition for enum fields. - */ -export const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); -/** - * Union of all primitive schema definitions. - */ -export const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); -/** - * Parameters for an `elicitation/create` request for form-based elicitation. - */ -export const ElicitRequestFormParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The elicitation mode. - */ - mode: z.literal('form'), - /** - * The message to present to the user describing what information is being requested. - */ - message: z.string(), - /** - * A restricted subset of JSON Schema. - * Only top-level properties are allowed, without nesting. - */ - requestedSchema: z.object({ - type: z.literal('object'), - properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema), - required: z.array(z.string()).optional() - }) -}); -/** - * Parameters for an `elicitation/create` request for URL-based elicitation. - */ -export const ElicitRequestURLParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The elicitation mode. - */ - mode: z.literal('url'), - /** - * The message to present to the user explaining why the interaction is needed. - */ - message: z.string(), - /** - * The ID of the elicitation, which must be unique within the context of the server. - * The client MUST treat this ID as an opaque value. - */ - elicitationId: z.string(), - /** - * The URL that the user should navigate to. - */ - url: z.string().url() -}); -/** - * The parameters for a request to elicit additional information from the user via the client. - */ -export const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); -/** - * A request from the server to elicit user input via the client. - * The client should present the message and form fields to the user (form mode) - * or navigate to a URL (URL mode). - */ -export const ElicitRequestSchema = RequestSchema.extend({ - method: z.literal('elicitation/create'), - params: ElicitRequestParamsSchema -}); -/** - * Parameters for a `notifications/elicitation/complete` notification. - * - * @category notifications/elicitation/complete - */ -export const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The ID of the elicitation that completed. - */ - elicitationId: z.string() -}); -/** - * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. - * - * @category notifications/elicitation/complete - */ -export const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/elicitation/complete'), - params: ElicitationCompleteNotificationParamsSchema -}); -/** - * The client's response to an elicitation/create request from the server. - */ -export const ElicitResultSchema = ResultSchema.extend({ - /** - * The user action in response to the elicitation. - * - "accept": User submitted the form/confirmed the action - * - "decline": User explicitly decline the action - * - "cancel": User dismissed without making an explicit choice - */ - action: z.enum(['accept', 'decline', 'cancel']), - /** - * The submitted form data, only present when action is "accept". - * Contains values matching the requested schema. - */ - content: z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional() -}); -/* Autocomplete */ -/** - * A reference to a resource or resource template definition. - */ -export const ResourceTemplateReferenceSchema = z.object({ - type: z.literal('ref/resource'), - /** - * The URI or URI template of the resource. - */ - uri: z.string() -}); -/** - * @deprecated Use ResourceTemplateReferenceSchema instead - */ -export const ResourceReferenceSchema = ResourceTemplateReferenceSchema; -/** - * Identifies a prompt. - */ -export const PromptReferenceSchema = z.object({ - type: z.literal('ref/prompt'), - /** - * The name of the prompt or prompt template - */ - name: z.string() -}); -/** - * Parameters for a `completion/complete` request. - */ -export const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ - ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - /** - * The argument's information - */ - argument: z.object({ - /** - * The name of the argument - */ - name: z.string(), - /** - * The value of the argument to use for completion matching. - */ - value: z.string() - }), - context: z - .object({ - /** - * Previously-resolved variables in a URI template or prompt. - */ - arguments: z.record(z.string(), z.string()).optional() - }) - .optional() -}); -/** - * A request from the client to the server, to ask for completion options. - */ -export const CompleteRequestSchema = RequestSchema.extend({ - method: z.literal('completion/complete'), - params: CompleteRequestParamsSchema -}); -export function assertCompleteRequestPrompt(request) { - if (request.params.ref.type !== 'ref/prompt') { - throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); - } - void request; -} -export function assertCompleteRequestResourceTemplate(request) { - if (request.params.ref.type !== 'ref/resource') { - throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); - } - void request; -} -/** - * The server's response to a completion/complete request - */ -export const CompleteResultSchema = ResultSchema.extend({ - completion: z.looseObject({ - /** - * An array of completion values. Must not exceed 100 items. - */ - values: z.array(z.string()).max(100), - /** - * The total number of completion options available. This can exceed the number of values actually sent in the response. - */ - total: z.optional(z.number().int()), - /** - * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. - */ - hasMore: z.optional(z.boolean()) - }) -}); -/* Roots */ -/** - * Represents a root directory or file that the server can operate on. - */ -export const RootSchema = z.object({ - /** - * The URI identifying the root. This *must* start with file:// for now. - */ - uri: z.string().startsWith('file://'), - /** - * An optional name for the root. - */ - name: z.string().optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * Sent from the server to request a list of root URIs from the client. - */ -export const ListRootsRequestSchema = RequestSchema.extend({ - method: z.literal('roots/list') -}); -/** - * The client's response to a roots/list request from the server. - */ -export const ListRootsResultSchema = ResultSchema.extend({ - roots: z.array(RootSchema) -}); -/** - * A notification from the client to the server, informing it that the list of roots has changed. - */ -export const RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/roots/list_changed') -}); -/* Client messages */ -export const ClientRequestSchema = z.union([ - PingRequestSchema, - InitializeRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - CallToolRequestSchema, - ListToolsRequestSchema -]); -export const ClientNotificationSchema = z.union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - InitializedNotificationSchema, - RootsListChangedNotificationSchema -]); -export const ClientResultSchema = z.union([EmptyResultSchema, CreateMessageResultSchema, ElicitResultSchema, ListRootsResultSchema]); -/* Server messages */ -export const ServerRequestSchema = z.union([PingRequestSchema, CreateMessageRequestSchema, ElicitRequestSchema, ListRootsRequestSchema]); -export const ServerNotificationSchema = z.union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema, - ElicitationCompleteNotificationSchema -]); -export const ServerResultSchema = z.union([ - EmptyResultSchema, - InitializeResultSchema, - CompleteResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - CallToolResultSchema, - ListToolsResultSchema -]); -export class McpError extends Error { - constructor(code, message, data) { - super(`MCP error ${code}: ${message}`); - this.code = code; - this.data = data; - this.name = 'McpError'; - } - /** - * Factory method to create the appropriate error type based on the error code and data - */ - static fromError(code, message, data) { - // Check for specific error types - if (code === ErrorCode.UrlElicitationRequired && data) { - const errorData = data; - if (errorData.elicitations) { - return new UrlElicitationRequiredError(errorData.elicitations, message); - } - } - // Default to generic McpError - return new McpError(code, message, data); - } -} -/** - * Specialized error type when a tool requires a URL mode elicitation. - * 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. - */ -export class UrlElicitationRequiredError extends McpError { - constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) { - super(ErrorCode.UrlElicitationRequired, message, { - elicitations: elicitations - }); - } - get elicitations() { - var _a, _b; - return (_b = (_a = this.data) === null || _a === void 0 ? void 0 : _a.elicitations) !== null && _b !== void 0 ? _b : []; - } -} -//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/esm/types.js.map b/dist/esm/types.js.map deleted file mode 100644 index cfb037901e..0000000000 --- a/dist/esm/types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,QAAQ,CAAC;AAG5B,MAAM,CAAC,MAAM,uBAAuB,GAAG,YAAY,CAAC;AACpD,MAAM,CAAC,MAAM,mCAAmC,GAAG,YAAY,CAAC;AAChE,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,uBAAuB,EAAE,YAAY,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC;AAE/G,oBAAoB;AACpB,MAAM,CAAC,MAAM,eAAe,GAAG,KAAK,CAAC;AAMrC;;;;GAIG;AACH,MAAM,kBAAkB,GAAG,CAAC,CAAC,MAAM,CAAS,CAAC,CAAC,EAAe,EAAE,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,OAAO,CAAC,KAAK,UAAU,CAAC,CAAC,CAAC;AAClI;;GAEG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;AAE3E;;GAEG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,CAAC,MAAM,EAAE,CAAC;AAEvC,MAAM,iBAAiB,GAAG,CAAC,CAAC,WAAW,CAAC;I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,EAAE,OAAO,CAAC,CAAC;YACxG,CAAC;QACL,CAAC;QAED,8BAA8B;QAC9B,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IAC7C,CAAC;CACJ;AAED;;;GAGG;AACH,MAAM,OAAO,2BAA4B,SAAQ,QAAQ;IACrD,YAAY,YAAsC,EAAE,UAAkB,kBAAkB,YAAY,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,WAAW;QACjI,KAAK,CAAC,SAAS,CAAC,sBAAsB,EAAE,OAAO,EAAE;YAC7C,YAAY,EAAE,YAAY;SAC7B,CAAC,CAAC;IACP,CAAC;IAED,IAAI,YAAY;;QACZ,OAAO,MAAA,MAAC,IAAI,CAAC,IAAmD,0CAAE,YAAY,mCAAI,EAAE,CAAC;IACzF,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/validation/ajv-provider.d.ts b/dist/esm/validation/ajv-provider.d.ts deleted file mode 100644 index 43e24ffc93..0000000000 --- a/dist/esm/validation/ajv-provider.d.ts +++ /dev/null @@ -1,53 +0,0 @@ -/** - * AJV-based JSON Schema validator provider - */ -import { Ajv } from 'ajv'; -import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from './types.js'; -/** - * @example - * ```typescript - * // Use with default AJV instance (recommended) - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // Use with custom AJV instance - * import { Ajv } from 'ajv'; - * const ajv = new Ajv({ strict: true, allErrors: true }); - * const validator = new AjvJsonSchemaValidator(ajv); - * ``` - */ -export declare class AjvJsonSchemaValidator implements jsonSchemaValidator { - private _ajv; - /** - * Create an AJV validator - * - * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. - * - * @example - * ```typescript - * // Use default configuration (recommended for most cases) - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // Or provide custom AJV instance for advanced configuration - * import { Ajv } from 'ajv'; - * import addFormats from 'ajv-formats'; - * - * const ajv = new Ajv({ validateFormats: true }); - * addFormats(ajv); - * const validator = new AjvJsonSchemaValidator(ajv); - * ``` - */ - constructor(ajv?: Ajv); - /** - * Create a validator for the given JSON Schema - * - * The validator is compiled once and can be reused multiple times. - * If the schema has an $id, it will be cached by AJV automatically. - * - * @param schema - Standard JSON Schema object - * @returns A validator function that validates input data - */ - getValidator(schema: JsonSchemaType): JsonSchemaValidator; -} -//# sourceMappingURL=ajv-provider.d.ts.map \ No newline at end of file diff --git a/dist/esm/validation/ajv-provider.d.ts.map b/dist/esm/validation/ajv-provider.d.ts.map deleted file mode 100644 index 4e955a3b32..0000000000 --- a/dist/esm/validation/ajv-provider.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ajv-provider.d.ts","sourceRoot":"","sources":["../../../src/validation/ajv-provider.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAE1B,OAAO,KAAK,EAAE,cAAc,EAAE,mBAAmB,EAA6B,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAgBtH;;;;;;;;;;;;GAYG;AACH,qBAAa,sBAAuB,YAAW,mBAAmB;IAC9D,OAAO,CAAC,IAAI,CAAM;IAElB;;;;;;;;;;;;;;;;;;;OAmBG;gBACS,GAAG,CAAC,EAAE,GAAG;IAIrB;;;;;;;;OAQG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC;CAyBlE"} \ No newline at end of file diff --git a/dist/esm/validation/ajv-provider.js b/dist/esm/validation/ajv-provider.js deleted file mode 100644 index 02762f0c1d..0000000000 --- a/dist/esm/validation/ajv-provider.js +++ /dev/null @@ -1,88 +0,0 @@ -/** - * AJV-based JSON Schema validator provider - */ -import { Ajv } from 'ajv'; -import _addFormats from 'ajv-formats'; -function createDefaultAjvInstance() { - const ajv = new Ajv({ - strict: false, - validateFormats: true, - validateSchema: false, - allErrors: true - }); - const addFormats = _addFormats; - addFormats(ajv); - return ajv; -} -/** - * @example - * ```typescript - * // Use with default AJV instance (recommended) - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // Use with custom AJV instance - * import { Ajv } from 'ajv'; - * const ajv = new Ajv({ strict: true, allErrors: true }); - * const validator = new AjvJsonSchemaValidator(ajv); - * ``` - */ -export class AjvJsonSchemaValidator { - /** - * Create an AJV validator - * - * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. - * - * @example - * ```typescript - * // Use default configuration (recommended for most cases) - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // Or provide custom AJV instance for advanced configuration - * import { Ajv } from 'ajv'; - * import addFormats from 'ajv-formats'; - * - * const ajv = new Ajv({ validateFormats: true }); - * addFormats(ajv); - * const validator = new AjvJsonSchemaValidator(ajv); - * ``` - */ - constructor(ajv) { - this._ajv = ajv !== null && ajv !== void 0 ? ajv : createDefaultAjvInstance(); - } - /** - * Create a validator for the given JSON Schema - * - * The validator is compiled once and can be reused multiple times. - * If the schema has an $id, it will be cached by AJV automatically. - * - * @param schema - Standard JSON Schema object - * @returns A validator function that validates input data - */ - getValidator(schema) { - var _a; - // Check if schema has $id and is already compiled/cached - const ajvValidator = '$id' in schema && typeof schema.$id === 'string' - ? ((_a = this._ajv.getSchema(schema.$id)) !== null && _a !== void 0 ? _a : this._ajv.compile(schema)) - : this._ajv.compile(schema); - return (input) => { - const valid = ajvValidator(input); - if (valid) { - return { - valid: true, - data: input, - errorMessage: undefined - }; - } - else { - return { - valid: false, - data: undefined, - errorMessage: this._ajv.errorsText(ajvValidator.errors) - }; - } - }; - } -} -//# sourceMappingURL=ajv-provider.js.map \ No newline at end of file diff --git a/dist/esm/validation/ajv-provider.js.map b/dist/esm/validation/ajv-provider.js.map deleted file mode 100644 index ce7e5d0c95..0000000000 --- a/dist/esm/validation/ajv-provider.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"ajv-provider.js","sourceRoot":"","sources":["../../../src/validation/ajv-provider.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAC1B,OAAO,WAAW,MAAM,aAAa,CAAC;AAGtC,SAAS,wBAAwB;IAC7B,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC;QAChB,MAAM,EAAE,KAAK;QACb,eAAe,EAAE,IAAI;QACrB,cAAc,EAAE,KAAK;QACrB,SAAS,EAAE,IAAI;KAClB,CAAC,CAAC;IAEH,MAAM,UAAU,GAAG,WAAoD,CAAC;IACxE,UAAU,CAAC,GAAG,CAAC,CAAC;IAEhB,OAAO,GAAG,CAAC;AACf,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,OAAO,sBAAsB;IAG/B;;;;;;;;;;;;;;;;;;;OAmBG;IACH,YAAY,GAAS;QACjB,IAAI,CAAC,IAAI,GAAG,GAAG,aAAH,GAAG,cAAH,GAAG,GAAI,wBAAwB,EAAE,CAAC;IAClD,CAAC;IAED;;;;;;;;OAQG;IACH,YAAY,CAAI,MAAsB;;QAClC,yDAAyD;QACzD,MAAM,YAAY,GACd,KAAK,IAAI,MAAM,IAAI,OAAO,MAAM,CAAC,GAAG,KAAK,QAAQ;YAC7C,CAAC,CAAC,CAAC,MAAA,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,mCAAI,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;YAChE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAEpC,OAAO,CAAC,KAAc,EAAgC,EAAE;YACpD,MAAM,KAAK,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;YAElC,IAAI,KAAK,EAAE,CAAC;gBACR,OAAO;oBACH,KAAK,EAAE,IAAI;oBACX,IAAI,EAAE,KAAU;oBAChB,YAAY,EAAE,SAAS;iBAC1B,CAAC;YACN,CAAC;iBAAM,CAAC;gBACJ,OAAO;oBACH,KAAK,EAAE,KAAK;oBACZ,IAAI,EAAE,SAAS;oBACf,YAAY,EAAE,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,YAAY,CAAC,MAAM,CAAC;iBAC1D,CAAC;YACN,CAAC;QACL,CAAC,CAAC;IACN,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/validation/cfworker-provider.d.ts b/dist/esm/validation/cfworker-provider.d.ts deleted file mode 100644 index 89c244a609..0000000000 --- a/dist/esm/validation/cfworker-provider.d.ts +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Cloudflare Worker-compatible JSON Schema validator provider - * - * This provider uses @cfworker/json-schema for validation without code generation, - * making it compatible with edge runtimes like Cloudflare Workers that restrict - * eval and new Function. - */ -import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from './types.js'; -/** - * JSON Schema draft version supported by @cfworker/json-schema - */ -export type CfWorkerSchemaDraft = '4' | '7' | '2019-09' | '2020-12'; -/** - * - * @example - * ```typescript - * // Use with default configuration (2020-12, shortcircuit) - * const validator = new CfWorkerJsonSchemaValidator(); - * - * // Use with custom configuration - * const validator = new CfWorkerJsonSchemaValidator({ - * draft: '2020-12', - * shortcircuit: false // Report all errors - * }); - * ``` - */ -export declare class CfWorkerJsonSchemaValidator implements jsonSchemaValidator { - private shortcircuit; - private draft; - /** - * Create a validator - * - * @param options - Configuration options - * @param options.shortcircuit - If true, stop validation after first error (default: true) - * @param options.draft - JSON Schema draft version to use (default: '2020-12') - */ - constructor(options?: { - shortcircuit?: boolean; - draft?: CfWorkerSchemaDraft; - }); - /** - * Create a validator for the given JSON Schema - * - * Unlike AJV, this validator is not cached internally - * - * @param schema - Standard JSON Schema object - * @returns A validator function that validates input data - */ - getValidator(schema: JsonSchemaType): JsonSchemaValidator; -} -//# sourceMappingURL=cfworker-provider.d.ts.map \ No newline at end of file diff --git a/dist/esm/validation/cfworker-provider.d.ts.map b/dist/esm/validation/cfworker-provider.d.ts.map deleted file mode 100644 index ce404d92fc..0000000000 --- a/dist/esm/validation/cfworker-provider.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"cfworker-provider.d.ts","sourceRoot":"","sources":["../../../src/validation/cfworker-provider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,mBAAmB,EAA6B,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtH;;GAEG;AACH,MAAM,MAAM,mBAAmB,GAAG,GAAG,GAAG,GAAG,GAAG,SAAS,GAAG,SAAS,CAAC;AAEpE;;;;;;;;;;;;;GAaG;AACH,qBAAa,2BAA4B,YAAW,mBAAmB;IACnE,OAAO,CAAC,YAAY,CAAU;IAC9B,OAAO,CAAC,KAAK,CAAsB;IAEnC;;;;;;OAMG;gBACS,OAAO,CAAC,EAAE;QAAE,YAAY,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,mBAAmB,CAAA;KAAE;IAK7E;;;;;;;OAOG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC;CAsBlE"} \ No newline at end of file diff --git a/dist/esm/validation/cfworker-provider.js b/dist/esm/validation/cfworker-provider.js deleted file mode 100644 index d55ef011e3..0000000000 --- a/dist/esm/validation/cfworker-provider.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * Cloudflare Worker-compatible JSON Schema validator provider - * - * This provider uses @cfworker/json-schema for validation without code generation, - * making it compatible with edge runtimes like Cloudflare Workers that restrict - * eval and new Function. - */ -import { Validator } from '@cfworker/json-schema'; -/** - * - * @example - * ```typescript - * // Use with default configuration (2020-12, shortcircuit) - * const validator = new CfWorkerJsonSchemaValidator(); - * - * // Use with custom configuration - * const validator = new CfWorkerJsonSchemaValidator({ - * draft: '2020-12', - * shortcircuit: false // Report all errors - * }); - * ``` - */ -export class CfWorkerJsonSchemaValidator { - /** - * Create a validator - * - * @param options - Configuration options - * @param options.shortcircuit - If true, stop validation after first error (default: true) - * @param options.draft - JSON Schema draft version to use (default: '2020-12') - */ - constructor(options) { - var _a, _b; - this.shortcircuit = (_a = options === null || options === void 0 ? void 0 : options.shortcircuit) !== null && _a !== void 0 ? _a : true; - this.draft = (_b = options === null || options === void 0 ? void 0 : options.draft) !== null && _b !== void 0 ? _b : '2020-12'; - } - /** - * Create a validator for the given JSON Schema - * - * Unlike AJV, this validator is not cached internally - * - * @param schema - Standard JSON Schema object - * @returns A validator function that validates input data - */ - getValidator(schema) { - const cfSchema = schema; - const validator = new Validator(cfSchema, this.draft, this.shortcircuit); - return (input) => { - const result = validator.validate(input); - if (result.valid) { - return { - valid: true, - data: input, - errorMessage: undefined - }; - } - else { - return { - valid: false, - data: undefined, - errorMessage: result.errors.map(err => `${err.instanceLocation}: ${err.error}`).join('; ') - }; - } - }; - } -} -//# sourceMappingURL=cfworker-provider.js.map \ No newline at end of file diff --git a/dist/esm/validation/cfworker-provider.js.map b/dist/esm/validation/cfworker-provider.js.map deleted file mode 100644 index 0f0e1799f8..0000000000 --- a/dist/esm/validation/cfworker-provider.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"cfworker-provider.js","sourceRoot":"","sources":["../../../src/validation/cfworker-provider.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAe,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAQ/D;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO,2BAA2B;IAIpC;;;;;;OAMG;IACH,YAAY,OAAiE;;QACzE,IAAI,CAAC,YAAY,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,YAAY,mCAAI,IAAI,CAAC;QAClD,IAAI,CAAC,KAAK,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,KAAK,mCAAI,SAAS,CAAC;IAC7C,CAAC;IAED;;;;;;;OAOG;IACH,YAAY,CAAI,MAAsB;QAClC,MAAM,QAAQ,GAAG,MAA2B,CAAC;QAC7C,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC,QAAQ,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,YAAY,CAAC,CAAC;QAEzE,OAAO,CAAC,KAAc,EAAgC,EAAE;YACpD,MAAM,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;YAEzC,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;gBACf,OAAO;oBACH,KAAK,EAAE,IAAI;oBACX,IAAI,EAAE,KAAU;oBAChB,YAAY,EAAE,SAAS;iBAC1B,CAAC;YACN,CAAC;iBAAM,CAAC;gBACJ,OAAO;oBACH,KAAK,EAAE,KAAK;oBACZ,IAAI,EAAE,SAAS;oBACf,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,gBAAgB,KAAK,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;iBAC7F,CAAC;YACN,CAAC;QACL,CAAC,CAAC;IACN,CAAC;CACJ"} \ No newline at end of file diff --git a/dist/esm/validation/index.d.ts b/dist/esm/validation/index.d.ts deleted file mode 100644 index 99e993967f..0000000000 --- a/dist/esm/validation/index.d.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** - * JSON Schema validation - * - * This module provides configurable JSON Schema validation for the MCP SDK. - * Choose a validator based on your runtime environment: - * - * - AjvJsonSchemaValidator: Best for Node.js (default, fastest) - * Import from: @modelcontextprotocol/sdk/validation/ajv - * Requires peer dependencies: ajv, ajv-formats - * - * - CfWorkerJsonSchemaValidator: Best for edge runtimes - * Import from: @modelcontextprotocol/sdk/validation/cfworker - * Requires peer dependency: @cfworker/json-schema - * - * @example - * ```typescript - * // For Node.js with AJV - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // For Cloudflare Workers - * import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker'; - * const validator = new CfWorkerJsonSchemaValidator(); - * ``` - * - * @module validation - */ -export type { JsonSchemaType, JsonSchemaValidator, JsonSchemaValidatorResult, jsonSchemaValidator } from './types.js'; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/dist/esm/validation/index.d.ts.map b/dist/esm/validation/index.d.ts.map deleted file mode 100644 index a8845b96e7..0000000000 --- a/dist/esm/validation/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/validation/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAGH,YAAY,EAAE,cAAc,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC"} \ No newline at end of file diff --git a/dist/esm/validation/index.js b/dist/esm/validation/index.js deleted file mode 100644 index 685b1fd45f..0000000000 --- a/dist/esm/validation/index.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * JSON Schema validation - * - * This module provides configurable JSON Schema validation for the MCP SDK. - * Choose a validator based on your runtime environment: - * - * - AjvJsonSchemaValidator: Best for Node.js (default, fastest) - * Import from: @modelcontextprotocol/sdk/validation/ajv - * Requires peer dependencies: ajv, ajv-formats - * - * - CfWorkerJsonSchemaValidator: Best for edge runtimes - * Import from: @modelcontextprotocol/sdk/validation/cfworker - * Requires peer dependency: @cfworker/json-schema - * - * @example - * ```typescript - * // For Node.js with AJV - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // For Cloudflare Workers - * import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker'; - * const validator = new CfWorkerJsonSchemaValidator(); - * ``` - * - * @module validation - */ -export {}; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/esm/validation/index.js.map b/dist/esm/validation/index.js.map deleted file mode 100644 index ed2b9fc234..0000000000 --- a/dist/esm/validation/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/validation/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG"} \ No newline at end of file diff --git a/dist/esm/validation/types.d.ts b/dist/esm/validation/types.d.ts deleted file mode 100644 index 5872215c78..0000000000 --- a/dist/esm/validation/types.d.ts +++ /dev/null @@ -1,55 +0,0 @@ -import type { Schema } from '@cfworker/json-schema'; -/** - * Result of a JSON Schema validation operation - */ -export type JsonSchemaValidatorResult = { - valid: true; - data: T; - errorMessage: undefined; -} | { - valid: false; - data: undefined; - errorMessage: string; -}; -/** - * A validator function that validates data against a JSON Schema - */ -export type JsonSchemaValidator = (input: unknown) => JsonSchemaValidatorResult; -/** - * Provider interface for creating validators from JSON Schemas - * - * This is the main extension point for custom validator implementations. - * Implementations should: - * - Support JSON Schema Draft 2020-12 (or be compatible with it) - * - Return validator functions that can be called multiple times - * - Handle schema compilation/caching internally - * - Provide clear error messages on validation failure - * - * @example - * ```typescript - * class MyValidatorProvider implements jsonSchemaValidator { - * getValidator(schema: JsonSchemaType): JsonSchemaValidator { - * // Compile/cache validator from schema - * return (input: unknown) => { - * // Validate input against schema - * if (valid) { - * return { valid: true, data: input as T, errorMessage: undefined }; - * } else { - * return { valid: false, data: undefined, errorMessage: 'Error details' }; - * } - * }; - * } - * } - * ``` - */ -export interface jsonSchemaValidator { - /** - * Create a validator for the given JSON Schema - * - * @param schema - Standard JSON Schema object - * @returns A validator function that can be called multiple times - */ - getValidator(schema: JsonSchemaType): JsonSchemaValidator; -} -export type JsonSchemaType = Schema; -//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dist/esm/validation/types.d.ts.map b/dist/esm/validation/types.d.ts.map deleted file mode 100644 index 3bdf64e589..0000000000 --- a/dist/esm/validation/types.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/validation/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAEpD;;GAEG;AACH,MAAM,MAAM,yBAAyB,CAAC,CAAC,IACjC;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,IAAI,EAAE,CAAC,CAAC;IAAC,YAAY,EAAE,SAAS,CAAA;CAAE,GACjD;IAAE,KAAK,EAAE,KAAK,CAAC;IAAC,IAAI,EAAE,SAAS,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC;AAE9D;;GAEG;AACH,MAAM,MAAM,mBAAmB,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,KAAK,yBAAyB,CAAC,CAAC,CAAC,CAAC;AAEtF;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,MAAM,WAAW,mBAAmB;IAChC;;;;;OAKG;IACH,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE,cAAc,GAAG,mBAAmB,CAAC,CAAC,CAAC,CAAC;CACnE;AAED,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/dist/esm/validation/types.js b/dist/esm/validation/types.js deleted file mode 100644 index 718fd38ae4..0000000000 --- a/dist/esm/validation/types.js +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dist/esm/validation/types.js.map b/dist/esm/validation/types.js.map deleted file mode 100644 index 51361cf6a4..0000000000 --- a/dist/esm/validation/types.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/validation/types.ts"],"names":[],"mappings":""} \ No newline at end of file From d210b1fa41890fffa0fae3ff52b1370155786634 Mon Sep 17 00:00:00 2001 From: Mikko Kutilainen Date: Sat, 22 Nov 2025 22:24:22 +0200 Subject: [PATCH 4/9] dev --- .gitignore | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index 397351de25..a1b83bc4fa 100644 --- a/.gitignore +++ b/.gitignore @@ -129,9 +129,7 @@ out .pnp.* .DS_Store - -# Include dist for npm -# dist/ +dist/ # IDE .idea/ From af3edd7e1742d46e5303fe40feabec58d2d570b3 Mon Sep 17 00:00:00 2001 From: Mikko Kutilainen Date: Mon, 8 Dec 2025 07:36:20 +0200 Subject: [PATCH 5/9] fix securitySchemes --- src/server/mcp.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/server/mcp.ts b/src/server/mcp.ts index 9a1653ba30..ed41e21a3e 100644 --- a/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -157,6 +157,7 @@ export class McpServer { : EMPTY_OBJECT_JSON_SCHEMA; })(), annotations: tool.annotations, + securitySchemes: tool.securitySchemes, execution: tool.execution, _meta: tool._meta }; From a7f143ee54a4f6d650c80f919f992803448ed379 Mon Sep 17 00:00:00 2001 From: Mikko Kutilainen Date: Mon, 8 Dec 2025 07:54:12 +0200 Subject: [PATCH 6/9] add test --- test/server/mcp.test.ts | 46 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/test/server/mcp.test.ts b/test/server/mcp.test.ts index f6c2124e13..3464bb2527 100644 --- a/test/server/mcp.test.ts +++ b/test/server/mcp.test.ts @@ -814,6 +814,50 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { }); }); + /*** + * Test: Tool Registration with securitySchemes + */ + test('should register tool with securitySchemes and include it in list response', async () => { + const mcpServer = new McpServer({ + name: 'test server', + version: '1.0' + }); + const client = new Client({ + name: 'test client', + version: '1.0' + }); + + mcpServer.registerTool( + 'secure-tool', + { + description: 'A tool with security schemes', + securitySchemes: [ + { type: 'oauth2', scopes: ['read', 'write'] }, + { type: 'noauth' } + ] + }, + async () => ({ + content: [{ type: 'text', text: 'Secure response' }] + }) + ); + + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + + await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); + + const result = await client.request( + { method: 'tools/list' }, + ListToolsResultSchema + ); + + expect(result.tools).toHaveLength(1); + expect(result.tools[0].name).toBe('secure-tool'); + expect(result.tools[0].securitySchemes).toEqual([ + { type: 'oauth2', scopes: ['read', 'write'] }, + { type: 'noauth' } + ]); + }); + /*** * Test: Tool Registration with Parameters and Annotations */ @@ -2009,7 +2053,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { }); // Spy on console.warn to verify warnings are logged - const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => { }); // Test valid tool names testServer.registerTool( From 6dd08ac60804f30fd3c4ff71d60699c1fcbf5f68 Mon Sep 17 00:00:00 2001 From: Felix Weinberger <3823880+felixweinberger@users.noreply.github.com> Date: Fri, 19 Dec 2025 14:45:13 +0100 Subject: [PATCH 7/9] ci: trigger workflow on v1.x branch (#1319) --- .github/workflows/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 60144add12..b92f67d815 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -1,7 +1,7 @@ on: push: branches: - - main + - v1.x pull_request: workflow_dispatch: release: From a0c9b13484748acab9e5dc8317a7e89c06b52e37 Mon Sep 17 00:00:00 2001 From: Anton Pidkuiko <105124934+antonpk1@users.noreply.github.com> Date: Fri, 19 Dec 2025 23:47:16 +0700 Subject: [PATCH 8/9] fix: README badges links destinations (#907) Co-authored-by: Claude Co-authored-by: Felix Weinberger <3823880+felixweinberger@users.noreply.github.com> --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e0d3f200f4..254671c8f3 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# MCP TypeScript SDK ![NPM Version](https://img.shields.io/npm/v/%40modelcontextprotocol%2Fsdk) ![MIT licensed](https://img.shields.io/npm/l/%40modelcontextprotocol%2Fsdk) +# MCP TypeScript SDK [![NPM Version](https://img.shields.io/npm/v/%40modelcontextprotocol%2Fsdk)](https://www.npmjs.com/package/@modelcontextprotocol/sdk) [![MIT licensed](https://img.shields.io/npm/l/%40modelcontextprotocol%2Fsdk)](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/LICENSE)
Table of Contents From 0ec7d89efd2ae4c1b1ac20eeef4a3b64177648db Mon Sep 17 00:00:00 2001 From: Mikko Kutilainen Date: Tue, 6 Jan 2026 15:09:13 +0200 Subject: [PATCH 9/9] Revert "Merge branch 'main' into feature/security-schemes" This reverts commit da0c8a368d2316baa696a04d9d19a4ed8854c3b0, reversing changes made to a7f143ee54a4f6d650c80f919f992803448ed379. --- .changeset/README.md | 6 - .changeset/config.json | 11 - .changeset/tender-snails-fold.md | 6 - .github/workflows/main.yml | 53 +- .github/workflows/publish.yml | 30 +- .github/workflows/release.yml | 45 - .github/workflows/update-spec-types.yml | 26 +- CLAUDE.md | 73 +- CONTRIBUTING.md | 45 +- README.md | 176 +- common/eslint-config/eslint.config.mjs | 81 - common/eslint-config/package.json | 36 - common/tsconfig/package.json | 21 - common/vitest-config/package.json | 28 - common/vitest-config/tsconfig.json | 8 - common/vitest-config/vitest.config.js | 25 - docs/capabilities.md | 16 +- docs/client.md | 22 +- docs/faq.md | 21 +- docs/server.md | 73 +- eslint.config.mjs | 34 + examples/client/README.md | 52 - examples/client/eslint.config.mjs | 14 - examples/client/package.json | 48 - examples/client/tsconfig.json | 17 - examples/client/tsdown.config.ts | 25 - examples/client/vitest.config.js | 3 - examples/server/README.md | 173 - examples/server/eslint.config.mjs | 14 - examples/server/package.json | 53 - .../src/honoWebStandardStreamableHttp.ts | 73 - examples/server/tsconfig.json | 17 - examples/server/tsdown.config.ts | 25 - examples/server/vitest.config.js | 3 - examples/shared/eslint.config.mjs | 14 - examples/shared/package.json | 57 - examples/shared/src/index.ts | 1 - examples/shared/tsconfig.json | 20 - examples/shared/vitest.config.js | 3 - package-lock.json | 37 +- package.json | 154 +- packages/client/eslint.config.mjs | 12 - packages/client/package.json | 88 - packages/client/src/experimental/index.ts | 13 - packages/client/src/index.ts | 14 - packages/client/tsconfig.json | 12 - packages/client/tsdown.config.ts | 34 - packages/client/vitest.config.js | 8 - packages/core/eslint.config.mjs | 5 - packages/core/package.json | 76 - packages/core/src/experimental/index.ts | 3 - packages/core/src/exports/types/index.ts | 1 - packages/core/src/types/spec.types.ts | 2552 ------- packages/core/tsconfig.json | 12 - packages/core/vitest.config.js | 3 - packages/server/eslint.config.mjs | 12 - packages/server/package.json | 97 - .../server/src/experimental/tasks/index.ts | 13 - .../src/experimental/tasks/interfaces.ts | 49 - packages/server/src/index.ts | 17 - packages/server/src/server/auth/index.ts | 12 - packages/server/src/server/streamableHttp.ts | 189 - .../src/server/webStandardStreamableHttp.ts | 994 --- packages/server/tsconfig.json | 12 - packages/server/tsdown.config.ts | 34 - packages/server/vitest.config.js | 3 - pnpm-lock.yaml | 6136 ----------------- pnpm-workspace.yaml | 55 - scripts/fetch-spec-types.ts | 6 +- .../__fixtures__/serverThatHangs.ts | 6 +- .../test => src}/__fixtures__/testServer.ts | 3 +- .../__fixtures__/zodTestMatrix.ts | 0 src/__mocks__/pkce-challenge.ts | 6 + .../src => src}/client/auth-extensions.ts | 7 +- {packages/client/src => src}/client/auth.ts | 48 +- .../client/client.ts => src/client/index.ts | 116 +- .../client/src => src}/client/middleware.ts | 6 +- {packages/client/src => src}/client/sse.ts | 12 +- {packages/client/src => src}/client/stdio.ts | 13 +- .../src => src}/client/streamableHttp.ts | 21 +- .../client/src => src}/client/websocket.ts | 4 +- src/examples/README.md | 352 + .../examples/client}/elicitationUrlExample.ts | 44 +- .../client}/multipleClientsParallel.ts | 10 +- .../client}/parallelToolCallsClient.ts | 11 +- .../client}/simpleClientCredentials.ts | 6 +- .../examples/client}/simpleOAuthClient.ts | 17 +- .../client}/simpleOAuthClientProvider.ts | 3 +- .../examples/client}/simpleStreamableHttp.ts | 45 +- .../client}/simpleTaskInteractiveClient.ts | 19 +- .../examples/client}/ssePollingClient.ts | 11 +- .../streamableHttpWithSseFallbackClient.ts | 15 +- .../server}/README-simpleTaskInteractive.md | 38 +- .../server}/demoInMemoryOAuthProvider.ts | 21 +- .../server}/elicitationFormExample.ts | 10 +- .../examples/server}/elicitationUrlExample.ts | 36 +- .../server}/jsonResponseStreamableHttp.ts | 25 +- .../examples/server}/mcpServerOutputSchema.ts | 3 +- .../examples/server}/simpleSseServer.ts | 20 +- .../server}/simpleStatelessStreamableHttp.ts | 28 +- .../examples/server}/simpleStreamableHttp.ts | 78 +- .../examples/server}/simpleTaskInteractive.ts | 58 +- .../sseAndStreamableHttpCompatibleServer.ts | 39 +- .../examples/server}/ssePollingExample.ts | 14 +- .../standaloneSseWithGetStreamableHttp.ts | 11 +- .../examples/server}/toolWithSampleServer.ts | 5 +- .../examples/shared}/inMemoryEventStore.ts | 5 +- .../server/src => src}/experimental/index.ts | 0 .../src => src}/experimental/tasks/client.ts | 24 +- .../src => src}/experimental/tasks/helpers.ts | 0 src/experimental/tasks/index.ts | 34 + .../experimental/tasks/interfaces.ts | 68 +- .../experimental/tasks/mcp-server.ts | 8 +- .../src => src}/experimental/tasks/server.ts | 20 +- .../experimental/tasks/stores/in-memory.ts | 6 +- src/experimental/tasks/types.ts | 43 + {packages/core/src/util => src}/inMemory.ts | 5 +- .../server/src => src}/server/auth/clients.ts | 2 +- .../core/src => src/server}/auth/errors.ts | 38 +- .../server/auth/handlers/authorize.ts | 18 +- .../server/auth/handlers/metadata.ts | 6 +- .../server/auth/handlers/register.ts | 20 +- .../server/auth/handlers/revoke.ts | 20 +- .../src => src}/server/auth/handlers/token.ts | 27 +- .../server/auth/middleware/allowedMethods.ts | 4 +- .../server/auth/middleware/bearerAuth.ts | 11 +- .../server/auth/middleware/clientAuth.ts | 9 +- .../src => src}/server/auth/provider.ts | 8 +- .../server/auth/providers/proxyProvider.ts | 19 +- .../server/src => src}/server/auth/router.ts | 20 +- src/server/auth/types.ts | 36 + .../server/src => src}/server/completable.ts | 2 +- .../server/src => src}/server/express.ts | 4 +- .../server/server.ts => src/server/index.ts | 97 +- {packages/server/src => src}/server/mcp.ts | 110 +- .../server/middleware/hostHeaderValidation.ts | 2 +- {packages/server/src => src}/server/sse.ts | 12 +- {packages/server/src => src}/server/stdio.ts | 8 +- src/server/streamableHttp.ts | 956 +++ .../src/util => src/server}/zod-compat.ts | 15 +- .../server}/zod-json-schema-compat.ts | 6 +- .../core/src => src}/shared/auth-utils.ts | 0 {packages/core/src => src}/shared/auth.ts | 0 .../core/src => src}/shared/metadataUtils.ts | 2 +- {packages/core/src => src}/shared/protocol.ts | 111 +- .../src => src}/shared/responseMessage.ts | 2 +- {packages/core/src => src}/shared/stdio.ts | 3 +- .../src => src}/shared/toolNameValidation.ts | 0 .../core/src => src}/shared/transport.ts | 4 +- .../core/src => src}/shared/uriTemplate.ts | 8 +- src/spec.types.ts | 2285 ++++++ {packages/core/src/types => src}/types.ts | 607 +- .../src => src}/validation/ajv-provider.ts | 3 +- .../validation/cfworker-provider.ts | 3 +- .../core/src => src/validation}/index.ts | 21 +- .../core/src => src}/validation/types.ts | 0 .../client/auth-extensions.test.ts | 11 +- .../client/test => test}/client/auth.test.ts | 144 +- .../test => test}/client/cross-spawn.test.ts | 10 +- .../client.test.ts => client/index.test.ts} | 131 +- .../test => test}/client/middleware.test.ts | 47 +- .../client/test => test}/client/sse.test.ts | 31 +- .../client/test => test}/client/stdio.test.ts | 10 +- .../client/streamableHttp.test.ts | 33 +- .../server}/demoInMemoryOAuthProvider.test.ts | 15 +- .../tasks/stores}/in-memory.test.ts | 45 +- .../experimental/tasks/task-listing.test.ts | 9 +- .../test => }/experimental/tasks/task.test.ts | 6 +- test/helpers/eslint.config.mjs | 5 - test/helpers/{src/helpers => }/http.ts | 18 +- test/{integration/test => }/helpers/mcp.ts | 9 +- test/helpers/{src/helpers => }/oauth.ts | 12 +- test/helpers/package.json | 42 - test/helpers/src/fixtures/zodTestMatrix.ts | 22 - test/helpers/src/index.ts | 4 - test/helpers/{src/helpers => }/tasks.ts | 2 +- test/helpers/tsconfig.json | 14 - test/helpers/vitest.config.js | 3 - {packages/core/test => test}/inMemory.test.ts | 5 +- .../processCleanup.test.ts | 11 +- .../stateManagementStreamableHttp.test.ts | 22 +- .../taskLifecycle.test.ts | 46 +- .../taskResumability.test.ts | 55 +- test/integration/eslint.config.mjs | 5 - test/integration/package.json | 46 - .../test_1277_zod_v4_description.test.ts | 64 - test/integration/tsconfig.json | 15 - test/integration/vitest.config.js | 3 - .../server/auth/handlers/authorize.test.ts | 32 +- .../server/auth/handlers/metadata.test.ts | 5 +- .../server/auth/handlers/register.test.ts | 10 +- .../server/auth/handlers/revoke.test.ts | 18 +- .../server/auth/handlers/token.test.ts | 20 +- .../auth/middleware/allowedMethods.test.ts | 6 +- .../server/auth/middleware/bearerAuth.test.ts | 13 +- .../server/auth/middleware/clientAuth.test.ts | 8 +- .../auth/providers/proxyProvider.test.ts | 15 +- .../test => test}/server/auth/router.test.ts | 19 +- .../test => test}/server/completable.test.ts | 3 +- .../test => }/server/elicitation.test.ts | 10 +- .../server.test.ts => server/index.test.ts} | 47 +- .../{integration/test => }/server/mcp.test.ts | 206 +- .../server/test => test}/server/sse.test.ts | 15 +- .../server/test => test}/server/stdio.test.ts | 10 +- .../server/streamableHttp.test.ts | 183 +- .../test => server}/title.test.ts | 51 +- .../test => test}/shared/auth-utils.test.ts | 2 +- .../core/test => test}/shared/auth.test.ts | 6 +- .../protocol-transport-handling.test.ts | 9 +- .../test => test}/shared/protocol.test.ts | 159 +- .../core/test => test}/shared/stdio.test.ts | 2 +- .../shared/toolNameValidation.test.ts | 6 +- .../test => test}/shared/uriTemplate.test.ts | 0 .../core/test => test}/spec.types.test.ts | 253 +- .../test => test}/types.capabilities.test.ts | 2 +- {packages/core/test => test}/types.test.ts | 36 +- .../validation/validation.test.ts | 0 tsconfig.cjs.json | 10 + .../tsconfig/tsconfig.json => tsconfig.json | 20 +- tsconfig.prod.json | 8 + vitest.config.ts | 10 + .../client/vitest.setup.js => vitest.setup.ts | 3 +- vitest.workspace.js | 3 - 223 files changed, 5961 insertions(+), 14108 deletions(-) delete mode 100644 .changeset/README.md delete mode 100644 .changeset/config.json delete mode 100644 .changeset/tender-snails-fold.md delete mode 100644 .github/workflows/release.yml delete mode 100644 common/eslint-config/eslint.config.mjs delete mode 100644 common/eslint-config/package.json delete mode 100644 common/tsconfig/package.json delete mode 100644 common/vitest-config/package.json delete mode 100644 common/vitest-config/tsconfig.json delete mode 100644 common/vitest-config/vitest.config.js create mode 100644 eslint.config.mjs delete mode 100644 examples/client/README.md delete mode 100644 examples/client/eslint.config.mjs delete mode 100644 examples/client/package.json delete mode 100644 examples/client/tsconfig.json delete mode 100644 examples/client/tsdown.config.ts delete mode 100644 examples/client/vitest.config.js delete mode 100644 examples/server/README.md delete mode 100644 examples/server/eslint.config.mjs delete mode 100644 examples/server/package.json delete mode 100644 examples/server/src/honoWebStandardStreamableHttp.ts delete mode 100644 examples/server/tsconfig.json delete mode 100644 examples/server/tsdown.config.ts delete mode 100644 examples/server/vitest.config.js delete mode 100644 examples/shared/eslint.config.mjs delete mode 100644 examples/shared/package.json delete mode 100644 examples/shared/src/index.ts delete mode 100644 examples/shared/tsconfig.json delete mode 100644 examples/shared/vitest.config.js delete mode 100644 packages/client/eslint.config.mjs delete mode 100644 packages/client/package.json delete mode 100644 packages/client/src/experimental/index.ts delete mode 100644 packages/client/src/index.ts delete mode 100644 packages/client/tsconfig.json delete mode 100644 packages/client/tsdown.config.ts delete mode 100644 packages/client/vitest.config.js delete mode 100644 packages/core/eslint.config.mjs delete mode 100644 packages/core/package.json delete mode 100644 packages/core/src/experimental/index.ts delete mode 100644 packages/core/src/exports/types/index.ts delete mode 100644 packages/core/src/types/spec.types.ts delete mode 100644 packages/core/tsconfig.json delete mode 100644 packages/core/vitest.config.js delete mode 100644 packages/server/eslint.config.mjs delete mode 100644 packages/server/package.json delete mode 100644 packages/server/src/experimental/tasks/index.ts delete mode 100644 packages/server/src/experimental/tasks/interfaces.ts delete mode 100644 packages/server/src/index.ts delete mode 100644 packages/server/src/server/auth/index.ts delete mode 100644 packages/server/src/server/streamableHttp.ts delete mode 100644 packages/server/src/server/webStandardStreamableHttp.ts delete mode 100644 packages/server/tsconfig.json delete mode 100644 packages/server/tsdown.config.ts delete mode 100644 packages/server/vitest.config.js delete mode 100644 pnpm-lock.yaml delete mode 100644 pnpm-workspace.yaml rename {test/integration/test => src}/__fixtures__/serverThatHangs.ts (90%) rename {test/integration/test => src}/__fixtures__/testServer.ts (74%) rename {packages/server/test/server => src}/__fixtures__/zodTestMatrix.ts (100%) create mode 100644 src/__mocks__/pkce-challenge.ts rename {packages/client/src => src}/client/auth-extensions.ts (98%) rename {packages/client/src => src}/client/auth.ts (98%) rename packages/client/src/client/client.ts => src/client/index.ts (95%) rename {packages/client/src => src}/client/middleware.ts (98%) rename {packages/client/src => src}/client/sse.ts (95%) rename {packages/client/src => src}/client/stdio.ts (96%) rename {packages/client/src => src}/client/streamableHttp.ts (97%) rename {packages/client/src => src}/client/websocket.ts (93%) create mode 100644 src/examples/README.md rename {examples/client/src => src/examples/client}/elicitationUrlExample.ts (98%) rename {examples/client/src => src/examples/client}/multipleClientsParallel.ts (95%) rename {examples/client/src => src/examples/client}/parallelToolCallsClient.ts (97%) rename {examples/client/src => src/examples/client}/simpleClientCredentials.ts (89%) rename {examples/client/src => src/examples/client}/simpleOAuthClient.ts (97%) rename {examples/client/src => src/examples/client}/simpleOAuthClientProvider.ts (91%) rename {examples/client/src => src/examples/client}/simpleStreamableHttp.ts (98%) rename {examples/client/src => src/examples/client}/simpleTaskInteractiveClient.ts (95%) rename {examples/client/src => src/examples/client}/ssePollingClient.ts (92%) rename {examples/client/src => src/examples/client}/streamableHttpWithSseFallbackClient.ts (95%) rename {examples/server/src => src/examples/server}/README-simpleTaskInteractive.md (79%) rename {examples/shared/src => src/examples/server}/demoInMemoryOAuthProvider.ts (93%) rename {examples/server/src => src/examples/server}/elicitationFormExample.ts (97%) rename {examples/server/src => src/examples/server}/elicitationUrlExample.ts (96%) rename {examples/server/src => src/examples/server}/jsonResponseStreamableHttp.ts (89%) rename {examples/server/src => src/examples/server}/mcpServerOutputSchema.ts (95%) rename {examples/server/src => src/examples/server}/simpleSseServer.ts (89%) rename {examples/server/src => src/examples/server}/simpleStatelessStreamableHttp.ts (83%) rename {examples/server/src => src/examples/server}/simpleStreamableHttp.ts (93%) rename {examples/server/src => src/examples/server}/simpleTaskInteractive.ts (96%) rename {examples/server/src => src/examples/server}/sseAndStreamableHttpCompatibleServer.ts (89%) rename {examples/server/src => src/examples/server}/ssePollingExample.ts (91%) rename {examples/server/src => src/examples/server}/standaloneSseWithGetStreamableHttp.ts (92%) rename {examples/server/src => src/examples/server}/toolWithSampleServer.ts (89%) rename {examples/server/src => src/examples/shared}/inMemoryEventStore.ts (93%) rename {packages/server/src => src}/experimental/index.ts (100%) rename {packages/client/src => src}/experimental/tasks/client.ts (94%) rename {packages/core/src => src}/experimental/tasks/helpers.ts (100%) create mode 100644 src/experimental/tasks/index.ts rename {packages/core/src => src}/experimental/tasks/interfaces.ts (83%) rename {packages/server/src => src}/experimental/tasks/mcp-server.ts (94%) rename {packages/server/src => src}/experimental/tasks/server.ts (91%) rename {packages/core/src => src}/experimental/tasks/stores/in-memory.ts (97%) create mode 100644 src/experimental/tasks/types.ts rename {packages/core/src/util => src}/inMemory.ts (93%) rename {packages/server/src => src}/server/auth/clients.ts (93%) rename {packages/core/src => src/server}/auth/errors.ts (84%) rename {packages/server/src => src}/server/auth/handlers/authorize.ts (91%) rename {packages/server/src => src}/server/auth/handlers/metadata.ts (76%) rename {packages/server/src => src}/server/auth/handlers/register.ts (89%) rename {packages/server/src => src}/server/auth/handlers/revoke.ts (86%) rename {packages/server/src => src}/server/auth/handlers/token.ts (94%) rename {packages/server/src => src}/server/auth/middleware/allowedMethods.ts (86%) rename {packages/server/src => src}/server/auth/middleware/bearerAuth.ts (93%) rename {packages/server/src => src}/server/auth/middleware/clientAuth.ts (88%) rename {packages/server/src => src}/server/auth/provider.ts (92%) rename {packages/server/src => src}/server/auth/providers/proxyProvider.ts (93%) rename {packages/server/src => src}/server/auth/router.ts (91%) create mode 100644 src/server/auth/types.ts rename {packages/server/src => src}/server/completable.ts (96%) rename {packages/server/src => src}/server/express.ts (97%) rename packages/server/src/server/server.ts => src/server/index.ts (94%) rename {packages/server/src => src}/server/mcp.ts (99%) rename {packages/server/src => src}/server/middleware/hostHeaderValidation.ts (96%) rename {packages/server/src => src}/server/sse.ts (96%) rename {packages/server/src => src}/server/stdio.ts (92%) create mode 100644 src/server/streamableHttp.ts rename {packages/core/src/util => src/server}/zod-compat.ts (96%) rename {packages/core/src/util => src/server}/zod-json-schema-compat.ts (93%) rename {packages/core/src => src}/shared/auth-utils.ts (100%) rename {packages/core/src => src}/shared/auth.ts (100%) rename {packages/core/src => src}/shared/metadataUtils.ts (94%) rename {packages/core/src => src}/shared/protocol.ts (97%) rename {packages/core/src => src}/shared/responseMessage.ts (96%) rename {packages/core/src => src}/shared/stdio.ts (89%) rename {packages/core/src => src}/shared/toolNameValidation.ts (100%) rename {packages/core/src => src}/shared/transport.ts (95%) rename {packages/core/src => src}/shared/uriTemplate.ts (98%) create mode 100644 src/spec.types.ts rename {packages/core/src/types => src}/types.ts (85%) rename {packages/core/src => src}/validation/ajv-provider.ts (96%) rename {packages/core/src => src}/validation/cfworker-provider.ts (95%) rename {packages/core/src => src/validation}/index.ts (54%) rename {packages/core/src => src}/validation/types.ts (100%) rename {packages/client/test => test}/client/auth-extensions.test.ts (97%) rename {packages/client/test => test}/client/auth.test.ts (96%) rename {packages/client/test => test}/client/cross-spawn.test.ts (94%) rename test/{integration/test/client/client.test.ts => client/index.test.ts} (97%) rename {packages/client/test => test}/client/middleware.test.ts (96%) rename {packages/client/test => test}/client/sse.test.ts (98%) rename {packages/client/test => test}/client/stdio.test.ts (86%) rename {packages/client/test => test}/client/streamableHttp.test.ts (98%) rename {examples/shared/test => test/examples/server}/demoInMemoryOAuthProvider.test.ts (96%) rename {packages/core/test/experimental => test/experimental/tasks/stores}/in-memory.test.ts (95%) rename test/{integration/test => }/experimental/tasks/task-listing.test.ts (94%) rename test/{integration/test => }/experimental/tasks/task.test.ts (95%) delete mode 100644 test/helpers/eslint.config.mjs rename test/helpers/{src/helpers => }/http.ts (85%) rename test/{integration/test => }/helpers/mcp.ts (82%) rename test/helpers/{src/helpers => }/oauth.ts (90%) delete mode 100644 test/helpers/package.json delete mode 100644 test/helpers/src/fixtures/zodTestMatrix.ts delete mode 100644 test/helpers/src/index.ts rename test/helpers/{src/helpers => }/tasks.ts (94%) delete mode 100644 test/helpers/tsconfig.json delete mode 100644 test/helpers/vitest.config.js rename {packages/core/test => test}/inMemory.test.ts (95%) rename test/{integration/test => integration-tests}/processCleanup.test.ts (89%) rename test/{integration/test => integration-tests}/stateManagementStreamableHttp.test.ts (96%) rename test/{integration/test => integration-tests}/taskLifecycle.test.ts (97%) rename test/{integration/test => integration-tests}/taskResumability.test.ts (85%) delete mode 100644 test/integration/eslint.config.mjs delete mode 100644 test/integration/package.json delete mode 100644 test/integration/test/issues/test_1277_zod_v4_description.test.ts delete mode 100644 test/integration/tsconfig.json delete mode 100644 test/integration/vitest.config.js rename {packages/server/test => test}/server/auth/handlers/authorize.test.ts (90%) rename {packages/server/test => test}/server/auth/handlers/metadata.test.ts (97%) rename {packages/server/test => test}/server/auth/handlers/register.test.ts (96%) rename {packages/server/test => test}/server/auth/handlers/revoke.test.ts (92%) rename {packages/server/test => test}/server/auth/handlers/token.test.ts (96%) rename {packages/server/test => test}/server/auth/middleware/allowedMethods.test.ts (96%) rename {packages/server/test => test}/server/auth/middleware/bearerAuth.test.ts (98%) rename {packages/server/test => test}/server/auth/middleware/clientAuth.test.ts (92%) rename {packages/server/test => test}/server/auth/providers/proxyProvider.test.ts (95%) rename {packages/server/test => test}/server/auth/router.test.ts (96%) rename {packages/server/test => test}/server/completable.test.ts (93%) rename test/{integration/test => }/server/elicitation.test.ts (98%) rename test/{integration/test/server.test.ts => server/index.test.ts} (98%) rename test/{integration/test => }/server/mcp.test.ts (97%) rename {packages/server/test => test}/server/sse.test.ts (98%) rename {packages/server/test => test}/server/stdio.test.ts (90%) rename {packages/server/test => test}/server/streamableHttp.test.ts (95%) rename test/{integration/test => server}/title.test.ts (80%) rename {packages/core/test => test}/shared/auth-utils.test.ts (98%) rename {packages/core/test => test}/shared/auth.test.ts (99%) rename {packages/core/test => test}/shared/protocol-transport-handling.test.ts (96%) rename {packages/core/test => test}/shared/protocol.test.ts (97%) rename {packages/core/test => test}/shared/stdio.test.ts (94%) rename {packages/core/test => test}/shared/toolNameValidation.test.ts (97%) rename {packages/core/test => test}/shared/uriTemplate.test.ts (100%) rename {packages/core/test => test}/spec.types.test.ts (66%) rename {packages/core/test => test}/types.capabilities.test.ts (99%) rename {packages/core/test => test}/types.test.ts (98%) rename {packages/core/test => test}/validation/validation.test.ts (100%) create mode 100644 tsconfig.cjs.json rename common/tsconfig/tsconfig.json => tsconfig.json (51%) create mode 100644 tsconfig.prod.json create mode 100644 vitest.config.ts rename packages/client/vitest.setup.js => vitest.setup.ts (70%) delete mode 100644 vitest.workspace.js diff --git a/.changeset/README.md b/.changeset/README.md deleted file mode 100644 index 8385205249..0000000000 --- a/.changeset/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# Changesets - -Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works with multi-package repos, or single-package repos to help you version and publish your code. You can find the full documentation for it -[in our repository](https://github.com/changesets/changesets) - -We have a quick list of common questions to get you started engaging with this project in [our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md) diff --git a/.changeset/config.json b/.changeset/config.json deleted file mode 100644 index bae546e8e1..0000000000 --- a/.changeset/config.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "$schema": "https://unpkg.com/@changesets/config@3.1.2/schema.json", - "changelog": ["@changesets/changelog-github", { "repo": "modelcontextprotocol/typescript-sdk" }], - "commit": false, - "fixed": [], - "linked": [], - "access": "public", - "baseBranch": "main", - "updateInternalDependencies": "patch", - "ignore": ["@modelcontextprotocol/examples-client", "@modelcontextprotocol/examples-server", "@modelcontextprotocol/examples-shared"] -} diff --git a/.changeset/tender-snails-fold.md b/.changeset/tender-snails-fold.md deleted file mode 100644 index 138596950c..0000000000 --- a/.changeset/tender-snails-fold.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -'@modelcontextprotocol/client': patch -'@modelcontextprotocol/server': patch ---- - -Initial 2.0.0-alpha.0 client and server package diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 495ca55814..60144add12 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -16,47 +16,32 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 - - - name: Install pnpm - uses: pnpm/action-setup@v4 - id: pnpm-install - with: - run_install: false - - uses: actions/setup-node@v6 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version: 24 - cache: pnpm - cache-dependency-path: pnpm-lock.yaml + cache: npm - - run: pnpm install - - run: pnpm run check:all - - run: pnpm run build:all + - run: npm ci + - run: npm run check + - run: npm run build test: runs-on: ubuntu-latest strategy: fail-fast: false matrix: - node-version: [20, 22, 24] + node-version: [18, 24] steps: - - uses: actions/checkout@v6 - - - name: Install pnpm - uses: pnpm/action-setup@v4 - id: pnpm-install - with: - run_install: false - - uses: actions/setup-node@v6 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} - cache: pnpm - cache-dependency-path: pnpm-lock.yaml - - - run: pnpm install + cache: npm - - run: pnpm test:all + - run: npm ci + - run: npm test publish: runs-on: ubuntu-latest @@ -70,19 +55,13 @@ jobs: steps: - uses: actions/checkout@v4 - - - name: Install pnpm - uses: pnpm/action-setup@v4 - id: pnpm-install - with: - run_install: false - uses: actions/setup-node@v4 with: node-version: 24 - cache: pnpm - cache-dependency-path: pnpm-lock.yaml + cache: npm registry-url: 'https://registry.npmjs.org' - - run: pnpm install + + - run: npm ci - name: Determine npm tag id: npm-tag @@ -105,6 +84,6 @@ jobs: echo "tag=" >> $GITHUB_OUTPUT fi - - run: pnpm publish --provenance --access public ${{ steps.npm-tag.outputs.tag }} + - run: npm publish --provenance --access public ${{ steps.npm-tag.outputs.tag }} env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 1167b176ad..00ffd6efe5 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,8 +1,6 @@ name: Publish Any Commit - permissions: contents: read - on: pull_request: push: @@ -16,26 +14,14 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v6 - - - name: Install pnpm - uses: pnpm/action-setup@v4 - with: - run_install: false - - - name: Setup Node.js - uses: actions/setup-node@v6 + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 with: node-version: 24 - cache: pnpm - cache-dependency-path: pnpm-lock.yaml - registry-url: 'https://registry.npmjs.org' - - - name: Install dependencies - run: pnpm install - - - name: Build packages - run: pnpm run build:all + cache: npm - - name: Publish preview packages - run: pnpm dlx pkg-pr-new publish --packageManager=npm --pnpm './packages/server' './packages/client' + - run: npm ci + - name: Build + run: npm run build + - name: Publish + run: npx pkg-pr-new publish diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index ed0b1061b8..0000000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,45 +0,0 @@ -name: Release - -permissions: - contents: write - pull-requests: write - -on: - push: - branches: - - main - -concurrency: ${{ github.workflow }}-${{ github.ref }} - -jobs: - release: - name: Release - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - - - name: Install pnpm - uses: pnpm/action-setup@v4 - with: - run_install: false - - - name: Setup Node.js - uses: actions/setup-node@v6 - with: - node-version: 24 - cache: pnpm - cache-dependency-path: pnpm-lock.yaml - registry-url: 'https://registry.npmjs.org' - - - name: Install dependencies - run: pnpm install - - - name: Create Release Pull Request or Publish to npm - id: changesets - uses: changesets/action@v1 - with: - publish: pnpm run build:all && pnpm changeset publish - env: - GITHUB_TOKEN: ${{ github.token }} - NPM_TOKEN: ${{ secrets.NPM_TOKEN }} - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} diff --git a/.github/workflows/update-spec-types.yml b/.github/workflows/update-spec-types.yml index 4a54f76c50..dbc00ebd51 100644 --- a/.github/workflows/update-spec-types.yml +++ b/.github/workflows/update-spec-types.yml @@ -15,35 +15,27 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout repository - uses: actions/checkout@v6 - - - name: Install pnpm - uses: pnpm/action-setup@v4 - id: pnpm-install - with: - run_install: false + uses: actions/checkout@v4 - name: Setup Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@v4 with: - node-version: 24 - cache: pnpm - cache-dependency-path: pnpm-lock.yaml + node-version: '24' - name: Install dependencies - run: pnpm install + run: npm ci - name: Fetch latest spec types - run: pnpm run fetch:spec-types + run: npm run fetch:spec-types - name: Check for changes id: check_changes run: | - if git diff --quiet packages/core/src/types/spec.types.ts; then + if git diff --quiet src/spec.types.ts; then echo "has_changes=false" >> $GITHUB_OUTPUT else echo "has_changes=true" >> $GITHUB_OUTPUT - LATEST_SHA=$(grep "Last updated from commit:" packages/core/src/types/spec.types.ts | cut -d: -f2 | tr -d ' ') + LATEST_SHA=$(grep "Last updated from commit:" src/spec.types.ts | cut -d: -f2 | tr -d ' ') echo "sha=$LATEST_SHA" >> $GITHUB_OUTPUT fi @@ -56,12 +48,12 @@ jobs: git config user.email "github-actions[bot]@users.noreply.github.com" git checkout -B update-spec-types - git add packages/core/src/types/spec.types.ts + git add src/spec.types.ts git commit -m "chore: update spec.types.ts from upstream" git push -f origin update-spec-types # Create PR if it doesn't exist, or update if it does - PR_BODY="This PR updates \`packages/core/src/types/spec.types.ts\` from the Model Context Protocol specification. + PR_BODY="This PR updates \`src/spec.types.ts\` from the Model Context Protocol specification. Source file: https://github.com/modelcontextprotocol/modelcontextprotocol/blob/${{ steps.check_changes.outputs.sha }}/schema/draft/schema.ts diff --git a/CLAUDE.md b/CLAUDE.md index 2a0b253a6c..6e768e559f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -5,21 +5,14 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Build & Test Commands ```sh -pnpm install # Install all workspace dependencies - -pnpm build:all # Build all packages -pnpm lint:all # Run ESLint + Prettier checks across all packages -pnpm lint:fix:all # Auto-fix lint and formatting issues across all packages -pnpm typecheck:all # Type-check all packages -pnpm test:all # Run all tests (vitest) across all packages -pnpm check:all # typecheck + lint across all packages - -# Run a single package script (examples) -# Run a single package script from the repo root with pnpm filter -pnpm --filter @modelcontextprotocol/core test # vitest run (core) -pnpm --filter @modelcontextprotocol/core test:watch # vitest (watch) -pnpm --filter @modelcontextprotocol/core test -- path/to/file.test.ts -pnpm --filter @modelcontextprotocol/core test -- -t "test name" +npm run build # Build ESM and CJS versions +npm run lint # Run ESLint and Prettier check +npm run lint:fix # Auto-fix lint and formatting issues +npm test # Run all tests (vitest) +npm run test:watch # Run tests in watch mode +npx vitest path/to/file.test.ts # Run specific test file +npx vitest -t "test name" # Run tests matching pattern +npm run typecheck # Type-check without emitting ``` ## Code Style Guidelines @@ -38,64 +31,64 @@ pnpm --filter @modelcontextprotocol/core test -- -t "test name" The SDK is organized into three main layers: -1. **Types Layer** (`packages/core/src/types/types.ts`) - Protocol types generated from the MCP specification. All JSON-RPC message types, schemas, and protocol constants are defined here using Zod v4. +1. **Types Layer** (`src/types.ts`) - Protocol types generated from the MCP specification. All JSON-RPC message types, schemas, and protocol constants are defined here using Zod v4. -2. **Protocol Layer** (`packages/core/src/shared/protocol.ts`) - The abstract `Protocol` class that handles JSON-RPC message routing, request/response correlation, capability negotiation, and transport management. Both `Client` and `Server` extend this class. +2. **Protocol Layer** (`src/shared/protocol.ts`) - The abstract `Protocol` class that handles JSON-RPC message routing, request/response correlation, capability negotiation, and transport management. Both `Client` and `Server` extend this class. 3. **High-Level APIs**: - - `Client` (`packages/client/src/client/client.ts`) - Client implementation extending Protocol with typed methods for MCP operations - - `Server` (`packages/server/src/server/server.ts`) - Server implementation extending Protocol with request handler registration - - `McpServer` (`packages/server/src/server/mcp.ts`) - High-level server API with simplified resource/tool/prompt registration + - `Client` (`src/client/index.ts`) - Low-level client extending Protocol with typed methods for all MCP operations + - `Server` (`src/server/index.ts`) - Low-level server extending Protocol with request handler registration + - `McpServer` (`src/server/mcp.ts`) - High-level server API with simplified resource/tool/prompt registration ### Transport System -Transports (`packages/core/src/shared/transport.ts`) provide the communication layer: +Transports (`src/shared/transport.ts`) provide the communication layer: -- **Streamable HTTP** (`packages/server/src/server/streamableHttp.ts`, `packages/client/src/client/streamableHttp.ts`) - Recommended transport for remote servers, supports SSE for streaming -- **SSE** (`packages/server/src/server/sse.ts`, `packages/client/src/client/sse.ts`) - Legacy HTTP+SSE transport for backwards compatibility -- **stdio** (`packages/server/src/server/stdio.ts`, `packages/client/src/client/stdio.ts`) - For local process-spawned integrations +- **Streamable HTTP** (`src/server/streamableHttp.ts`, `src/client/streamableHttp.ts`) - Recommended transport for remote servers, supports SSE for streaming +- **SSE** (`src/server/sse.ts`, `src/client/sse.ts`) - Legacy HTTP+SSE transport for backwards compatibility +- **stdio** (`src/server/stdio.ts`, `src/client/stdio.ts`) - For local process-spawned integrations ### Server-Side Features - **Tools/Resources/Prompts**: Registered via `McpServer.tool()`, `.resource()`, `.prompt()` methods -- **OAuth/Auth**: Full OAuth 2.0 server implementation in `packages/server/src/server/auth/` -- **Completions**: Auto-completion support via `packages/server/src/server/completable.ts` +- **OAuth/Auth**: Full OAuth 2.0 server implementation in `src/server/auth/` +- **Completions**: Auto-completion support via `src/server/completable.ts` ### Client-Side Features -- **Auth**: OAuth client support in `packages/client/src/client/auth.ts` and `packages/client/src/client/auth-extensions.ts` -- **Middleware**: Request middleware in `packages/client/src/client/middleware.ts` +- **Auth**: OAuth client support in `src/client/auth.ts` and `src/client/auth-extensions.ts` +- **Middleware**: Request middleware in `src/client/middleware.ts` - **Sampling**: Clients can handle `sampling/createMessage` requests from servers (LLM completions) - **Elicitation**: Clients can handle `elicitation/create` requests for user input (form or URL mode) - **Roots**: Clients can expose filesystem roots to servers via `roots/list` ### Experimental Features -Located in `packages/*/src/experimental/`: +Located in `src/experimental/`: -- **Tasks**: Long-running task support with polling/resumption (`packages/core/src/experimental/tasks/`) +- **Tasks**: Long-running task support with polling/resumption (`src/experimental/tasks/`) ### Zod Compatibility The SDK uses `zod/v4` internally but supports both v3 and v4 APIs. Compatibility utilities: -- `packages/core/src/util/zod-compat.ts` - Schema parsing helpers that work across versions -- `packages/core/src/util/zod-json-schema-compat.ts` - Converts Zod schemas to JSON Schema +- `src/server/zod-compat.ts` - Schema parsing helpers that work across versions +- `src/server/zod-json-schema-compat.ts` - Converts Zod schemas to JSON Schema ### Validation -Pluggable JSON Schema validation (`packages/core/src/validation/`): +Pluggable JSON Schema validation (`src/validation/`): - `ajv-provider.ts` - Default Ajv-based validator - `cfworker-provider.ts` - Cloudflare Workers-compatible alternative ### Examples -Runnable examples in `examples/`: +Runnable examples in `src/examples/`: -- `examples/server/src/` - Various server configurations (stateful, stateless, OAuth, etc.) -- `examples/client/src/` - Client examples (basic, OAuth, parallel calls, etc.) -- `examples/shared/src/` - Shared utilities (OAuth demo provider, etc.) +- `server/` - Various server configurations (stateful, stateless, OAuth, etc.) +- `client/` - Client examples (basic, OAuth, parallel calls, etc.) +- `shared/` - Shared utilities like in-memory event store ## Message Flow (Bidirectional Protocol) @@ -105,9 +98,9 @@ MCP is bidirectional: both client and server can send requests. Understanding th ``` Protocol (abstract base) -├── Client (packages/client/src/client/client.ts) - can send requests TO server, handle requests FROM server -└── Server (packages/server/src/server/server.ts) - can send requests TO client, handle requests FROM client - └── McpServer (packages/server/src/server/mcp.ts) - high-level wrapper around Server +├── Client (src/client/index.ts) - can send requests TO server, handle requests FROM server +└── Server (src/server/index.ts) - can send requests TO client, handle requests FROM client + └── McpServer (src/server/mcp.ts) - high-level wrapper around Server ``` ### Outbound Flow: Sending Requests diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 64c8ab1401..ace9542dbf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,40 +2,20 @@ We welcome contributions to the Model Context Protocol TypeScript SDK! This document outlines the process for contributing to the project. -## Branches - -This repository has two main branches: - -- **`main`** – v2 of the SDK (currently in development). This is a monorepo with split packages. -- **`v1.x`** – stable v1 release. Bug fixes and patches for v1 should target this branch. - -**Which branch should I use as a base?** - -- For **new features** or **v2-related work**: base your PR on `main` -- For **v1 bug fixes** or **patches**: base your PR on `v1.x` - ## Getting Started -This project uses [pnpm](https://pnpm.io/) as its package manager. If you don't have pnpm installed, enable it via [corepack](https://nodejs.org/api/corepack.html) (included with Node.js 16.9+): - -```bash -corepack enable -``` - -Then: - 1. Fork the repository 2. Clone your fork: `git clone https://github.com/YOUR-USERNAME/typescript-sdk.git` -3. Install dependencies: `pnpm install` -4. Build the project: `pnpm build:all` -5. Run tests: `pnpm test:all` +3. Install dependencies: `npm install` +4. Build the project: `npm run build` +5. Run tests: `npm test` ## Development Process -1. Create a new branch for your changes (based on `main` or `v1.x` as appropriate) +1. Create a new branch for your changes 2. Make your changes -3. Run `pnpm lint:all` to ensure code style compliance -4. Run `pnpm test:all` to verify all tests pass +3. Run `npm run lint` to ensure code style compliance +4. Run `npm test` to verify all tests pass 5. Submit a pull request ## Pull Request Guidelines @@ -48,17 +28,8 @@ Then: ## Running Examples -See [`examples/server/README.md`](examples/server/README.md) and [`examples/client/README.md`](examples/client/README.md) for a full list of runnable examples. - -Quick start: - -```bash -# Run a server example -pnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts - -# Run a client example (in another terminal) -pnpm --filter @modelcontextprotocol/examples-client exec tsx src/simpleStreamableHttp.ts -``` +- Start the server: `npm run server` +- Run the client: `npm run client` ## Code of Conduct diff --git a/README.md b/README.md index dc0116c96b..e0d3f200f4 100644 --- a/README.md +++ b/README.md @@ -1,21 +1,13 @@ -# MCP TypeScript SDK - -> [!IMPORTANT] -> **This is the `main` branch which contains v2 of the SDK (currently in development, pre-alpha).** -> -> We anticipate a stable v2 release in Q1 2026. Until then, **v1.x remains the recommended version** for production use. v1.x will continue to receive bug fixes and security updates for at least 6 months after v2 ships to give people time to upgrade. -> -> For v1 documentation and code, see the [`v1.x` branch](https://github.com/modelcontextprotocol/typescript-sdk/tree/v1.x). - -![NPM Version](https://img.shields.io/npm/v/%40modelcontextprotocol%2Fserver) ![NPM Version](https://img.shields.io/npm/v/%40modelcontextprotocol%2Fclient) ![MIT licensed](https://img.shields.io/npm/l/%40modelcontextprotocol%2Fserver) +# MCP TypeScript SDK ![NPM Version](https://img.shields.io/npm/v/%40modelcontextprotocol%2Fsdk) ![MIT licensed](https://img.shields.io/npm/l/%40modelcontextprotocol%2Fsdk)
Table of Contents - [Overview](#overview) -- [Packages](#packages) - [Installation](#installation) -- [Quick Start (runnable examples)](#quick-start-runnable-examples) +- [Quick Start](#quick-start) +- [Core Concepts](#core-concepts) +- [Examples](#examples) - [Documentation](#documentation) - [Contributing](#contributing) - [License](#license) @@ -24,83 +16,142 @@ ## Overview -The Model Context Protocol (MCP) allows applications to provide context for LLMs in a standardized way, separating the concerns of providing context from the actual LLM interaction. +The Model Context Protocol allows applications to provide context for LLMs in a standardized way, separating the concerns of providing context from the actual LLM interaction. This TypeScript SDK implements +[the full MCP specification](https://modelcontextprotocol.io/specification/draft), making it easy to: -This repository contains the TypeScript SDK implementation of the MCP specification and ships: +- Create MCP servers that expose resources, prompts and tools +- Build MCP clients that can connect to any MCP server +- Use standard transports like stdio and Streamable HTTP -- MCP **server** libraries (tools/resources/prompts, Streamable HTTP, stdio, auth helpers) -- MCP **client** libraries (transports, high-level helpers, OAuth helpers) -- Runnable **examples** (under [`examples/`](examples/)) +## Installation -## Packages +```bash +npm install @modelcontextprotocol/sdk zod +``` -This monorepo publishes split packages: +This SDK has a **required peer dependency** on `zod` for schema validation. The SDK internally imports from `zod/v4`, but maintains backwards compatibility with projects using Zod v3.25 or later. You can use either API in your code by importing from `zod/v3` or `zod/v4`: -- **`@modelcontextprotocol/server`**: build MCP servers -- **`@modelcontextprotocol/client`**: build MCP clients +## Quick Start -Both packages have a **required peer dependency** on `zod` for schema validation. The SDK internally imports from `zod/v4`, but remains compatible with projects using Zod v3.25+. +To see the SDK in action end-to-end, start from the runnable examples in `src/examples`: -## Installation +1. **Install dependencies** (from the SDK repo root): -### Server + ```bash + npm install + ``` -```bash -npm install @modelcontextprotocol/server zod -``` +2. **Run the example Streamable HTTP server**: -### Client + ```bash + npx tsx src/examples/server/simpleStreamableHttp.ts + ``` -```bash -npm install @modelcontextprotocol/client zod -``` +3. **Run the interactive client in another terminal**: -## Quick Start (runnable examples) + ```bash + npx tsx src/examples/client/simpleStreamableHttp.ts + ``` -The runnable examples live under `examples/` and are kept in sync with the docs. +This pair of examples demonstrates tools, resources, prompts, sampling, elicitation, tasks and logging. For a guided walkthrough and variations (stateless servers, JSON-only responses, SSE compatibility, OAuth, etc.), see [docs/server.md](docs/server.md) and +[docs/client.md](docs/client.md). -1. **Install dependencies** (from repo root): +## Core Concepts -```bash -pnpm install -``` +### Servers and transports -2. **Run a Streamable HTTP example server**: +An MCP server is typically created with `McpServer` and connected to a transport such as Streamable HTTP or stdio. The SDK supports: -```bash -pnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts -``` +- **Streamable HTTP** for remote servers (recommended). +- **HTTP + SSE** for backwards compatibility only. +- **stdio** for local, process-spawned integrations. -Alternatively, from within the example package: +Runnable server examples live under `src/examples/server` and are documented in [docs/server.md](docs/server.md). -```bash -cd examples/server -pnpm tsx src/simpleStreamableHttp.ts -``` +### Tools, resources, prompts -3. **Run the interactive client in another terminal**: +- **Tools** let LLMs ask your server to take actions (computation, side effects, network calls). +- **Resources** expose read-only data that clients can surface to users or models. +- **Prompts** are reusable templates that help users talk to models in a consistent way. -```bash -pnpm --filter @modelcontextprotocol/examples-client exec tsx src/simpleStreamableHttp.ts -``` +The detailed APIs, including `ResourceTemplate`, completions, and display-name metadata, are covered in [docs/server.md](docs/server.md#tools-resources-and-prompts), with runnable implementations in [`simpleStreamableHttp.ts`](src/examples/server/simpleStreamableHttp.ts). -Alternatively, from within the example package: +### Capabilities: sampling, elicitation, and tasks -```bash -cd examples/client -pnpm tsx src/simpleStreamableHttp.ts -``` +The SDK includes higher-level capabilities for richer workflows: -Next steps: +- **Sampling**: server-side tools can ask connected clients to run LLM completions. +- **Form elicitation**: tools can request non-sensitive input via structured forms. +- **URL elicitation**: servers can ask users to complete secure flows in a browser (e.g., API key entry, payments, OAuth). +- **Tasks (experimental)**: long-running tool calls can be turned into tasks that you poll or resume later. -- Server examples index: [`examples/server/README.md`](examples/server/README.md) -- Client examples index: [`examples/client/README.md`](examples/client/README.md) -- Guided walkthroughs: [`docs/server.md`](docs/server.md) and [`docs/client.md`](docs/client.md) +Conceptual overviews and links to runnable examples are in: + +- [docs/capabilities.md](docs/capabilities.md) + +Key example servers include: + +- [`toolWithSampleServer.ts`](src/examples/server/toolWithSampleServer.ts) +- [`elicitationFormExample.ts`](src/examples/server/elicitationFormExample.ts) +- [`elicitationUrlExample.ts`](src/examples/server/elicitationUrlExample.ts) + +### Clients + +The high-level `Client` class connects to MCP servers over different transports and exposes helpers like `listTools`, `callTool`, `listResources`, `readResource`, `listPrompts`, and `getPrompt`. + +Runnable clients live under `src/examples/client` and are described in [docs/client.md](docs/client.md), including: + +- Interactive Streamable HTTP client ([`simpleStreamableHttp.ts`](src/examples/client/simpleStreamableHttp.ts)) +- Streamable HTTP client with SSE fallback ([`streamableHttpWithSseFallbackClient.ts`](src/examples/client/streamableHttpWithSseFallbackClient.ts)) +- OAuth-enabled clients and polling/parallel examples + +### Node.js Web Crypto (globalThis.crypto) compatibility + +Some parts of the SDK (for example, JWT-based client authentication in `auth-extensions.ts` via `jose`) rely on the Web Crypto API exposed as `globalThis.crypto`. + +See [docs/faq.md](docs/faq.md) for details on supported Node.js versions and how to polyfill `globalThis.crypto` when running on older Node.js runtimes. + +## Examples + +The SDK ships runnable examples under `src/examples`. Use these tables to find the scenario you care about and jump straight to the corresponding code and docs. + +### Server examples + +| Scenario | Description | Example file(s) | Related docs | +| --------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | +| Streamable HTTP server (stateful) | Feature-rich server with tools, resources, prompts, logging, tasks, sampling, and optional OAuth. | [`simpleStreamableHttp.ts`](src/examples/server/simpleStreamableHttp.ts) | [`server.md`](docs/server.md), [`capabilities.md`](docs/capabilities.md) | +| Streamable HTTP server (stateless) | No session tracking; good for simple API-style servers. | [`simpleStatelessStreamableHttp.ts`](src/examples/server/simpleStatelessStreamableHttp.ts) | [`server.md`](docs/server.md) | +| JSON response mode (no SSE) | Streamable HTTP with JSON responses only and limited notifications. | [`jsonResponseStreamableHttp.ts`](src/examples/server/jsonResponseStreamableHttp.ts) | [`server.md`](docs/server.md) | +| Server notifications over Streamable HTTP | Demonstrates server-initiated notifications using SSE with Streamable HTTP. | [`standaloneSseWithGetStreamableHttp.ts`](src/examples/server/standaloneSseWithGetStreamableHttp.ts) | [`server.md`](docs/server.md) | +| Deprecated HTTP+SSE server | Legacy HTTP+SSE transport for backwards-compatibility testing. | [`simpleSseServer.ts`](src/examples/server/simpleSseServer.ts) | [`server.md`](docs/server.md) | +| Backwards-compatible server (Streamable HTTP + SSE) | Single server that supports both Streamable HTTP and legacy SSE clients. | [`sseAndStreamableHttpCompatibleServer.ts`](src/examples/server/sseAndStreamableHttpCompatibleServer.ts) | [`server.md`](docs/server.md) | +| Form elicitation server | Uses form elicitation to collect non-sensitive user input. | [`elicitationFormExample.ts`](src/examples/server/elicitationFormExample.ts) | [`capabilities.md`](docs/capabilities.md#elicitation) | +| URL elicitation server | Demonstrates URL-mode elicitation in an OAuth-protected server. | [`elicitationUrlExample.ts`](src/examples/server/elicitationUrlExample.ts) | [`capabilities.md`](docs/capabilities.md#elicitation) | +| Sampling and tasks server | Combines tools, logging, sampling, and experimental task-based execution. | [`toolWithSampleServer.ts`](src/examples/server/toolWithSampleServer.ts) | [`capabilities.md`](docs/capabilities.md) | +| OAuth demo authorization server | In-memory OAuth provider used with the example servers. | [`demoInMemoryOAuthProvider.ts`](src/examples/server/demoInMemoryOAuthProvider.ts) | [`server.md`](docs/server.md) | + +### Client examples + +| Scenario | Description | Example file(s) | Related docs | +| --------------------------------------------------- | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ | +| Interactive Streamable HTTP client | CLI client that exercises tools, resources, prompts, elicitation, and tasks. | [`simpleStreamableHttp.ts`](src/examples/client/simpleStreamableHttp.ts) | [`client.md`](docs/client.md) | +| Backwards-compatible client (Streamable HTTP → SSE) | Tries Streamable HTTP first, then falls back to SSE on 4xx responses. | [`streamableHttpWithSseFallbackClient.ts`](src/examples/client/streamableHttpWithSseFallbackClient.ts) | [`client.md`](docs/client.md), [`server.md`](docs/server.md) | +| SSE polling client | Polls a legacy SSE server and demonstrates notification handling. | [`ssePollingClient.ts`](src/examples/client/ssePollingClient.ts) | [`client.md`](docs/client.md) | +| Parallel tool calls client | Shows how to run multiple tool calls in parallel. | [`parallelToolCallsClient.ts`](src/examples/client/parallelToolCallsClient.ts) | [`client.md`](docs/client.md) | +| Multiple clients in parallel | Demonstrates connecting multiple clients concurrently to the same server. | [`multipleClientsParallel.ts`](src/examples/client/multipleClientsParallel.ts) | [`client.md`](docs/client.md) | +| OAuth clients | Examples of client_credentials (basic and private_key_jwt) and reusable providers. | [`simpleOAuthClient.ts`](src/examples/client/simpleOAuthClient.ts), [`simpleOAuthClientProvider.ts`](src/examples/client/simpleOAuthClientProvider.ts), [`simpleClientCredentials.ts`](src/examples/client/simpleClientCredentials.ts) | [`client.md`](docs/client.md) | +| URL elicitation client | Works with the URL elicitation server to drive secure browser flows. | [`elicitationUrlExample.ts`](src/examples/client/elicitationUrlExample.ts) | [`capabilities.md`](docs/capabilities.md#elicitation) | + +Shared utilities: + +- In-memory event store for resumability: [`inMemoryEventStore.ts`](src/examples/shared/inMemoryEventStore.ts) (see [`server.md`](docs/server.md)). + +For more details on how to run these examples (including recommended commands and deployment diagrams), see `src/examples/README.md`. ## Documentation - Local SDK docs: - - [docs/server.md](docs/server.md) – building MCP servers, transports, tools/resources/prompts, CORS, DNS rebinding, and deployment patterns. + - [docs/server.md](docs/server.md) – building and running MCP servers, transports, tools/resources/prompts, CORS, DNS rebinding, and multi-node deployment. - [docs/client.md](docs/client.md) – using the high-level client, transports, backwards compatibility, and OAuth helpers. - [docs/capabilities.md](docs/capabilities.md) – sampling, elicitation (form and URL), and experimental task-based execution. - [docs/faq.md](docs/faq.md) – environment and troubleshooting FAQs (including Node.js Web Crypto support). @@ -109,11 +160,6 @@ Next steps: - [MCP Specification](https://spec.modelcontextprotocol.io) - [Example Servers](https://github.com/modelcontextprotocol/servers) -## v1 (legacy) documentation and fixes - -If you are using the **v1** generation of the SDK, the **v1 documentation** (and any v1-specific fixes) live on the long-lived [`v1.x` branch](https://github.com/modelcontextprotocol/typescript-sdk/tree/v1.x). See: -[`https://github.com/modelcontextprotocol/typescript-sdk/tree/v1.x`](https://github.com/modelcontextprotocol/typescript-sdk/tree/v1.x). - ## Contributing Issues and pull requests are welcome on GitHub at . diff --git a/common/eslint-config/eslint.config.mjs b/common/eslint-config/eslint.config.mjs deleted file mode 100644 index 321f3f6fce..0000000000 --- a/common/eslint-config/eslint.config.mjs +++ /dev/null @@ -1,81 +0,0 @@ -// @ts-check -import path from 'node:path'; -import { fileURLToPath } from 'node:url'; - -import eslint from '@eslint/js'; -import { defineConfig } from 'eslint/config'; -import eslintConfigPrettier from 'eslint-config-prettier/flat'; -import importPlugin from 'eslint-plugin-import'; -import nodePlugin from 'eslint-plugin-n'; -import simpleImportSortPlugin from 'eslint-plugin-simple-import-sort'; -import { configs } from 'typescript-eslint'; - -const __dirname = path.dirname(fileURLToPath(import.meta.url)); - -export default defineConfig( - eslint.configs.recommended, - ...configs.recommended, - importPlugin.flatConfigs.recommended, - importPlugin.flatConfigs.typescript, - { - languageOptions: { - parserOptions: { - // Ensure consumers of this shared config get a stable tsconfig root - tsconfigRootDir: __dirname - } - }, - linterOptions: { - reportUnusedDisableDirectives: false - }, - plugins: { - n: nodePlugin, - 'simple-import-sort': simpleImportSortPlugin - }, - settings: { - 'import/resolver': { - typescript: { - // Let the TS resolver handle NodeNext-style imports like "./foo.js" - extensions: ['.js', '.jsx', '.ts', '.tsx', '.d.ts'], - // Use the tsconfig in each package root (when running ESLint from that package) - project: 'tsconfig.json' - } - } - }, - rules: { - '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }], - 'n/prefer-node-protocol': 'error', - '@typescript-eslint/consistent-type-imports': ['error', { disallowTypeAnnotations: false }], - 'simple-import-sort/imports': 'warn', - 'simple-import-sort/exports': 'warn', - 'import/no-extraneous-dependencies': [ - 'error', - { - devDependencies: [ - '**/test/**', - '**/*.test.ts', - '**/*.test.tsx', - '**/scripts/**', - '**/vitest.config.*', - '**/tsdown.config.*', - '**/eslint.config.*', - '**/vitest.setup.*' - ], - optionalDependencies: false, - peerDependencies: true - } - ] - } - }, - { - // Ignore generated protocol types everywhere - ignores: ['**/spec.types.ts'] - }, - { - files: ['packages/client/**/*.ts', 'packages/server/**/*.ts'], - ignores: ['**/*.test.ts'], - rules: { - 'no-console': 'error' - } - }, - eslintConfigPrettier -); diff --git a/common/eslint-config/package.json b/common/eslint-config/package.json deleted file mode 100644 index 30904a0fc2..0000000000 --- a/common/eslint-config/package.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "name": "@modelcontextprotocol/eslint-config", - "private": true, - "main": "eslint.config.mjs", - "type": "module", - "exports": { - ".": "./eslint.config.mjs" - }, - "dependencies": { - "typescript": "catalog:devTools" - }, - "repository": { - "type": "git", - "url": "https://github.com/modelcontextprotocol/typescript-sdk.git" - }, - "bugs": { - "url": "https://github.com/modelcontextprotocol/typescript-sdk/issues" - }, - "homepage": "https://github.com/modelcontextprotocol/typescript-sdk/tree/develop/common/eslint-config", - "publishConfig": { - "registry": "https://npm.pkg.github.com/" - }, - "version": "2.0.0", - "devDependencies": { - "@eslint/js": "catalog:devTools", - "eslint": "catalog:devTools", - "eslint-config-prettier": "catalog:devTools", - "eslint-import-resolver-typescript": "^4.4.4", - "eslint-plugin-import": "^2.32.0", - "eslint-plugin-n": "catalog:devTools", - "eslint-plugin-simple-import-sort": "^12.1.1", - "prettier": "catalog:devTools", - "typescript": "catalog:devTools", - "typescript-eslint": "catalog:devTools" - } -} diff --git a/common/tsconfig/package.json b/common/tsconfig/package.json deleted file mode 100644 index 7c62db2c57..0000000000 --- a/common/tsconfig/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "@modelcontextprotocol/tsconfig", - "private": true, - "main": "tsconfig.json", - "type": "module", - "dependencies": { - "typescript": "catalog:devTools" - }, - "repository": { - "type": "git", - "url": "https://github.com/modelcontextprotocol/typescript-sdk.git" - }, - "bugs": { - "url": "https://github.com/modelcontextprotocol/typescript-sdk/issues" - }, - "homepage": "https://github.com/modelcontextprotocol/typescript-sdk/tree/develop/common/ts-config", - "publishConfig": { - "registry": "https://npm.pkg.github.com/" - }, - "version": "2.0.0" -} diff --git a/common/vitest-config/package.json b/common/vitest-config/package.json deleted file mode 100644 index 3ae59937eb..0000000000 --- a/common/vitest-config/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "@modelcontextprotocol/vitest-config", - "private": true, - "main": "vitest.config.mjs", - "type": "module", - "exports": { - ".": "./vitest.config.js" - }, - "dependencies": { - "typescript": "catalog:devTools" - }, - "repository": { - "type": "git", - "url": "https://github.com/modelcontextprotocol/typescript-sdk.git" - }, - "bugs": { - "url": "https://github.com/modelcontextprotocol/typescript-sdk/issues" - }, - "homepage": "https://github.com/modelcontextprotocol/typescript-sdk/tree/develop/common/vitest-config", - "publishConfig": { - "registry": "https://npm.pkg.github.com/" - }, - "version": "2.0.0", - "devDependencies": { - "@modelcontextprotocol/tsconfig": "workspace:^", - "vite-tsconfig-paths": "catalog:devTools" - } -} diff --git a/common/vitest-config/tsconfig.json b/common/vitest-config/tsconfig.json deleted file mode 100644 index 6e58368d27..0000000000 --- a/common/vitest-config/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "include": ["./"], - "extends": "@modelcontextprotocol/tsconfig", - "compilerOptions": { - "noEmit": true, - "allowJs": true - } -} diff --git a/common/vitest-config/vitest.config.js b/common/vitest-config/vitest.config.js deleted file mode 100644 index 9d1a094e7e..0000000000 --- a/common/vitest-config/vitest.config.js +++ /dev/null @@ -1,25 +0,0 @@ -import { defineConfig } from 'vitest/config'; -import tsconfigPaths from 'vite-tsconfig-paths'; -import path from 'node:path'; -import url from 'node:url'; - -const ignorePatterns = ['**/dist/**']; -const __dirname = path.dirname(url.fileURLToPath(import.meta.url)); - -export default defineConfig({ - test: { - globals: true, - environment: 'node', - include: ['test/**/*.test.ts'], - exclude: ignorePatterns, - deps: { - moduleDirectories: ['node_modules', path.resolve(__dirname, '../../packages'), path.resolve(__dirname, '../../common')] - }, - poolOptions: { - threads: { - useAtomics: true - } - } - }, - plugins: [tsconfigPaths()] -}); diff --git a/docs/capabilities.md b/docs/capabilities.md index 21e309bc15..301e850fe8 100644 --- a/docs/capabilities.md +++ b/docs/capabilities.md @@ -4,7 +4,7 @@ MCP servers can request LLM completions from connected clients that support the For a runnable server that combines tools, logging and tasks, see: -- [`toolWithSampleServer.ts`](../examples/server/src/toolWithSampleServer.ts) +- [`toolWithSampleServer.ts`](../src/examples/server/toolWithSampleServer.ts) In practice you will: @@ -22,8 +22,8 @@ Form elicitation lets a tool ask the user for additional, **non‑sensitive** in Runnable example: -- Server: [`elicitationFormExample.ts`](../examples/server/src/elicitationFormExample.ts) -- Client‑side handling: [`simpleStreamableHttp.ts`](../examples/client/src/simpleStreamableHttp.ts) +- Server: [`elicitationFormExample.ts`](../src/examples/server/elicitationFormExample.ts) +- Client‑side handling: [`simpleStreamableHttp.ts`](../src/examples/client/simpleStreamableHttp.ts) The `simpleStreamableHttp` server also includes a `collect-user-info` tool that demonstrates how to drive elicitation from a tool and handle the response. @@ -33,8 +33,8 @@ URL elicitation is designed for sensitive data and secure web‑based flows (e.g Runnable example: -- Server: [`elicitationUrlExample.ts`](../examples/server/src/elicitationUrlExample.ts) -- Client: [`elicitationUrlExample.ts`](../examples/client/src/elicitationUrlExample.ts) +- Server: [`elicitationUrlExample.ts`](../src/examples/server/elicitationUrlExample.ts) +- Client: [`elicitationUrlExample.ts`](../src/examples/client/elicitationUrlExample.ts) Key points: @@ -62,8 +62,8 @@ On the server you will: For a runnable example that uses the in-memory store shipped with the SDK, see: -- [`toolWithSampleServer.ts`](../examples/server/src/toolWithSampleServer.ts) -- `packages/core/src/experimental/tasks/stores/in-memory.ts` +- [`toolWithSampleServer.ts`](../src/examples/server/toolWithSampleServer.ts) +- `src/experimental/tasks/stores/in-memory.ts` ### Client-side usage @@ -74,7 +74,7 @@ On the client, you use: The interactive client in: -- [`simpleStreamableHttp.ts`](../examples/client/src/simpleStreamableHttp.ts) +- [`simpleStreamableHttp.ts`](../src/examples/client/simpleStreamableHttp.ts) includes commands to demonstrate calling tools that support tasks and handling their lifecycle. diff --git a/docs/client.md b/docs/client.md index 52cb4caf08..d28765fd03 100644 --- a/docs/client.md +++ b/docs/client.md @@ -8,11 +8,11 @@ The SDK provides a high-level `Client` class that connects to MCP servers over d Runnable client examples live under: -- [`simpleStreamableHttp.ts`](../examples/client/src/simpleStreamableHttp.ts) -- [`streamableHttpWithSseFallbackClient.ts`](../examples/client/src/streamableHttpWithSseFallbackClient.ts) -- [`ssePollingClient.ts`](../examples/client/src/ssePollingClient.ts) -- [`multipleClientsParallel.ts`](../examples/client/src/multipleClientsParallel.ts) -- [`parallelToolCallsClient.ts`](../examples/client/src/parallelToolCallsClient.ts) +- [`simpleStreamableHttp.ts`](../src/examples/client/simpleStreamableHttp.ts) +- [`streamableHttpWithSseFallbackClient.ts`](../src/examples/client/streamableHttpWithSseFallbackClient.ts) +- [`ssePollingClient.ts`](../src/examples/client/ssePollingClient.ts) +- [`multipleClientsParallel.ts`](../src/examples/client/multipleClientsParallel.ts) +- [`parallelToolCallsClient.ts`](../src/examples/client/parallelToolCallsClient.ts) ## Connecting and basic operations @@ -25,7 +25,7 @@ A typical flow: - `listPrompts`, `getPrompt` - `listResources`, `readResource` -See [`simpleStreamableHttp.ts`](../examples/client/src/simpleStreamableHttp.ts) for an interactive CLI client that exercises these methods and shows how to handle notifications, elicitation and tasks. +See [`simpleStreamableHttp.ts`](../src/examples/client/simpleStreamableHttp.ts) for an interactive CLI client that exercises these methods and shows how to handle notifications, elicitation and tasks. ## Transports and backwards compatibility @@ -36,7 +36,7 @@ To support both modern Streamable HTTP and legacy SSE servers, use a client that Runnable example: -- [`streamableHttpWithSseFallbackClient.ts`](../examples/client/src/streamableHttpWithSseFallbackClient.ts) +- [`streamableHttpWithSseFallbackClient.ts`](../src/examples/client/streamableHttpWithSseFallbackClient.ts) ## OAuth client authentication helpers @@ -48,10 +48,10 @@ For OAuth-secured MCP servers, the client `auth` module exposes: Examples: -- [`simpleOAuthClient.ts`](../examples/client/src/simpleOAuthClient.ts) -- [`simpleOAuthClientProvider.ts`](../examples/client/src/simpleOAuthClientProvider.ts) -- [`simpleClientCredentials.ts`](../examples/client/src/simpleClientCredentials.ts) -- Server-side auth demo: [`demoInMemoryOAuthProvider.ts`](../examples/shared/src/demoInMemoryOAuthProvider.ts) (tests live under `examples/shared/test/demoInMemoryOAuthProvider.test.ts`) +- [`simpleOAuthClient.ts`](../src/examples/client/simpleOAuthClient.ts) +- [`simpleOAuthClientProvider.ts`](../src/examples/client/simpleOAuthClientProvider.ts) +- [`simpleClientCredentials.ts`](../src/examples/client/simpleClientCredentials.ts) +- Server-side auth demo: [`demoInMemoryOAuthProvider.ts`](../src/examples/server/demoInMemoryOAuthProvider.ts) (tests live under `test/examples/server/demoInMemoryOAuthProvider.test.ts`) These examples show how to: diff --git a/docs/faq.md b/docs/faq.md index 1afe1d10b9..6de0ecaae8 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -6,7 +6,6 @@ - [General](#general) - [Clients](#clients) - [Servers](#servers) -- [v1 (legacy)](#v1-legacy)
@@ -14,8 +13,7 @@ ### Why do I see `TS2589: Type instantiation is excessively deep and possibly infinite` after upgrading the SDK? -This TypeScript error can appear when upgrading to newer SDK versions that support Zod v4 (for example, from older `@modelcontextprotocol/sdk` releases to newer `@modelcontextprotocol/client` / `@modelcontextprotocol/server` releases) **and** your project ends up with multiple -`zod` versions in the dependency tree. +This TypeScript error can appear when upgrading to newer SDK versions that support Zod v4 (for example, from `@modelcontextprotocol/sdk` `1.22.0` to `1.23.0`) **and** your project ends up with multiple `zod` versions in the dependency tree. When there are multiple copies or versions of `zod`, TypeScript may try to instantiate very complex, cross-version types and hit its recursion limits, resulting in `TS2589`. This scenario is discussed in GitHub issue [#1180](https://github.com/modelcontextprotocol/typescript-sdk/issues/1180#event-21236550401). @@ -36,12 +34,12 @@ Once your project is using a single, compatible `zod` version, the `TS2589` erro ### How do I enable Web Crypto (`globalThis.crypto`) for client authentication in older Node.js versions? -The SDK’s OAuth client authentication helpers (for example, those in `packages/client/src/client/auth-extensions.ts` that use `jose`) rely on the Web Crypto API exposed as `globalThis.crypto`. This is especially important for **client credentials** and **JWT-based** -authentication flows used by MCP clients. +The SDK’s OAuth client authentication helpers (for example, those in `src/client/auth-extensions.ts` that use `jose`) rely on the Web Crypto API exposed as `globalThis.crypto`. This is especially important for **client credentials** and **JWT-based** authentication flows used by +MCP clients. - **Node.js v19.0.0 and later**: `globalThis.crypto` is available by default. -- **Node.js v18.x**: `globalThis.crypto` may not be defined by default. In this repository we polyfill it for tests (see `packages/client/vitest.setup.js`), and you should do the same in your app if it is missing – or alternatively, run Node with `--experimental-global-webcrypto` - as per your Node version documentation. (See https://nodejs.org/dist/latest-v18.x/docs/api/globals.html#crypto ) +- **Node.js v18.x**: `globalThis.crypto` may not be defined by default. In this repository we polyfill it for tests (see `vitest.setup.ts`), and you should do the same in your app if it is missing – or alternatively, run Node with `--experimental-global-webcrypto` as per your + Node version documentation. (See https://nodejs.org/dist/latest-v18.x/docs/api/globals.html#crypto ) If you run clients on Node.js versions where `globalThis.crypto` is missing, you can polyfill it using the built-in `node:crypto` module, similar to the SDK's own `vitest.setup.ts`: @@ -63,10 +61,5 @@ For production use, you can either: ### Where can I find runnable server examples? -The SDK ships several runnable server examples under `examples/server/src`. Start from the server examples index in [`examples/server/README.md`](../examples/server/README.md) and the entry-point quick start in the root [`README.md`](../README.md). - -## v1 (legacy) - -### Where do v1 documentation and v1-specific fixes live? - -The v1 generation of this SDK is maintained on the long-lived [`v1.x` branch](https://github.com/modelcontextprotocol/typescript-sdk/tree/v1.x). If you’re using v1, refer to that branch for documentation and any v1-specific fixes. +The SDK ships several runnable server examples under `src/examples/server`. The root `README.md` contains a curated **Server examples** table that links to each scenario (stateful/stateless Streamable HTTP, JSON-only mode, SSE/backwards compatibility, elicitation, sampling, +tasks, and OAuth demos), and `src/examples/README.md` includes commands and deployment diagrams for running them. diff --git a/docs/server.md b/docs/server.md index 4d5138e84a..bfb8dad218 100644 --- a/docs/server.md +++ b/docs/server.md @@ -1,6 +1,6 @@ ## Server overview -This SDK lets you build MCP servers in TypeScript and connect them to different transports. For most use cases you will use `McpServer` from `@modelcontextprotocol/server` and choose one of: +This SDK lets you build MCP servers in TypeScript and connect them to different transports. For most use cases you will use `McpServer` from `@modelcontextprotocol/sdk/server/mcp.js` and choose one of: - **Streamable HTTP** (recommended for remote servers) - **HTTP + SSE** (deprecated, for backwards compatibility only) @@ -8,11 +8,11 @@ This SDK lets you build MCP servers in TypeScript and connect them to different For a complete, runnable example server, see: -- [`simpleStreamableHttp.ts`](../examples/server/src/simpleStreamableHttp.ts) – feature‑rich Streamable HTTP server -- [`jsonResponseStreamableHttp.ts`](../examples/server/src/jsonResponseStreamableHttp.ts) – Streamable HTTP with JSON response mode -- [`simpleStatelessStreamableHttp.ts`](../examples/server/src/simpleStatelessStreamableHttp.ts) – stateless Streamable HTTP server -- [`simpleSseServer.ts`](../examples/server/src/simpleSseServer.ts) – deprecated HTTP+SSE transport -- [`sseAndStreamableHttpCompatibleServer.ts`](../examples/server/src/sseAndStreamableHttpCompatibleServer.ts) – backwards‑compatible server for old and new clients +- [`simpleStreamableHttp.ts`](../src/examples/server/simpleStreamableHttp.ts) – feature‑rich Streamable HTTP server +- [`jsonResponseStreamableHttp.ts`](../src/examples/server/jsonResponseStreamableHttp.ts) – Streamable HTTP with JSON response mode +- [`simpleStatelessStreamableHttp.ts`](../src/examples/server/simpleStatelessStreamableHttp.ts) – stateless Streamable HTTP server +- [`simpleSseServer.ts`](../src/examples/server/simpleSseServer.ts) – deprecated HTTP+SSE transport +- [`sseAndStreamableHttpCompatibleServer.ts`](../src/examples/server/sseAndStreamableHttpCompatibleServer.ts) – backwards‑compatible server for old and new clients ## Transports @@ -27,11 +27,12 @@ Streamable HTTP is the modern, fully featured transport. It supports: Key examples: -- [`simpleStreamableHttp.ts`](../examples/server/src/simpleStreamableHttp.ts) – sessions, logging, tasks, elicitation, auth hooks -- [`jsonResponseStreamableHttp.ts`](../examples/server/src/jsonResponseStreamableHttp.ts) – `enableJsonResponse: true`, no SSE -- [`standaloneSseWithGetStreamableHttp.ts`](../examples/server/src/standaloneSseWithGetStreamableHttp.ts) – notifications with Streamable HTTP GET + SSE +- [`simpleStreamableHttp.ts`](../src/examples/server/simpleStreamableHttp.ts) – sessions, logging, tasks, elicitation, auth hooks +- [`jsonResponseStreamableHttp.ts`](../src/examples/server/jsonResponseStreamableHttp.ts) – `enableJsonResponse: true`, no SSE +- [`standaloneSseWithGetStreamableHttp.ts`](../src/examples/server/standaloneSseWithGetStreamableHttp.ts) – notifications with Streamable HTTP GET + SSE -See the MCP spec for full transport details: `https://modelcontextprotocol.io/specification/2025-11-25/basic/transports` +See the MCP spec for full transport details: +`https://modelcontextprotocol.io/specification/2025-03-26/basic/transports` ### Stateless vs stateful sessions @@ -42,8 +43,8 @@ Streamable HTTP can run: Examples: -- Stateless Streamable HTTP: [`simpleStatelessStreamableHttp.ts`](../examples/server/src/simpleStatelessStreamableHttp.ts) -- Stateful with resumability: [`simpleStreamableHttp.ts`](../examples/server/src/simpleStreamableHttp.ts) +- Stateless Streamable HTTP: [`simpleStatelessStreamableHttp.ts`](../src/examples/server/simpleStatelessStreamableHttp.ts) +- Stateful with resumability: [`simpleStreamableHttp.ts`](../src/examples/server/simpleStreamableHttp.ts) ### Deprecated HTTP + SSE @@ -51,15 +52,15 @@ The older HTTP+SSE transport (protocol version 2024‑11‑05) is supported only Examples: -- Legacy SSE server: [`simpleSseServer.ts`](../examples/server/src/simpleSseServer.ts) +- Legacy SSE server: [`simpleSseServer.ts`](../src/examples/server/simpleSseServer.ts) - Backwards‑compatible server (Streamable HTTP + SSE): - [`sseAndStreamableHttpCompatibleServer.ts`](../examples/server/src/sseAndStreamableHttpCompatibleServer.ts) + [`sseAndStreamableHttpCompatibleServer.ts`](../src/examples/server/sseAndStreamableHttpCompatibleServer.ts) ## Running your server For a minimal “getting started” experience: -1. Start from [`simpleStreamableHttp.ts`](../examples/server/src/simpleStreamableHttp.ts). +1. Start from [`simpleStreamableHttp.ts`](../src/examples/server/simpleStreamableHttp.ts). 2. Remove features you do not need (tasks, advanced logging, OAuth, etc.). 3. Register your own tools, resources and prompts. @@ -70,7 +71,7 @@ For more detailed patterns (stateless vs stateful, JSON response mode, CORS, DNS MCP servers running on localhost are vulnerable to DNS rebinding attacks. Use `createMcpExpressApp()` to create an Express app with DNS rebinding protection enabled by default: ```typescript -import { createMcpExpressApp } from '@modelcontextprotocol/server'; +import { createMcpExpressApp } from '@modelcontextprotocol/sdk/server/express.js'; // Protection auto-enabled (default host is 127.0.0.1) const app = createMcpExpressApp(); @@ -78,19 +79,19 @@ const app = createMcpExpressApp(); // Protection auto-enabled for localhost const app = createMcpExpressApp({ host: 'localhost' }); -// No auto protection when binding to all interfaces, unless you provide allowedHosts +// No auto protection when binding to all interfaces const app = createMcpExpressApp({ host: '0.0.0.0' }); ``` -When binding to `0.0.0.0` / `::`, provide an allow-list of hosts: +For custom host validation, use the middleware directly: ```typescript -import { createMcpExpressApp } from '@modelcontextprotocol/server'; +import express from 'express'; +import { hostHeaderValidation } from '@modelcontextprotocol/sdk/server/middleware/hostHeaderValidation.js'; -const app = createMcpExpressApp({ - host: '0.0.0.0', - allowedHosts: ['localhost', '127.0.0.1', 'myhost.local'] -}); +const app = express(); +app.use(express.json()); +app.use(hostHeaderValidation(['localhost', '127.0.0.1', 'myhost.local'])); ``` ## Tools, resources, and prompts @@ -125,14 +126,14 @@ server.registerTool( This snippet is illustrative only; for runnable servers that expose tools, see: -- [`simpleStreamableHttp.ts`](../examples/server/src/simpleStreamableHttp.ts) -- [`toolWithSampleServer.ts`](../examples/server/src/toolWithSampleServer.ts) +- [`simpleStreamableHttp.ts`](../src/examples/server/simpleStreamableHttp.ts) +- [`toolWithSampleServer.ts`](../src/examples/server/toolWithSampleServer.ts) #### ResourceLink outputs Tools can return `resource_link` content items to reference large resources without embedding them directly, allowing clients to fetch only what they need. -The README’s `list-files` example shows the pattern conceptually; for concrete usage, see the Streamable HTTP examples in `examples/server/src`. +The README’s `list-files` example shows the pattern conceptually; for concrete usage, see the Streamable HTTP examples in `src/examples/server`. ### Resources @@ -157,7 +158,7 @@ server.registerResource( Dynamic resources use `ResourceTemplate` and can support completions on path parameters. For full runnable examples of resources: -- [`simpleStreamableHttp.ts`](../examples/server/src/simpleStreamableHttp.ts) +- [`simpleStreamableHttp.ts`](../src/examples/server/simpleStreamableHttp.ts) ### Prompts @@ -189,33 +190,37 @@ server.registerPrompt( For prompts integrated into a full server, see: -- [`simpleStreamableHttp.ts`](../examples/server/src/simpleStreamableHttp.ts) +- [`simpleStreamableHttp.ts`](../src/examples/server/simpleStreamableHttp.ts) ### Completions Both prompts and resources can support argument completions. On the client side, you use `client.complete()` with a reference to the prompt or resource and the partially‑typed argument. -See the MCP spec sections on prompts and resources for complete details, and [`simpleStreamableHttp.ts`](../examples/client/src/simpleStreamableHttp.ts) for client‑side usage patterns. +See the MCP spec sections on prompts and resources for complete details, and [`simpleStreamableHttp.ts`](../src/examples/client/simpleStreamableHttp.ts) for client‑side usage patterns. ### Display names and metadata Tools, resources and prompts support a `title` field for human‑readable names. Older APIs can also attach `annotations.title`. To compute the correct display name on the client, use: -- `getDisplayName` from `@modelcontextprotocol/client` +- `getDisplayName` from `@modelcontextprotocol/sdk/shared/metadataUtils.js` ## Multi‑node deployment patterns -The SDK supports multi‑node deployments using Streamable HTTP. The high‑level patterns and diagrams live with the runnable server examples: +The SDK supports multi‑node deployments using Streamable HTTP. The high‑level patterns are documented in [`README.md`](../src/examples/README.md): -- [`examples/server/README.md`](../examples/server/README.md#multi-node-deployment-patterns) +- Stateless mode (any node can handle any request) +- Persistent storage mode (shared database for session state) +- Local state with message routing (message queue + pub/sub) + +Those deployment diagrams are kept in [`README.md`](../src/examples/README.md) so the examples and documentation stay aligned. ## Backwards compatibility To handle both modern and legacy clients: - Run a backwards‑compatible server: - - [`sseAndStreamableHttpCompatibleServer.ts`](../examples/server/src/sseAndStreamableHttpCompatibleServer.ts) + - [`sseAndStreamableHttpCompatibleServer.ts`](../src/examples/server/sseAndStreamableHttpCompatibleServer.ts) - Use a client that falls back from Streamable HTTP to SSE: - - [`streamableHttpWithSseFallbackClient.ts`](../examples/client/src/streamableHttpWithSseFallbackClient.ts) + - [`streamableHttpWithSseFallbackClient.ts`](../src/examples/client/streamableHttpWithSseFallbackClient.ts) For the detailed protocol rules, see the “Backwards compatibility” section of the MCP spec. diff --git a/eslint.config.mjs b/eslint.config.mjs new file mode 100644 index 0000000000..fdfab80e28 --- /dev/null +++ b/eslint.config.mjs @@ -0,0 +1,34 @@ +// @ts-check + +import eslint from '@eslint/js'; +import tseslint from 'typescript-eslint'; +import eslintConfigPrettier from 'eslint-config-prettier/flat'; +import nodePlugin from 'eslint-plugin-n'; + +export default tseslint.config( + eslint.configs.recommended, + ...tseslint.configs.recommended, + { + linterOptions: { + reportUnusedDisableDirectives: false + }, + plugins: { + n: nodePlugin + }, + rules: { + '@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }], + 'n/prefer-node-protocol': 'error' + } + }, + { + ignores: ['src/spec.types.ts'] + }, + { + files: ['src/client/**/*.ts', 'src/server/**/*.ts'], + ignores: ['**/*.test.ts'], + rules: { + 'no-console': 'error' + } + }, + eslintConfigPrettier +); diff --git a/examples/client/README.md b/examples/client/README.md deleted file mode 100644 index 12a2b0d68b..0000000000 --- a/examples/client/README.md +++ /dev/null @@ -1,52 +0,0 @@ -# MCP TypeScript SDK Examples (Client) - -This directory contains runnable MCP **client** examples built with `@modelcontextprotocol/client`. - -For server examples, see [`../server/README.md`](../server/README.md). For guided docs, see [`../../docs/client.md`](../../docs/client.md). - -## Running examples - -From the repo root: - -```bash -pnpm install -pnpm --filter @modelcontextprotocol/examples-client exec tsx src/simpleStreamableHttp.ts -``` - -Or, from within this package: - -```bash -cd examples/client -pnpm tsx src/simpleStreamableHttp.ts -``` - -Most clients expect a server to be running. Start one from [`../server/README.md`](../server/README.md) (for example `src/simpleStreamableHttp.ts` in `examples/server`). - -## Example index - -| Scenario | Description | File | -| --------------------------------------------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | -| Interactive Streamable HTTP client | CLI client that exercises tools/resources/prompts, notifications, elicitation, and tasks. | [`src/simpleStreamableHttp.ts`](src/simpleStreamableHttp.ts) | -| Backwards-compatible client (Streamable HTTP → SSE) | Tries Streamable HTTP first, falls back to legacy SSE on 4xx responses. | [`src/streamableHttpWithSseFallbackClient.ts`](src/streamableHttpWithSseFallbackClient.ts) | -| SSE polling client (legacy) | Polls a legacy HTTP+SSE server and demonstrates notification handling. | [`src/ssePollingClient.ts`](src/ssePollingClient.ts) | -| Parallel tool calls | Runs multiple tool calls in parallel. | [`src/parallelToolCallsClient.ts`](src/parallelToolCallsClient.ts) | -| Multiple clients in parallel | Connects multiple clients concurrently to the same server. | [`src/multipleClientsParallel.ts`](src/multipleClientsParallel.ts) | -| OAuth client (interactive) | OAuth-enabled client (dynamic registration, auth flow). | [`src/simpleOAuthClient.ts`](src/simpleOAuthClient.ts) | -| OAuth provider helper | Demonstrates reusable OAuth providers. | [`src/simpleOAuthClientProvider.ts`](src/simpleOAuthClientProvider.ts) | -| Client credentials (M2M) | Machine-to-machine OAuth client credentials example. | [`src/simpleClientCredentials.ts`](src/simpleClientCredentials.ts) | -| URL elicitation client | Drives URL-mode elicitation flows (sensitive input in a browser). | [`src/elicitationUrlExample.ts`](src/elicitationUrlExample.ts) | -| Task interactive client | Demonstrates task-based execution + interactive server→client requests. | [`src/simpleTaskInteractiveClient.ts`](src/simpleTaskInteractiveClient.ts) | - -## URL elicitation example (server + client) - -Run the server first: - -```bash -pnpm --filter @modelcontextprotocol/examples-server exec tsx src/elicitationUrlExample.ts -``` - -Then run the client: - -```bash -pnpm --filter @modelcontextprotocol/examples-client exec tsx src/elicitationUrlExample.ts -``` diff --git a/examples/client/eslint.config.mjs b/examples/client/eslint.config.mjs deleted file mode 100644 index 83b79879f6..0000000000 --- a/examples/client/eslint.config.mjs +++ /dev/null @@ -1,14 +0,0 @@ -// @ts-check - -import baseConfig from '@modelcontextprotocol/eslint-config'; - -export default [ - ...baseConfig, - { - files: ['src/**/*.{ts,tsx,js,jsx,mts,cts}'], - rules: { - // Allow console statements in examples only - 'no-console': 'off' - } - } -]; diff --git a/examples/client/package.json b/examples/client/package.json deleted file mode 100644 index d77d6faf26..0000000000 --- a/examples/client/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "@modelcontextprotocol/examples-client", - "private": true, - "version": "2.0.0-alpha.0", - "description": "Model Context Protocol implementation for TypeScript", - "license": "MIT", - "author": "Anthropic, PBC (https://anthropic.com)", - "homepage": "https://modelcontextprotocol.io", - "bugs": "https://github.com/modelcontextprotocol/typescript-sdk/issues", - "type": "module", - "repository": { - "type": "git", - "url": "git+https://github.com/modelcontextprotocol/typescript-sdk.git" - }, - "engines": { - "node": ">=20", - "pnpm": ">=10.24.0" - }, - "packageManager": "pnpm@10.24.0", - "keywords": [ - "modelcontextprotocol", - "mcp" - ], - "scripts": { - "typecheck": "tsgo -p tsconfig.json --noEmit", - "build": "tsdown", - "build:watch": "tsdown --watch", - "prepack": "npm run build:esm && npm run build:cjs", - "lint": "eslint src/ && prettier --ignore-path ../../.prettierignore --check .", - "lint:fix": "eslint src/ --fix && prettier --ignore-path ../../.prettierignore --write .", - "check": "npm run typecheck && npm run lint", - "start": "npm run server", - "server": "tsx watch --clear-screen=false scripts/cli.ts server", - "client": "tsx scripts/cli.ts client" - }, - "dependencies": { - "@modelcontextprotocol/client": "workspace:^", - "ajv": "catalog:runtimeShared", - "zod": "catalog:runtimeShared" - }, - "devDependencies": { - "@modelcontextprotocol/examples-shared": "workspace:^", - "@modelcontextprotocol/tsconfig": "workspace:^", - "@modelcontextprotocol/eslint-config": "workspace:^", - "@modelcontextprotocol/vitest-config": "workspace:^", - "tsdown": "catalog:devTools" - } -} diff --git a/examples/client/tsconfig.json b/examples/client/tsconfig.json deleted file mode 100644 index 30a050fe74..0000000000 --- a/examples/client/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "@modelcontextprotocol/tsconfig", - "include": ["./"], - "exclude": ["node_modules", "dist"], - "compilerOptions": { - "paths": { - "*": ["./*"], - "@modelcontextprotocol/client": ["./node_modules/@modelcontextprotocol/client/src/index.ts"], - "@modelcontextprotocol/core": [ - "./node_modules/@modelcontextprotocol/client/node_modules/@modelcontextprotocol/core/src/index.ts" - ], - "@modelcontextprotocol/eslint-config": ["./node_modules/@modelcontextprotocol/eslint-config/tsconfig.json"], - "@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"], - "@modelcontextprotocol/examples-shared": ["./node_modules/@modelcontextprotocol/examples-shared/src/index.ts"] - } - } -} diff --git a/examples/client/tsdown.config.ts b/examples/client/tsdown.config.ts deleted file mode 100644 index efc4299d35..0000000000 --- a/examples/client/tsdown.config.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { defineConfig } from 'tsdown'; - -export default defineConfig({ - // 1. Entry Points - // Directly matches package.json include/exclude globs - entry: ['src/**/*.ts'], - - // 2. Output Configuration - format: ['esm'], - outDir: 'dist', - clean: true, // Recommended: Cleans 'dist' before building - sourcemap: true, - - // 3. Platform & Target - target: 'esnext', - platform: 'node', - shims: true, // Polyfills common Node.js shims (__dirname, etc.) - - // 4. Type Definitions - // Bundles d.ts files into a single output - dts: false, - // 5. Vendoring Strategy - Bundle the code for this specific package into the output, - // but treat all other dependencies as external (require/import). - noExternal: ['@modelcontextprotocol/examples-shared'] -}); diff --git a/examples/client/vitest.config.js b/examples/client/vitest.config.js deleted file mode 100644 index 496fca3200..0000000000 --- a/examples/client/vitest.config.js +++ /dev/null @@ -1,3 +0,0 @@ -import baseConfig from '@modelcontextprotocol/vitest-config'; - -export default baseConfig; diff --git a/examples/server/README.md b/examples/server/README.md deleted file mode 100644 index 310113e457..0000000000 --- a/examples/server/README.md +++ /dev/null @@ -1,173 +0,0 @@ -# MCP TypeScript SDK Examples (Server) - -This directory contains runnable MCP **server** examples built with `@modelcontextprotocol/server`. - -For client examples, see [`../client/README.md`](../client/README.md). For guided docs, see [`../../docs/server.md`](../../docs/server.md). - -## Running examples - -From anywhere in the SDK: - -```bash -pnpm install -pnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts -``` - -Or, from within this package: - -```bash -cd examples/server -pnpm tsx src/simpleStreamableHttp.ts -``` - -## Example index - -| Scenario | Description | File | -| --------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | -| Streamable HTTP server (stateful) | Feature-rich server with tools/resources/prompts, logging, tasks, sampling, and optional OAuth. | [`src/simpleStreamableHttp.ts`](src/simpleStreamableHttp.ts) | -| Streamable HTTP server (stateless) | No session tracking; good for simple API-style servers. | [`src/simpleStatelessStreamableHttp.ts`](src/simpleStatelessStreamableHttp.ts) | -| JSON response mode (no SSE) | Streamable HTTP with JSON-only responses and limited notifications. | [`src/jsonResponseStreamableHttp.ts`](src/jsonResponseStreamableHttp.ts) | -| Server notifications over Streamable HTTP | Demonstrates server-initiated notifications via GET+SSE. | [`src/standaloneSseWithGetStreamableHttp.ts`](src/standaloneSseWithGetStreamableHttp.ts) | -| Deprecated HTTP+SSE server (legacy) | Legacy HTTP+SSE transport for backwards-compatibility testing. | [`src/simpleSseServer.ts`](src/simpleSseServer.ts) | -| Backwards-compatible server (Streamable HTTP + SSE) | One server that supports both Streamable HTTP and legacy SSE clients. | [`src/sseAndStreamableHttpCompatibleServer.ts`](src/sseAndStreamableHttpCompatibleServer.ts) | -| Form elicitation server | Collects **non-sensitive** user input via schema-driven forms. | [`src/elicitationFormExample.ts`](src/elicitationFormExample.ts) | -| URL elicitation server | Secure browser-based flows for **sensitive** input (API keys, OAuth, payments). | [`src/elicitationUrlExample.ts`](src/elicitationUrlExample.ts) | -| Sampling + tasks server | Demonstrates sampling and experimental task-based execution. | [`src/toolWithSampleServer.ts`](src/toolWithSampleServer.ts) | -| Task interactive server | Task-based execution with interactive server→client requests. | [`src/simpleTaskInteractive.ts`](src/simpleTaskInteractive.ts) | -| Hono Streamable HTTP server | Streamable HTTP server built with Hono instead of Express. | [`src/honoWebStandardStreamableHttp.ts`](src/honoWebStandardStreamableHttp.ts) | -| SSE polling demo server | Legacy SSE server intended for polling demos. | [`src/ssePollingExample.ts`](src/ssePollingExample.ts) | - -## OAuth demo flags (Streamable HTTP server) - -```bash -pnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts --oauth -pnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts --oauth --oauth-strict -``` - -## URL elicitation example (server + client) - -Run the server: - -```bash -pnpm --filter @modelcontextprotocol/examples-server exec tsx src/elicitationUrlExample.ts -``` - -Run the client in another terminal: - -```bash -pnpm --filter @modelcontextprotocol/examples-client exec tsx src/elicitationUrlExample.ts -``` - -## Multi-node deployment patterns - -When deploying MCP servers in a horizontally scaled environment (multiple server instances), there are a few different options that can be useful for different use cases: - -- **Stateless mode** - no need to maintain state between calls. -- **Persistent storage mode** - state stored in a database; any node can handle a session. -- **Local state with message routing** - stateful nodes + pub/sub routing for a session. - -### Stateless mode - -To enable stateless mode, configure the `StreamableHTTPServerTransport` with: - -```typescript -sessionIdGenerator: undefined; -``` - -``` -┌─────────────────────────────────────────────┐ -│ Client │ -└─────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────┐ -│ Load Balancer │ -└─────────────────────────────────────────────┘ - │ │ - ▼ ▼ -┌─────────────────┐ ┌─────────────────────┐ -│ MCP Server #1 │ │ MCP Server #2 │ -│ (Node.js) │ │ (Node.js) │ -└─────────────────┘ └─────────────────────┘ -``` - -### Persistent storage mode - -Configure the transport with session management, but use an external event store: - -```typescript -sessionIdGenerator: () => randomUUID(), -eventStore: databaseEventStore -``` - -``` -┌─────────────────────────────────────────────┐ -│ Client │ -└─────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────┐ -│ Load Balancer │ -└─────────────────────────────────────────────┘ - │ │ - ▼ ▼ -┌─────────────────┐ ┌─────────────────────┐ -│ MCP Server #1 │ │ MCP Server #2 │ -│ (Node.js) │ │ (Node.js) │ -└─────────────────┘ └─────────────────────┘ - │ │ - │ │ - ▼ ▼ -┌─────────────────────────────────────────────┐ -│ Database (PostgreSQL) │ -│ │ -│ • Session state │ -│ • Event storage for resumability │ -└─────────────────────────────────────────────┘ -``` - -### Streamable HTTP with distributed message routing - -For scenarios where local in-memory state must be maintained on specific nodes, combine Streamable HTTP with pub/sub routing so one node can terminate the client connection while another node owns the session state. - -``` -┌─────────────────────────────────────────────┐ -│ Client │ -└─────────────────────────────────────────────┘ - │ - ▼ -┌─────────────────────────────────────────────┐ -│ Load Balancer │ -└─────────────────────────────────────────────┘ - │ │ - ▼ ▼ -┌─────────────────┐ ┌─────────────────────┐ -│ MCP Server #1 │◄───►│ MCP Server #2 │ -│ (Has Session A) │ │ (Has Session B) │ -└─────────────────┘ └─────────────────────┘ - ▲│ ▲│ - │▼ │▼ -┌─────────────────────────────────────────────┐ -│ Message Queue / Pub-Sub │ -│ │ -│ • Session ownership registry │ -│ • Bidirectional message routing │ -│ • Request/response forwarding │ -└─────────────────────────────────────────────┘ -``` - -## Backwards compatibility (Streamable HTTP ↔ legacy SSE) - -Start one of the servers: - -```bash -pnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleSseServer.ts -pnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleStreamableHttp.ts -pnpm --filter @modelcontextprotocol/examples-server exec tsx src/sseAndStreamableHttpCompatibleServer.ts -``` - -Then run the backwards-compatible client: - -```bash -pnpm --filter @modelcontextprotocol/examples-client exec tsx src/streamableHttpWithSseFallbackClient.ts -``` diff --git a/examples/server/eslint.config.mjs b/examples/server/eslint.config.mjs deleted file mode 100644 index 83b79879f6..0000000000 --- a/examples/server/eslint.config.mjs +++ /dev/null @@ -1,14 +0,0 @@ -// @ts-check - -import baseConfig from '@modelcontextprotocol/eslint-config'; - -export default [ - ...baseConfig, - { - files: ['src/**/*.{ts,tsx,js,jsx,mts,cts}'], - rules: { - // Allow console statements in examples only - 'no-console': 'off' - } - } -]; diff --git a/examples/server/package.json b/examples/server/package.json deleted file mode 100644 index a3a3d14c76..0000000000 --- a/examples/server/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "@modelcontextprotocol/examples-server", - "private": true, - "version": "2.0.0-alpha.0", - "description": "Model Context Protocol implementation for TypeScript", - "license": "MIT", - "author": "Anthropic, PBC (https://anthropic.com)", - "homepage": "https://modelcontextprotocol.io", - "bugs": "https://github.com/modelcontextprotocol/typescript-sdk/issues", - "type": "module", - "repository": { - "type": "git", - "url": "git+https://github.com/modelcontextprotocol/typescript-sdk.git" - }, - "engines": { - "node": ">=20", - "pnpm": ">=10.24.0" - }, - "packageManager": "pnpm@10.24.0", - "keywords": [ - "modelcontextprotocol", - "mcp" - ], - "scripts": { - "typecheck": "tsgo -p tsconfig.json --noEmit", - "build": "tsdown", - "build:watch": "tsdown --watch", - "prepack": "npm run build:esm && npm run build:cjs", - "lint": "eslint src/ && prettier --ignore-path ../../.prettierignore --check .", - "lint:fix": "eslint src/ --fix && prettier --ignore-path ../../.prettierignore --write .", - "check": "npm run typecheck && npm run lint", - "start": "npm run server", - "server": "tsx watch --clear-screen=false scripts/cli.ts server", - "client": "tsx scripts/cli.ts client" - }, - "dependencies": { - "@hono/node-server": "catalog:runtimeServerOnly", - "hono": "catalog:runtimeServerOnly", - "@modelcontextprotocol/examples-shared": "workspace:^", - "@modelcontextprotocol/server": "workspace:^", - "cors": "catalog:runtimeServerOnly", - "express": "catalog:runtimeServerOnly", - "zod": "catalog:runtimeShared" - }, - "devDependencies": { - "@modelcontextprotocol/eslint-config": "workspace:^", - "@modelcontextprotocol/tsconfig": "workspace:^", - "@modelcontextprotocol/vitest-config": "workspace:^", - "@types/cors": "catalog:devTools", - "@types/express": "catalog:devTools", - "tsdown": "catalog:devTools" - } -} diff --git a/examples/server/src/honoWebStandardStreamableHttp.ts b/examples/server/src/honoWebStandardStreamableHttp.ts deleted file mode 100644 index aef1e99e2e..0000000000 --- a/examples/server/src/honoWebStandardStreamableHttp.ts +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Example MCP server using Hono with WebStandardStreamableHTTPServerTransport - * - * This example demonstrates using the Web Standard transport directly with Hono, - * which works on any runtime: Node.js, Cloudflare Workers, Deno, Bun, etc. - * - * Run with: pnpm tsx src/honoWebStandardStreamableHttp.ts - */ - -import { serve } from '@hono/node-server'; -import type { CallToolResult } from '@modelcontextprotocol/server'; -import { McpServer, WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/server'; -import { Hono } from 'hono'; -import { cors } from 'hono/cors'; -import * as z from 'zod/v4'; - -// Create the MCP server -const server = new McpServer({ - name: 'hono-webstandard-mcp-server', - version: '1.0.0' -}); - -// Register a simple greeting tool -server.registerTool( - 'greet', - { - title: 'Greeting Tool', - description: 'A simple greeting tool', - inputSchema: { name: z.string().describe('Name to greet') } - }, - async ({ name }): Promise => { - return { - content: [{ type: 'text', text: `Hello, ${name}! (from Hono + WebStandard transport)` }] - }; - } -); - -// Create a stateless transport (no options = no session management) -const transport = new WebStandardStreamableHTTPServerTransport(); - -// Create the Hono app -const app = new Hono(); - -// Enable CORS for all origins -app.use( - '*', - cors({ - origin: '*', - allowMethods: ['GET', 'POST', 'DELETE', 'OPTIONS'], - allowHeaders: ['Content-Type', 'mcp-session-id', 'Last-Event-ID', 'mcp-protocol-version'], - exposeHeaders: ['mcp-session-id', 'mcp-protocol-version'] - }) -); - -// Health check endpoint -app.get('/health', c => c.json({ status: 'ok' })); - -// MCP endpoint -app.all('/mcp', c => transport.handleRequest(c.req.raw)); - -// Start the server -const PORT = process.env.MCP_PORT ? parseInt(process.env.MCP_PORT, 10) : 3000; - -server.connect(transport).then(() => { - console.log(`Starting Hono MCP server on port ${PORT}`); - console.log(`Health check: http://localhost:${PORT}/health`); - console.log(`MCP endpoint: http://localhost:${PORT}/mcp`); - - serve({ - fetch: app.fetch, - port: PORT - }); -}); diff --git a/examples/server/tsconfig.json b/examples/server/tsconfig.json deleted file mode 100644 index 98d3a5b3fe..0000000000 --- a/examples/server/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "extends": "@modelcontextprotocol/tsconfig", - "include": ["./"], - "exclude": ["node_modules", "dist"], - "compilerOptions": { - "paths": { - "*": ["./*"], - "@modelcontextprotocol/server": ["./node_modules/@modelcontextprotocol/server/src/index.ts"], - "@modelcontextprotocol/core": [ - "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/index.ts" - ], - "@modelcontextprotocol/examples-shared": ["./node_modules/@modelcontextprotocol/examples-shared/src/index.ts"], - "@modelcontextprotocol/eslint-config": ["./node_modules/@modelcontextprotocol/eslint-config/tsconfig.json"], - "@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"] - } - } -} diff --git a/examples/server/tsdown.config.ts b/examples/server/tsdown.config.ts deleted file mode 100644 index efc4299d35..0000000000 --- a/examples/server/tsdown.config.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { defineConfig } from 'tsdown'; - -export default defineConfig({ - // 1. Entry Points - // Directly matches package.json include/exclude globs - entry: ['src/**/*.ts'], - - // 2. Output Configuration - format: ['esm'], - outDir: 'dist', - clean: true, // Recommended: Cleans 'dist' before building - sourcemap: true, - - // 3. Platform & Target - target: 'esnext', - platform: 'node', - shims: true, // Polyfills common Node.js shims (__dirname, etc.) - - // 4. Type Definitions - // Bundles d.ts files into a single output - dts: false, - // 5. Vendoring Strategy - Bundle the code for this specific package into the output, - // but treat all other dependencies as external (require/import). - noExternal: ['@modelcontextprotocol/examples-shared'] -}); diff --git a/examples/server/vitest.config.js b/examples/server/vitest.config.js deleted file mode 100644 index 496fca3200..0000000000 --- a/examples/server/vitest.config.js +++ /dev/null @@ -1,3 +0,0 @@ -import baseConfig from '@modelcontextprotocol/vitest-config'; - -export default baseConfig; diff --git a/examples/shared/eslint.config.mjs b/examples/shared/eslint.config.mjs deleted file mode 100644 index 83b79879f6..0000000000 --- a/examples/shared/eslint.config.mjs +++ /dev/null @@ -1,14 +0,0 @@ -// @ts-check - -import baseConfig from '@modelcontextprotocol/eslint-config'; - -export default [ - ...baseConfig, - { - files: ['src/**/*.{ts,tsx,js,jsx,mts,cts}'], - rules: { - // Allow console statements in examples only - 'no-console': 'off' - } - } -]; diff --git a/examples/shared/package.json b/examples/shared/package.json deleted file mode 100644 index 8287ca552a..0000000000 --- a/examples/shared/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "name": "@modelcontextprotocol/examples-shared", - "private": true, - "version": "2.0.0-alpha.0", - "description": "Model Context Protocol implementation for TypeScript", - "license": "MIT", - "author": "Anthropic, PBC (https://anthropic.com)", - "homepage": "https://modelcontextprotocol.io", - "bugs": "https://github.com/modelcontextprotocol/typescript-sdk/issues", - "type": "module", - "repository": { - "type": "git", - "url": "git+https://github.com/modelcontextprotocol/typescript-sdk.git" - }, - "engines": { - "node": ">=20", - "pnpm": ">=10.24.0" - }, - "packageManager": "pnpm@10.24.0", - "keywords": [ - "modelcontextprotocol", - "mcp" - ], - "scripts": { - "typecheck": "tsgo -p tsconfig.json --noEmit", - "prepack": "npm run build:esm && npm run build:cjs", - "lint": "eslint src/ && prettier --ignore-path ../../.prettierignore --check .", - "lint:fix": "eslint src/ --fix && prettier --ignore-path ../../.prettierignore --write .", - "check": "npm run typecheck && npm run lint", - "test": "vitest run", - "test:watch": "vitest", - "start": "npm run server", - "server": "tsx watch --clear-screen=false scripts/cli.ts server", - "client": "tsx scripts/cli.ts client" - }, - "dependencies": { - "@modelcontextprotocol/server": "workspace:^", - "express": "catalog:runtimeServerOnly" - }, - "devDependencies": { - "@modelcontextprotocol/tsconfig": "workspace:^", - "@modelcontextprotocol/eslint-config": "workspace:^", - "@modelcontextprotocol/vitest-config": "workspace:^", - "@modelcontextprotocol/test-helpers": "workspace:^", - "@types/express": "catalog:devTools", - "@typescript/native-preview": "catalog:devTools", - "@eslint/js": "catalog:devTools", - "eslint": "catalog:devTools", - "eslint-config-prettier": "catalog:devTools", - "eslint-plugin-n": "catalog:devTools", - "prettier": "catalog:devTools", - "tsx": "catalog:devTools", - "typescript": "catalog:devTools", - "typescript-eslint": "catalog:devTools", - "vitest": "catalog:devTools" - } -} diff --git a/examples/shared/src/index.ts b/examples/shared/src/index.ts deleted file mode 100644 index 1c31cf06e8..0000000000 --- a/examples/shared/src/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './demoInMemoryOAuthProvider.js'; diff --git a/examples/shared/tsconfig.json b/examples/shared/tsconfig.json deleted file mode 100644 index aa994f9394..0000000000 --- a/examples/shared/tsconfig.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "extends": "@modelcontextprotocol/tsconfig", - "include": ["./"], - "exclude": ["node_modules", "dist"], - "compilerOptions": { - "paths": { - "*": ["./*"], - "@modelcontextprotocol/server": ["./node_modules/@modelcontextprotocol/server/src/index.ts"], - "@modelcontextprotocol/core": [ - "./node_modules/@modelcontextprotocol/server/node_modules/@modelcontextprotocol/core/src/index.ts" - ], - "@modelcontextprotocol/eslint-config": ["./node_modules/@modelcontextprotocol/eslint-config/tsconfig.json"], - "@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"], - "@modelcontextprotocol/test-helpers": ["./node_modules/@modelcontextprotocol/test-helpers/src/index.ts"], - "@modelcontextprotocol/client": [ - "./node_modules/@modelcontextprotocol/test-helpers/node_modules/@modelcontextprotocol/client/src/index.ts" - ] - } - } -} diff --git a/examples/shared/vitest.config.js b/examples/shared/vitest.config.js deleted file mode 100644 index 496fca3200..0000000000 --- a/examples/shared/vitest.config.js +++ /dev/null @@ -1,3 +0,0 @@ -import baseConfig from '@modelcontextprotocol/vitest-config'; - -export default baseConfig; diff --git a/package-lock.json b/package-lock.json index 64bc6f21dd..d32963a73d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,15 +1,14 @@ { "name": "@modelcontextprotocol/sdk", - "version": "1.25.1", + "version": "1.24.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@modelcontextprotocol/sdk", - "version": "1.25.1", + "version": "1.24.3", "license": "MIT", "dependencies": { - "@hono/node-server": "^1.19.7", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", @@ -664,18 +663,6 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, - "node_modules/@hono/node-server": { - "version": "1.19.7", - "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.7.tgz", - "integrity": "sha512-vUcD0uauS7EU2caukW8z5lJKtoGMokxNbJtBiwHgpqxEXokaHCBkQUmCHhjFB1VUTWdqj25QoMkMKzgjq+uhrw==", - "license": "MIT", - "engines": { - "node": ">=18.14.1" - }, - "peerDependencies": { - "hono": "^4" - } - }, "node_modules/@humanfs/core": { "version": "0.19.1", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", @@ -1332,6 +1319,7 @@ "integrity": "sha512-PC0PDZfJg8sP7cmKe6L3QIL8GZwU5aRvUFedqSIpw3B+QjRSUZeeITC2M5XKeMXEzL6wccN196iy3JLwKNvDVA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.48.1", "@typescript-eslint/types": "8.48.1", @@ -1763,6 +1751,7 @@ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "dev": true, "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -2305,6 +2294,7 @@ "integrity": "sha512-BhHmn2yNOFA9H9JmmIVKJmd288g9hrVRDkdoIgRCRuSySRUHH7r/DI6aAXW9T1WwUuY3DFgrcaqB+deURBLR5g==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -2623,6 +2613,7 @@ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz", "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", "license": "MIT", + "peer": true, "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", @@ -3036,16 +3027,6 @@ "node": ">= 0.4" } }, - "node_modules/hono": { - "version": "4.10.8", - "resolved": "https://registry.npmjs.org/hono/-/hono-4.10.8.tgz", - "integrity": "sha512-DDT0A0r6wzhe8zCGoYOmMeuGu3dyTAE40HHjwUsWFTEy5WxK1x2WDSsBPlEXgPbRIFY6miDualuUDbasPogIww==", - "license": "MIT", - "peer": true, - "engines": { - "node": ">=16.9.0" - } - }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -4090,6 +4071,7 @@ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -4170,6 +4152,7 @@ "integrity": "sha512-4H8vUNGNjQ4V2EOoGw005+c+dGuPSnhpPBPHBtsZdGZBk/iJb4kguGlPWaZTZ3q5nMtFOEsY0nRDlh9PJyd6SQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "~0.25.0", "get-tsconfig": "^4.7.5" @@ -4215,6 +4198,7 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz", "integrity": "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==", "dev": true, + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -4409,6 +4393,7 @@ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -4422,6 +4407,7 @@ "integrity": "sha512-BxAKBWmIbrDgrokdGZH1IgkIk/5mMHDreLDmCJ0qpyJaAteP8NvMhkwr/ZCQNqNH97bw/dANTE9PDzqwJghfMQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.5.0", @@ -4574,6 +4560,7 @@ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==", "license": "MIT", + "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/package.json b/package.json index 2633d5ef26..bfbc73802e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@modelcontextprotocol/sdk", - "version": "1.25.1", + "version": "1.24.3", "description": "Model Context Protocol implementation for TypeScript", "license": "MIT", "author": "Anthropic, PBC (https://anthropic.com)", @@ -12,51 +12,131 @@ "url": "git+https://github.com/modelcontextprotocol/typescript-sdk.git" }, "engines": { - "node": ">=20", - "pnpm": ">=10.24.0" + "node": ">=18" }, - "packageManager": "pnpm@10.24.0", "keywords": [ "modelcontextprotocol", "mcp" ], + "exports": { + ".": { + "import": "./dist/esm/index.js", + "require": "./dist/cjs/index.js" + }, + "./client": { + "import": "./dist/esm/client/index.js", + "require": "./dist/cjs/client/index.js" + }, + "./server": { + "import": "./dist/esm/server/index.js", + "require": "./dist/cjs/server/index.js" + }, + "./validation": { + "import": "./dist/esm/validation/index.js", + "require": "./dist/cjs/validation/index.js" + }, + "./validation/ajv": { + "import": "./dist/esm/validation/ajv-provider.js", + "require": "./dist/cjs/validation/ajv-provider.js" + }, + "./validation/cfworker": { + "import": "./dist/esm/validation/cfworker-provider.js", + "require": "./dist/cjs/validation/cfworker-provider.js" + }, + "./experimental": { + "import": "./dist/esm/experimental/index.js", + "require": "./dist/cjs/experimental/index.js" + }, + "./experimental/tasks": { + "import": "./dist/esm/experimental/tasks/index.js", + "require": "./dist/cjs/experimental/tasks/index.js" + }, + "./*": { + "import": "./dist/esm/*", + "require": "./dist/cjs/*" + } + }, + "typesVersions": { + "*": { + "*": [ + "./dist/esm/*" + ] + } + }, + "files": [ + "dist" + ], "scripts": { "fetch:spec-types": "tsx scripts/fetch-spec-types.ts", - "examples:simple-server:w": "pnpm --filter @modelcontextprotocol/examples-server exec tsx --watch src/simpleStreamableHttp.ts --oauth", - "typecheck:all": "pnpm -r typecheck", - "build:all": "pnpm -r build", - "prepack:all": "pnpm -r prepack", - "lint:all": "pnpm -r lint", - "lint:fix:all": "pnpm -r lint:fix", - "check:all": "pnpm -r typecheck && pnpm -r lint", - "test:all": "pnpm -r test" + "typecheck": "tsgo --noEmit", + "build": "npm run build:esm && npm run build:cjs", + "build:esm": "mkdir -p dist/esm && echo '{\"type\": \"module\"}' > dist/esm/package.json && tsc -p tsconfig.prod.json", + "build:esm:w": "npm run build:esm -- -w", + "build:cjs": "mkdir -p dist/cjs && echo '{\"type\": \"commonjs\"}' > dist/cjs/package.json && tsc -p tsconfig.cjs.json", + "build:cjs:w": "npm run build:cjs -- -w", + "examples:simple-server:w": "tsx --watch src/examples/server/simpleStreamableHttp.ts --oauth", + "prepack": "npm run build:esm && npm run build:cjs", + "lint": "eslint src/ && prettier --check .", + "lint:fix": "eslint src/ --fix && prettier --write .", + "check": "npm run typecheck && npm run lint", + "test": "vitest run", + "test:watch": "vitest", + "start": "npm run server", + "server": "tsx watch --clear-screen=false scripts/cli.ts server", + "client": "tsx scripts/cli.ts client" + }, + "dependencies": { + "ajv": "^8.17.1", + "ajv-formats": "^3.0.1", + "content-type": "^1.0.5", + "cors": "^2.8.5", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.0", + "express": "^5.0.1", + "express-rate-limit": "^7.5.0", + "jose": "^6.1.1", + "json-schema-typed": "^8.0.2", + "pkce-challenge": "^5.0.0", + "raw-body": "^3.0.0", + "zod": "^3.25 || ^4.0", + "zod-to-json-schema": "^3.25.0" + }, + "peerDependencies": { + "@cfworker/json-schema": "^4.1.1", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@cfworker/json-schema": { + "optional": true + }, + "zod": { + "optional": false + } }, "devDependencies": { - "@cfworker/json-schema": "catalog:runtimeShared", - "@changesets/changelog-github": "^0.5.2", - "@changesets/cli": "^2.29.8", - "@eslint/js": "catalog:devTools", - "@types/content-type": "catalog:devTools", - "@types/cors": "catalog:devTools", - "@types/cross-spawn": "catalog:devTools", - "@types/eventsource": "catalog:devTools", - "@types/express": "catalog:devTools", - "@types/express-serve-static-core": "catalog:devTools", - "@types/node": "^24.10.1", - "@types/supertest": "catalog:devTools", - "@types/ws": "catalog:devTools", - "@typescript/native-preview": "catalog:devTools", - "eslint": "catalog:devTools", - "eslint-config-prettier": "catalog:devTools", - "eslint-plugin-n": "catalog:devTools", - "prettier": "catalog:devTools", - "supertest": "catalog:devTools", - "tsdown": "catalog:devTools", - "tsx": "catalog:devTools", - "typescript": "catalog:devTools", - "typescript-eslint": "catalog:devTools", - "vitest": "catalog:devTools", - "ws": "catalog:devTools" + "@cfworker/json-schema": "^4.1.1", + "@eslint/js": "^9.39.1", + "@types/content-type": "^1.1.8", + "@types/cors": "^2.8.17", + "@types/cross-spawn": "^6.0.6", + "@types/eventsource": "^1.1.15", + "@types/express": "^5.0.0", + "@types/express-serve-static-core": "^5.1.0", + "@types/node": "^22.12.0", + "@types/supertest": "^6.0.2", + "@types/ws": "^8.5.12", + "@typescript/native-preview": "^7.0.0-dev.20251103.1", + "eslint": "^9.8.0", + "eslint-config-prettier": "^10.1.8", + "eslint-plugin-n": "^17.23.1", + "prettier": "3.6.2", + "supertest": "^7.0.0", + "tsx": "^4.16.5", + "typescript": "^5.5.4", + "typescript-eslint": "^8.48.1", + "vitest": "^4.0.8", + "ws": "^8.18.0" }, "resolutions": { "strip-ansi": "6.0.1" diff --git a/packages/client/eslint.config.mjs b/packages/client/eslint.config.mjs deleted file mode 100644 index 4f034f2235..0000000000 --- a/packages/client/eslint.config.mjs +++ /dev/null @@ -1,12 +0,0 @@ -// @ts-check - -import baseConfig from '@modelcontextprotocol/eslint-config'; - -export default [ - ...baseConfig, - { - settings: { - 'import/internal-regex': '^@modelcontextprotocol/core' - } - } -]; diff --git a/packages/client/package.json b/packages/client/package.json deleted file mode 100644 index e62a5bf160..0000000000 --- a/packages/client/package.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "name": "@modelcontextprotocol/client", - "version": "2.0.0-alpha.0", - "description": "Model Context Protocol implementation for TypeScript", - "license": "MIT", - "author": "Anthropic, PBC (https://anthropic.com)", - "homepage": "https://modelcontextprotocol.io", - "bugs": "https://github.com/modelcontextprotocol/typescript-sdk/issues", - "type": "module", - "repository": { - "type": "git", - "url": "git+https://github.com/modelcontextprotocol/typescript-sdk.git" - }, - "engines": { - "node": ">=20", - "pnpm": ">=10.24.0" - }, - "packageManager": "pnpm@10.24.0", - "keywords": [ - "modelcontextprotocol", - "mcp" - ], - "exports": { - ".": { - "types": "./dist/index.d.mts", - "import": "./dist/index.mjs" - } - }, - "files": [ - "dist" - ], - "scripts": { - "typecheck": "tsgo -p tsconfig.json --noEmit", - "build": "tsdown", - "build:watch": "tsdown --watch", - "prepack": "npm run build", - "lint": "eslint src/ && prettier --ignore-path ../../.prettierignore --check .", - "lint:fix": "eslint src/ --fix && prettier --ignore-path ../../.prettierignore --write .", - "check": "npm run typecheck && npm run lint", - "test": "vitest run", - "test:watch": "vitest", - "start": "npm run server", - "server": "tsx watch --clear-screen=false scripts/cli.ts server", - "client": "tsx scripts/cli.ts client" - }, - "dependencies": { - "cross-spawn": "catalog:runtimeClientOnly", - "eventsource": "catalog:runtimeClientOnly", - "eventsource-parser": "catalog:runtimeClientOnly", - "jose": "catalog:runtimeClientOnly", - "pkce-challenge": "catalog:runtimeShared", - "zod": "catalog:runtimeShared" - }, - "peerDependencies": { - "@cfworker/json-schema": "catalog:runtimeShared", - "zod": "catalog:runtimeShared" - }, - "peerDependenciesMeta": { - "@cfworker/json-schema": { - "optional": true - }, - "zod": { - "optional": false - } - }, - "devDependencies": { - "@modelcontextprotocol/core": "workspace:^", - "@modelcontextprotocol/tsconfig": "workspace:^", - "@modelcontextprotocol/vitest-config": "workspace:^", - "@modelcontextprotocol/eslint-config": "workspace:^", - "@modelcontextprotocol/test-helpers": "workspace:^", - "@cfworker/json-schema": "catalog:runtimeShared", - "@types/content-type": "catalog:devTools", - "@types/cross-spawn": "catalog:devTools", - "@types/eventsource": "catalog:devTools", - "@typescript/native-preview": "catalog:devTools", - "@eslint/js": "catalog:devTools", - "eslint": "catalog:devTools", - "eslint-config-prettier": "catalog:devTools", - "eslint-plugin-n": "catalog:devTools", - "prettier": "catalog:devTools", - "tsx": "catalog:devTools", - "typescript": "catalog:devTools", - "typescript-eslint": "catalog:devTools", - "vitest": "catalog:devTools", - "tsdown": "catalog:devTools" - } -} diff --git a/packages/client/src/experimental/index.ts b/packages/client/src/experimental/index.ts deleted file mode 100644 index 926369f994..0000000000 --- a/packages/client/src/experimental/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * Experimental MCP SDK features. - * WARNING: These APIs are experimental and may change without notice. - * - * Import experimental features from this module: - * ```typescript - * import { TaskStore, InMemoryTaskStore } from '@modelcontextprotocol/sdk/experimental'; - * ``` - * - * @experimental - */ - -export * from './tasks/client.js'; diff --git a/packages/client/src/index.ts b/packages/client/src/index.ts deleted file mode 100644 index 0f802c4fb5..0000000000 --- a/packages/client/src/index.ts +++ /dev/null @@ -1,14 +0,0 @@ -export * from './client/auth.js'; -export * from './client/auth-extensions.js'; -export * from './client/client.js'; -export * from './client/middleware.js'; -export * from './client/sse.js'; -export * from './client/stdio.js'; -export * from './client/streamableHttp.js'; -export * from './client/websocket.js'; - -// experimental exports -export * from './experimental/index.js'; - -// re-export shared types -export * from '@modelcontextprotocol/core'; diff --git a/packages/client/tsconfig.json b/packages/client/tsconfig.json deleted file mode 100644 index a16bfd7d9d..0000000000 --- a/packages/client/tsconfig.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "@modelcontextprotocol/tsconfig", - "include": ["./"], - "exclude": ["node_modules", "dist"], - "compilerOptions": { - "paths": { - "*": ["./*"], - "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], - "@modelcontextprotocol/test-helpers": ["./node_modules/@modelcontextprotocol/test-helpers/src/index.ts"] - } - } -} diff --git a/packages/client/tsdown.config.ts b/packages/client/tsdown.config.ts deleted file mode 100644 index c3d38817a6..0000000000 --- a/packages/client/tsdown.config.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { defineConfig } from 'tsdown'; - -export default defineConfig({ - // 1. Entry Points - // Directly matches package.json include/exclude globs - entry: ['src/index.ts'], - - // 2. Output Configuration - format: ['esm'], - outDir: 'dist', - clean: true, // Recommended: Cleans 'dist' before building - sourcemap: true, - - // 3. Platform & Target - target: 'esnext', - platform: 'node', - shims: true, // Polyfills common Node.js shims (__dirname, etc.) - - // 4. Type Definitions - // Bundles d.ts files into a single output - dts: { - resolver: 'tsc', - // override just for DTS generation: - compilerOptions: { - baseUrl: '.', - paths: { - '@modelcontextprotocol/core': ['../core/src/index.ts'] - } - } - }, - // 5. Vendoring Strategy - Bundle the code for this specific package into the output, - // but treat all other dependencies as external (require/import). - noExternal: ['@modelcontextprotocol/core'] -}); diff --git a/packages/client/vitest.config.js b/packages/client/vitest.config.js deleted file mode 100644 index 2012fa59ea..0000000000 --- a/packages/client/vitest.config.js +++ /dev/null @@ -1,8 +0,0 @@ -import baseConfig from '@modelcontextprotocol/vitest-config'; -import { mergeConfig } from 'vitest/config'; - -export default mergeConfig(baseConfig, { - test: { - setupFiles: ['./vitest.setup.js'] - } -}); diff --git a/packages/core/eslint.config.mjs b/packages/core/eslint.config.mjs deleted file mode 100644 index 951c9f3a91..0000000000 --- a/packages/core/eslint.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -// @ts-check - -import baseConfig from '@modelcontextprotocol/eslint-config'; - -export default baseConfig; diff --git a/packages/core/package.json b/packages/core/package.json deleted file mode 100644 index a7364d4dd0..0000000000 --- a/packages/core/package.json +++ /dev/null @@ -1,76 +0,0 @@ -{ - "name": "@modelcontextprotocol/core", - "private": true, - "version": "2.0.0-alpha.0", - "description": "Model Context Protocol implementation for TypeScript", - "license": "MIT", - "author": "Anthropic, PBC (https://anthropic.com)", - "homepage": "https://modelcontextprotocol.io", - "bugs": "https://github.com/modelcontextprotocol/typescript-sdk/issues", - "type": "module", - "repository": { - "type": "git", - "url": "git+https://github.com/modelcontextprotocol/typescript-sdk.git" - }, - "engines": { - "node": ">=20", - "pnpm": ">=10.24.0" - }, - "packageManager": "pnpm@10.24.0", - "keywords": [ - "modelcontextprotocol", - "mcp" - ], - "scripts": { - "typecheck": "tsgo -p tsconfig.json --noEmit", - "lint": "eslint src/ && prettier --ignore-path ../../.prettierignore --check .", - "lint:fix": "eslint src/ --fix && prettier --ignore-path ../../.prettierignore --write .", - "check": "npm run typecheck && npm run lint", - "test": "vitest run", - "test:watch": "vitest", - "start": "npm run server", - "server": "tsx watch --clear-screen=false scripts/cli.ts server", - "client": "tsx scripts/cli.ts client" - }, - "dependencies": { - "ajv": "catalog:runtimeShared", - "ajv-formats": "catalog:runtimeShared", - "json-schema-typed": "catalog:runtimeShared", - "zod": "catalog:runtimeShared", - "zod-to-json-schema": "catalog:runtimeShared" - }, - "peerDependencies": { - "@cfworker/json-schema": "catalog:runtimeShared", - "zod": "catalog:runtimeShared" - }, - "peerDependenciesMeta": { - "@cfworker/json-schema": { - "optional": true - }, - "zod": { - "optional": false - } - }, - "devDependencies": { - "@modelcontextprotocol/tsconfig": "workspace:^", - "@modelcontextprotocol/vitest-config": "workspace:^", - "@modelcontextprotocol/eslint-config": "workspace:^", - "@cfworker/json-schema": "catalog:runtimeShared", - "@eslint/js": "catalog:devTools", - "@types/content-type": "catalog:devTools", - "@types/cors": "catalog:devTools", - "@types/cross-spawn": "catalog:devTools", - "@types/eventsource": "catalog:devTools", - "@types/express": "catalog:devTools", - "@types/express-serve-static-core": "catalog:devTools", - "@typescript/native-preview": "catalog:devTools", - "eslint": "catalog:devTools", - "eslint-config-prettier": "catalog:devTools", - "eslint-plugin-n": "catalog:devTools", - "prettier": "catalog:devTools", - "tsx": "catalog:devTools", - "typescript": "catalog:devTools", - "typescript-eslint": "catalog:devTools", - "vitest": "catalog:devTools" - } -} diff --git a/packages/core/src/experimental/index.ts b/packages/core/src/experimental/index.ts deleted file mode 100644 index 1a641c25d7..0000000000 --- a/packages/core/src/experimental/index.ts +++ /dev/null @@ -1,3 +0,0 @@ -export * from './tasks/helpers.js'; -export * from './tasks/interfaces.js'; -export * from './tasks/stores/in-memory.js'; diff --git a/packages/core/src/exports/types/index.ts b/packages/core/src/exports/types/index.ts deleted file mode 100644 index 47806ee8ba..0000000000 --- a/packages/core/src/exports/types/index.ts +++ /dev/null @@ -1 +0,0 @@ -export type * from '../../types/types.js'; diff --git a/packages/core/src/types/spec.types.ts b/packages/core/src/types/spec.types.ts deleted file mode 100644 index aa298e63c4..0000000000 --- a/packages/core/src/types/spec.types.ts +++ /dev/null @@ -1,2552 +0,0 @@ -/** - * This file is automatically generated from the Model Context Protocol specification. - * - * Source: https://github.com/modelcontextprotocol/modelcontextprotocol - * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts - * Last updated from commit: 35fa160caf287a9c48696e3ae452c0645c713669 - * - * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. - * To update this file, run: npm run fetch:spec-types - */ /* JSON-RPC types */ - -/** - * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. - * - * @category JSON-RPC - */ -export type JSONRPCMessage = JSONRPCRequest | JSONRPCNotification | JSONRPCResponse; - -/** @internal */ -export const LATEST_PROTOCOL_VERSION = 'DRAFT-2026-v1'; -/** @internal */ -export const JSONRPC_VERSION = '2.0'; - -/** - * A progress token, used to associate progress notifications with the original request. - * - * @category Common Types - */ -export type ProgressToken = string | number; - -/** - * An opaque token used to represent a cursor for pagination. - * - * @category Common Types - */ -export type Cursor = string; - -/** - * Common params for any task-augmented request. - * - * @internal - */ -export interface TaskAugmentedRequestParams extends RequestParams { - /** - * If specified, the caller is requesting task-augmented execution for this request. - * The request will return a CreateTaskResult immediately, and the actual result can be - * retrieved later via tasks/result. - * - * Task augmentation is subject to capability negotiation - receivers MUST declare support - * for task augmentation of specific request types in their capabilities. - */ - task?: TaskMetadata; -} -/** - * Common params for any request. - * - * @internal - */ -export interface RequestParams { - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - /** - * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. - */ - progressToken?: ProgressToken; - [key: string]: unknown; - }; -} - -/** @internal */ -export interface Request { - method: string; - // Allow unofficial extensions of `Request.params` without impacting `RequestParams`. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - params?: { [key: string]: any }; -} - -/** @internal */ -export interface NotificationParams { - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; -} - -/** @internal */ -export interface Notification { - method: string; - // Allow unofficial extensions of `Notification.params` without impacting `NotificationParams`. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - params?: { [key: string]: any }; -} - -/** - * @category Common Types - */ -export interface Result { - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; - [key: string]: unknown; -} - -/** - * @category Common Types - */ -export interface Error { - /** - * The error type that occurred. - */ - code: number; - /** - * A short description of the error. The message SHOULD be limited to a concise single sentence. - */ - message: string; - /** - * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). - */ - data?: unknown; -} - -/** - * A uniquely identifying ID for a request in JSON-RPC. - * - * @category Common Types - */ -export type RequestId = string | number; - -/** - * A request that expects a response. - * - * @category JSON-RPC - */ -export interface JSONRPCRequest extends Request { - jsonrpc: typeof JSONRPC_VERSION; - id: RequestId; -} - -/** - * A notification which does not expect a response. - * - * @category JSON-RPC - */ -export interface JSONRPCNotification extends Notification { - jsonrpc: typeof JSONRPC_VERSION; -} - -/** - * A successful (non-error) response to a request. - * - * @category JSON-RPC - */ -export interface JSONRPCResultResponse { - jsonrpc: typeof JSONRPC_VERSION; - id: RequestId; - result: Result; -} - -/** - * A response to a request that indicates an error occurred. - * - * @category JSON-RPC - */ -export interface JSONRPCErrorResponse { - jsonrpc: typeof JSONRPC_VERSION; - id?: RequestId; - error: Error; -} - -/** - * A response to a request, containing either the result or error. - */ -export type JSONRPCResponse = JSONRPCResultResponse | JSONRPCErrorResponse; - -// Standard JSON-RPC error codes -export const PARSE_ERROR = -32700; -export const INVALID_REQUEST = -32600; -export const METHOD_NOT_FOUND = -32601; -export const INVALID_PARAMS = -32602; -export const INTERNAL_ERROR = -32603; - -// Implementation-specific JSON-RPC error codes [-32000, -32099] -/** @internal */ -export const URL_ELICITATION_REQUIRED = -32042; - -/** - * An error response that indicates that the server requires the client to provide additional information via an elicitation request. - * - * @internal - */ -export interface URLElicitationRequiredError extends Omit { - error: Error & { - code: typeof URL_ELICITATION_REQUIRED; - data: { - elicitations: ElicitRequestURLParams[]; - [key: string]: unknown; - }; - }; -} - -/* Empty result */ -/** - * A response that indicates success but carries no data. - * - * @category Common Types - */ -export type EmptyResult = Result; - -/* Cancellation */ -/** - * Parameters for a `notifications/cancelled` notification. - * - * @category `notifications/cancelled` - */ -export interface CancelledNotificationParams extends NotificationParams { - /** - * The ID of the request to cancel. - * - * This MUST correspond to the ID of a request previously issued in the same direction. - * This MUST be provided for cancelling non-task requests. - * This MUST NOT be used for cancelling tasks (use the `tasks/cancel` request instead). - */ - requestId?: RequestId; - - /** - * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. - */ - reason?: string; -} - -/** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its `initialize` request. - * - * For task cancellation, use the `tasks/cancel` request instead of this notification. - * - * @category `notifications/cancelled` - */ -export interface CancelledNotification extends JSONRPCNotification { - method: 'notifications/cancelled'; - params: CancelledNotificationParams; -} - -/* Initialization */ -/** - * Parameters for an `initialize` request. - * - * @category `initialize` - */ -export interface InitializeRequestParams extends RequestParams { - /** - * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. - */ - protocolVersion: string; - capabilities: ClientCapabilities; - clientInfo: Implementation; -} - -/** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - * - * @category `initialize` - */ -export interface InitializeRequest extends JSONRPCRequest { - method: 'initialize'; - params: InitializeRequestParams; -} - -/** - * After receiving an initialize request from the client, the server sends this response. - * - * @category `initialize` - */ -export interface InitializeResult extends Result { - /** - * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. - */ - protocolVersion: string; - capabilities: ServerCapabilities; - serverInfo: Implementation; - - /** - * Instructions describing how to use the server and its features. - * - * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. - */ - instructions?: string; -} - -/** - * This notification is sent from the client to the server after initialization has finished. - * - * @category `notifications/initialized` - */ -export interface InitializedNotification extends JSONRPCNotification { - method: 'notifications/initialized'; - params?: NotificationParams; -} - -/** - * 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. - * - * @category `initialize` - */ -export interface ClientCapabilities { - /** - * Experimental, non-standard capabilities that the client supports. - */ - experimental?: { [key: string]: object }; - /** - * Present if the client supports listing roots. - */ - roots?: { - /** - * Whether the client supports notifications for changes to the roots list. - */ - listChanged?: boolean; - }; - /** - * Present if the client supports sampling from an LLM. - */ - sampling?: { - /** - * Whether the client supports context inclusion via includeContext parameter. - * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). - */ - context?: object; - /** - * Whether the client supports tool use via tools and toolChoice parameters. - */ - tools?: object; - }; - /** - * Present if the client supports elicitation from the server. - */ - elicitation?: { form?: object; url?: object }; - - /** - * Present if the client supports task-augmented requests. - */ - tasks?: { - /** - * Whether this client supports tasks/list. - */ - list?: object; - /** - * Whether this client supports tasks/cancel. - */ - cancel?: object; - /** - * Specifies which request types can be augmented with tasks. - */ - requests?: { - /** - * Task support for sampling-related requests. - */ - sampling?: { - /** - * Whether the client supports task-augmented sampling/createMessage requests. - */ - createMessage?: object; - }; - /** - * Task support for elicitation-related requests. - */ - elicitation?: { - /** - * Whether the client supports task-augmented elicitation/create requests. - */ - create?: object; - }; - }; - }; -} - -/** - * 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. - * - * @category `initialize` - */ -export interface ServerCapabilities { - /** - * Experimental, non-standard capabilities that the server supports. - */ - experimental?: { [key: string]: object }; - /** - * Present if the server supports sending log messages to the client. - */ - logging?: object; - /** - * Present if the server supports argument autocompletion suggestions. - */ - completions?: object; - /** - * Present if the server offers any prompt templates. - */ - prompts?: { - /** - * Whether this server supports notifications for changes to the prompt list. - */ - listChanged?: boolean; - }; - /** - * Present if the server offers any resources to read. - */ - resources?: { - /** - * Whether this server supports subscribing to resource updates. - */ - subscribe?: boolean; - /** - * Whether this server supports notifications for changes to the resource list. - */ - listChanged?: boolean; - }; - /** - * Present if the server offers any tools to call. - */ - tools?: { - /** - * Whether this server supports notifications for changes to the tool list. - */ - listChanged?: boolean; - }; - /** - * Present if the server supports task-augmented requests. - */ - tasks?: { - /** - * Whether this server supports tasks/list. - */ - list?: object; - /** - * Whether this server supports tasks/cancel. - */ - cancel?: object; - /** - * Specifies which request types can be augmented with tasks. - */ - requests?: { - /** - * Task support for tool-related requests. - */ - tools?: { - /** - * Whether the server supports task-augmented tools/call requests. - */ - call?: object; - }; - }; - }; -} - -/** - * An optionally-sized icon that can be displayed in a user interface. - * - * @category Common Types - */ -export interface Icon { - /** - * A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a - * `data:` URI with Base64-encoded image data. - * - * Consumers SHOULD takes steps to ensure URLs serving icons are from the - * same domain as the client/server or a trusted domain. - * - * Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain - * executable JavaScript. - * - * @format uri - */ - src: string; - - /** - * Optional MIME type override if the source MIME type is missing or generic. - * For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`. - */ - mimeType?: string; - - /** - * Optional array of strings that specify sizes at which the icon can be used. - * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. - * - * If not provided, the client should assume that the icon can be used at any size. - */ - sizes?: string[]; - - /** - * Optional specifier for the theme this icon is designed for. `light` indicates - * the icon is designed to be used with a light background, and `dark` indicates - * the icon is designed to be used with a dark background. - * - * If not provided, the client should assume the icon can be used with any theme. - */ - theme?: 'light' | 'dark'; -} - -/** - * Base interface to add `icons` property. - * - * @internal - */ -export interface Icons { - /** - * Optional set of sized icons that the client can display in a user interface. - * - * Clients that support rendering icons MUST support at least the following MIME types: - * - `image/png` - PNG images (safe, universal compatibility) - * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) - * - * Clients that support rendering icons SHOULD also support: - * - `image/svg+xml` - SVG images (scalable but requires security precautions) - * - `image/webp` - WebP images (modern, efficient format) - */ - icons?: Icon[]; -} - -/** - * Base interface for metadata with name (identifier) and title (display name) properties. - * - * @internal - */ -export interface BaseMetadata { - /** - * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present). - */ - name: string; - - /** - * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, - * even by those unfamiliar with domain-specific terminology. - * - * If not provided, the name should be used for display (except for Tool, - * where `annotations.title` should be given precedence over using `name`, - * if present). - */ - title?: string; -} - -/** - * Describes the MCP implementation. - * - * @category `initialize` - */ -export interface Implementation extends BaseMetadata, Icons { - version: string; - - /** - * An optional human-readable description of what this implementation does. - * - * This can be used by clients or servers to provide context about their purpose - * and capabilities. For example, a server might describe the types of resources - * or tools it provides, while a client might describe its intended use case. - */ - description?: string; - - /** - * An optional URL of the website for this implementation. - * - * @format uri - */ - websiteUrl?: string; -} - -/* Ping */ -/** - * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. - * - * @category `ping` - */ -export interface PingRequest extends JSONRPCRequest { - method: 'ping'; - params?: RequestParams; -} - -/* Progress notifications */ - -/** - * Parameters for a `notifications/progress` notification. - * - * @category `notifications/progress` - */ -export interface ProgressNotificationParams extends NotificationParams { - /** - * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. - */ - progressToken: ProgressToken; - /** - * The progress thus far. This should increase every time progress is made, even if the total is unknown. - * - * @TJS-type number - */ - progress: number; - /** - * Total number of items to process (or total progress required), if known. - * - * @TJS-type number - */ - total?: number; - /** - * An optional message describing the current progress. - */ - message?: string; -} - -/** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - * - * @category `notifications/progress` - */ -export interface ProgressNotification extends JSONRPCNotification { - method: 'notifications/progress'; - params: ProgressNotificationParams; -} - -/* Pagination */ -/** - * Common parameters for paginated requests. - * - * @internal - */ -export interface PaginatedRequestParams extends RequestParams { - /** - * An opaque token representing the current pagination position. - * If provided, the server should return results starting after this cursor. - */ - cursor?: Cursor; -} - -/** @internal */ -export interface PaginatedRequest extends JSONRPCRequest { - params?: PaginatedRequestParams; -} - -/** @internal */ -export interface PaginatedResult extends Result { - /** - * An opaque token representing the pagination position after the last returned result. - * If present, there may be more results available. - */ - nextCursor?: Cursor; -} - -/* Resources */ -/** - * Sent from the client to request a list of resources the server has. - * - * @category `resources/list` - */ -export interface ListResourcesRequest extends PaginatedRequest { - method: 'resources/list'; -} - -/** - * The server's response to a resources/list request from the client. - * - * @category `resources/list` - */ -export interface ListResourcesResult extends PaginatedResult { - resources: Resource[]; -} - -/** - * Sent from the client to request a list of resource templates the server has. - * - * @category `resources/templates/list` - */ -export interface ListResourceTemplatesRequest extends PaginatedRequest { - method: 'resources/templates/list'; -} - -/** - * The server's response to a resources/templates/list request from the client. - * - * @category `resources/templates/list` - */ -export interface ListResourceTemplatesResult extends PaginatedResult { - resourceTemplates: ResourceTemplate[]; -} - -/** - * Common parameters when working with resources. - * - * @internal - */ -export interface ResourceRequestParams extends RequestParams { - /** - * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it. - * - * @format uri - */ - uri: string; -} - -/** - * Parameters for a `resources/read` request. - * - * @category `resources/read` - */ -// eslint-disable-next-line @typescript-eslint/no-empty-object-type -export interface ReadResourceRequestParams extends ResourceRequestParams {} - -/** - * Sent from the client to the server, to read a specific resource URI. - * - * @category `resources/read` - */ -export interface ReadResourceRequest extends JSONRPCRequest { - method: 'resources/read'; - params: ReadResourceRequestParams; -} - -/** - * The server's response to a resources/read request from the client. - * - * @category `resources/read` - */ -export interface ReadResourceResult extends Result { - contents: (TextResourceContents | BlobResourceContents)[]; -} - -/** - * 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. - * - * @category `notifications/resources/list_changed` - */ -export interface ResourceListChangedNotification extends JSONRPCNotification { - method: 'notifications/resources/list_changed'; - params?: NotificationParams; -} - -/** - * Parameters for a `resources/subscribe` request. - * - * @category `resources/subscribe` - */ -// eslint-disable-next-line @typescript-eslint/no-empty-object-type -export interface SubscribeRequestParams extends ResourceRequestParams {} - -/** - * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. - * - * @category `resources/subscribe` - */ -export interface SubscribeRequest extends JSONRPCRequest { - method: 'resources/subscribe'; - params: SubscribeRequestParams; -} - -/** - * Parameters for a `resources/unsubscribe` request. - * - * @category `resources/unsubscribe` - */ -// eslint-disable-next-line @typescript-eslint/no-empty-object-type -export interface UnsubscribeRequestParams extends ResourceRequestParams {} - -/** - * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. - * - * @category `resources/unsubscribe` - */ -export interface UnsubscribeRequest extends JSONRPCRequest { - method: 'resources/unsubscribe'; - params: UnsubscribeRequestParams; -} - -/** - * Parameters for a `notifications/resources/updated` notification. - * - * @category `notifications/resources/updated` - */ -export interface ResourceUpdatedNotificationParams extends NotificationParams { - /** - * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. - * - * @format uri - */ - uri: string; -} - -/** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. - * - * @category `notifications/resources/updated` - */ -export interface ResourceUpdatedNotification extends JSONRPCNotification { - method: 'notifications/resources/updated'; - params: ResourceUpdatedNotificationParams; -} - -/** - * A known resource that the server is capable of reading. - * - * @category `resources/list` - */ -export interface Resource extends BaseMetadata, Icons { - /** - * The URI of this resource. - * - * @format uri - */ - uri: string; - - /** - * A description of what this resource represents. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description?: string; - - /** - * The MIME type of this resource, if known. - */ - mimeType?: string; - - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - - /** - * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. - * - * This can be used by Hosts to display file sizes and estimate context window usage. - */ - size?: number; - - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; -} - -/** - * A template description for resources available on the server. - * - * @category `resources/templates/list` - */ -export interface ResourceTemplate extends BaseMetadata, Icons { - /** - * A URI template (according to RFC 6570) that can be used to construct resource URIs. - * - * @format uri-template - */ - uriTemplate: string; - - /** - * A description of what this template is for. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description?: string; - - /** - * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. - */ - mimeType?: string; - - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; -} - -/** - * The contents of a specific resource or sub-resource. - * - * @internal - */ -export interface ResourceContents { - /** - * The URI of this resource. - * - * @format uri - */ - uri: string; - /** - * The MIME type of this resource, if known. - */ - mimeType?: string; - - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; -} - -/** - * @category Content - */ -export interface TextResourceContents extends ResourceContents { - /** - * The text of the item. This must only be set if the item can actually be represented as text (not binary data). - */ - text: string; -} - -/** - * @category Content - */ -export interface BlobResourceContents extends ResourceContents { - /** - * A base64-encoded string representing the binary data of the item. - * - * @format byte - */ - blob: string; -} - -/* Prompts */ -/** - * Sent from the client to request a list of prompts and prompt templates the server has. - * - * @category `prompts/list` - */ -export interface ListPromptsRequest extends PaginatedRequest { - method: 'prompts/list'; -} - -/** - * The server's response to a prompts/list request from the client. - * - * @category `prompts/list` - */ -export interface ListPromptsResult extends PaginatedResult { - prompts: Prompt[]; -} - -/** - * Parameters for a `prompts/get` request. - * - * @category `prompts/get` - */ -export interface GetPromptRequestParams extends RequestParams { - /** - * The name of the prompt or prompt template. - */ - name: string; - /** - * Arguments to use for templating the prompt. - */ - arguments?: { [key: string]: string }; -} - -/** - * Used by the client to get a prompt provided by the server. - * - * @category `prompts/get` - */ -export interface GetPromptRequest extends JSONRPCRequest { - method: 'prompts/get'; - params: GetPromptRequestParams; -} - -/** - * The server's response to a prompts/get request from the client. - * - * @category `prompts/get` - */ -export interface GetPromptResult extends Result { - /** - * An optional description for the prompt. - */ - description?: string; - messages: PromptMessage[]; -} - -/** - * A prompt or prompt template that the server offers. - * - * @category `prompts/list` - */ -export interface Prompt extends BaseMetadata, Icons { - /** - * An optional description of what this prompt provides - */ - description?: string; - - /** - * A list of arguments to use for templating the prompt. - */ - arguments?: PromptArgument[]; - - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; -} - -/** - * Describes an argument that a prompt can accept. - * - * @category `prompts/list` - */ -export interface PromptArgument extends BaseMetadata { - /** - * A human-readable description of the argument. - */ - description?: string; - /** - * Whether this argument must be provided. - */ - required?: boolean; -} - -/** - * The sender or recipient of messages and data in a conversation. - * - * @category Common Types - */ -export type Role = 'user' | 'assistant'; - -/** - * Describes a message returned as part of a prompt. - * - * This is similar to `SamplingMessage`, but also supports the embedding of - * resources from the MCP server. - * - * @category `prompts/get` - */ -export interface PromptMessage { - role: Role; - content: ContentBlock; -} - -/** - * A resource that the server is capable of reading, included in a prompt or tool call result. - * - * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. - * - * @category Content - */ -export interface ResourceLink extends Resource { - type: 'resource_link'; -} - -/** - * The contents of a resource, embedded into a prompt or tool call result. - * - * It is up to the client how best to render embedded resources for the benefit - * of the LLM and/or the user. - * - * @category Content - */ -export interface EmbeddedResource { - type: 'resource'; - resource: TextResourceContents | BlobResourceContents; - - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; -} -/** - * 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. - * - * @category `notifications/prompts/list_changed` - */ -export interface PromptListChangedNotification extends JSONRPCNotification { - method: 'notifications/prompts/list_changed'; - params?: NotificationParams; -} - -/* Tools */ -/** - * Sent from the client to request a list of tools the server has. - * - * @category `tools/list` - */ -export interface ListToolsRequest extends PaginatedRequest { - method: 'tools/list'; -} - -/** - * The server's response to a tools/list request from the client. - * - * @category `tools/list` - */ -export interface ListToolsResult extends PaginatedResult { - tools: Tool[]; -} - -/** - * The server's response to a tool call. - * - * @category `tools/call` - */ -export interface CallToolResult extends Result { - /** - * A list of content objects that represent the unstructured result of the tool call. - */ - content: ContentBlock[]; - - /** - * An optional JSON object that represents the structured result of the tool call. - */ - structuredContent?: { [key: string]: unknown }; - - /** - * Whether the tool call ended in an error. - * - * If not set, this is assumed to be false (the call was successful). - * - * Any errors that originate from the tool SHOULD be reported inside the result - * object, with `isError` set to true, _not_ as an MCP protocol-level error - * response. Otherwise, the LLM would not be able to see that an error occurred - * and self-correct. - * - * However, any errors in _finding_ the tool, an error indicating that the - * server does not support tool calls, or any other exceptional conditions, - * should be reported as an MCP error response. - */ - isError?: boolean; -} - -/** - * Parameters for a `tools/call` request. - * - * @category `tools/call` - */ -export interface CallToolRequestParams extends TaskAugmentedRequestParams { - /** - * The name of the tool. - */ - name: string; - /** - * Arguments to use for the tool call. - */ - arguments?: { [key: string]: unknown }; -} - -/** - * Used by the client to invoke a tool provided by the server. - * - * @category `tools/call` - */ -export interface CallToolRequest extends JSONRPCRequest { - method: 'tools/call'; - params: CallToolRequestParams; -} - -/** - * 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. - * - * @category `notifications/tools/list_changed` - */ -export interface ToolListChangedNotification extends JSONRPCNotification { - method: 'notifications/tools/list_changed'; - params?: NotificationParams; -} - -/** - * Additional properties describing a Tool to clients. - * - * NOTE: all properties in ToolAnnotations are **hints**. - * They are not guaranteed to provide a faithful description of - * tool behavior (including descriptive properties like `title`). - * - * Clients should never make tool use decisions based on ToolAnnotations - * received from untrusted servers. - * - * @category `tools/list` - */ -export interface ToolAnnotations { - /** - * A human-readable title for the tool. - */ - title?: string; - - /** - * If true, the tool does not modify its environment. - * - * Default: false - */ - readOnlyHint?: boolean; - - /** - * If true, the tool may perform destructive updates to its environment. - * If false, the tool performs only additive updates. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: true - */ - destructiveHint?: boolean; - - /** - * If true, calling the tool repeatedly with the same arguments - * will have no additional effect on its environment. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: false - */ - idempotentHint?: boolean; - - /** - * If true, this tool may interact with an "open world" of external - * entities. If false, the tool's domain of interaction is closed. - * For example, the world of a web search tool is open, whereas that - * of a memory tool is not. - * - * Default: true - */ - openWorldHint?: boolean; -} - -/** - * Execution-related properties for a tool. - * - * @category `tools/list` - */ -export interface ToolExecution { - /** - * Indicates whether this tool supports task-augmented execution. - * This allows clients to handle long-running operations through polling - * the task system. - * - * - "forbidden": Tool does not support task-augmented execution (default when absent) - * - "optional": Tool may support task-augmented execution - * - "required": Tool requires task-augmented execution - * - * Default: "forbidden" - */ - taskSupport?: 'forbidden' | 'optional' | 'required'; -} - -/** - * Definition for a tool the client can call. - * - * @category `tools/list` - */ -export interface Tool extends BaseMetadata, Icons { - /** - * A human-readable description of the tool. - * - * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. - */ - description?: string; - - /** - * A JSON Schema object defining the expected parameters for the tool. - */ - inputSchema: { - $schema?: string; - type: 'object'; - properties?: { [key: string]: object }; - required?: string[]; - }; - - /** - * Execution-related properties for this tool. - */ - execution?: ToolExecution; - - /** - * An optional JSON Schema object defining the structure of the tool's output returned in - * the structuredContent field of a CallToolResult. - * - * Defaults to JSON Schema 2020-12 when no explicit $schema is provided. - * Currently restricted to type: "object" at the root level. - */ - outputSchema?: { - $schema?: string; - type: 'object'; - properties?: { [key: string]: object }; - required?: string[]; - }; - - /** - * Optional additional tool information. - * - * Display name precedence order is: title, annotations.title, then name. - */ - annotations?: ToolAnnotations; - - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; -} - -/* Tasks */ - -/** - * The status of a task. - * - * @category `tasks` - */ -export type TaskStatus = - | 'working' // The request is currently being processed - | 'input_required' // The task is waiting for input (e.g., elicitation or sampling) - | 'completed' // The request completed successfully and results are available - | 'failed' // The associated request did not complete successfully. For tool calls specifically, this includes cases where the tool call result has `isError` set to true. - | 'cancelled'; // The request was cancelled before completion - -/** - * Metadata for augmenting a request with task execution. - * Include this in the `task` field of the request parameters. - * - * @category `tasks` - */ -export interface TaskMetadata { - /** - * Requested duration in milliseconds to retain task from creation. - */ - ttl?: number; -} - -/** - * Metadata for associating messages with a task. - * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. - * - * @category `tasks` - */ -export interface RelatedTaskMetadata { - /** - * The task identifier this message is associated with. - */ - taskId: string; -} - -/** - * Data associated with a task. - * - * @category `tasks` - */ -export interface Task { - /** - * The task identifier. - */ - taskId: string; - - /** - * Current task state. - */ - status: TaskStatus; - - /** - * Optional human-readable message describing the current task state. - * This can provide context for any status, including: - * - Reasons for "cancelled" status - * - Summaries for "completed" status - * - Diagnostic information for "failed" status (e.g., error details, what went wrong) - */ - statusMessage?: string; - - /** - * ISO 8601 timestamp when the task was created. - */ - createdAt: string; - - /** - * ISO 8601 timestamp when the task was last updated. - */ - lastUpdatedAt: string; - - /** - * Actual retention duration from creation in milliseconds, null for unlimited. - */ - ttl: number | null; - - /** - * Suggested polling interval in milliseconds. - */ - pollInterval?: number; -} - -/** - * A response to a task-augmented request. - * - * @category `tasks` - */ -export interface CreateTaskResult extends Result { - task: Task; -} - -/** - * A request to retrieve the state of a task. - * - * @category `tasks/get` - */ -export interface GetTaskRequest extends JSONRPCRequest { - method: 'tasks/get'; - params: { - /** - * The task identifier to query. - */ - taskId: string; - }; -} - -/** - * The response to a tasks/get request. - * - * @category `tasks/get` - */ -export type GetTaskResult = Result & Task; - -/** - * A request to retrieve the result of a completed task. - * - * @category `tasks/result` - */ -export interface GetTaskPayloadRequest extends JSONRPCRequest { - method: 'tasks/result'; - params: { - /** - * The task identifier to retrieve results for. - */ - taskId: string; - }; -} - -/** - * The response to a tasks/result request. - * The structure matches the result type of the original request. - * For example, a tools/call task would return the CallToolResult structure. - * - * @category `tasks/result` - */ -export interface GetTaskPayloadResult extends Result { - [key: string]: unknown; -} - -/** - * A request to cancel a task. - * - * @category `tasks/cancel` - */ -export interface CancelTaskRequest extends JSONRPCRequest { - method: 'tasks/cancel'; - params: { - /** - * The task identifier to cancel. - */ - taskId: string; - }; -} - -/** - * The response to a tasks/cancel request. - * - * @category `tasks/cancel` - */ -export type CancelTaskResult = Result & Task; - -/** - * A request to retrieve a list of tasks. - * - * @category `tasks/list` - */ -export interface ListTasksRequest extends PaginatedRequest { - method: 'tasks/list'; -} - -/** - * The response to a tasks/list request. - * - * @category `tasks/list` - */ -export interface ListTasksResult extends PaginatedResult { - tasks: Task[]; -} - -/** - * Parameters for a `notifications/tasks/status` notification. - * - * @category `notifications/tasks/status` - */ -export type TaskStatusNotificationParams = NotificationParams & Task; - -/** - * An optional notification from the receiver to the requestor, informing them that a task's status has changed. Receivers are not required to send these notifications. - * - * @category `notifications/tasks/status` - */ -export interface TaskStatusNotification extends JSONRPCNotification { - method: 'notifications/tasks/status'; - params: TaskStatusNotificationParams; -} - -/* Logging */ - -/** - * Parameters for a `logging/setLevel` request. - * - * @category `logging/setLevel` - */ -export interface SetLevelRequestParams extends RequestParams { - /** - * 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/message. - */ - level: LoggingLevel; -} - -/** - * A request from the client to the server, to enable or adjust logging. - * - * @category `logging/setLevel` - */ -export interface SetLevelRequest extends JSONRPCRequest { - method: 'logging/setLevel'; - params: SetLevelRequestParams; -} - -/** - * Parameters for a `notifications/message` notification. - * - * @category `notifications/message` - */ -export interface LoggingMessageNotificationParams extends NotificationParams { - /** - * The severity of this log message. - */ - level: LoggingLevel; - /** - * An optional name of the logger issuing this message. - */ - logger?: string; - /** - * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. - */ - data: unknown; -} - -/** - * JSONRPCNotification 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. - * - * @category `notifications/message` - */ -export interface LoggingMessageNotification extends JSONRPCNotification { - method: 'notifications/message'; - params: LoggingMessageNotificationParams; -} - -/** - * The severity of a log message. - * - * These map to syslog message severities, as specified in RFC-5424: - * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 - * - * @category Common Types - */ -export type LoggingLevel = 'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency'; - -/* Sampling */ -/** - * Parameters for a `sampling/createMessage` request. - * - * @category `sampling/createMessage` - */ -export interface CreateMessageRequestParams extends TaskAugmentedRequestParams { - messages: SamplingMessage[]; - /** - * The server's preferences for which model to select. The client MAY ignore these preferences. - */ - modelPreferences?: ModelPreferences; - /** - * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. - */ - systemPrompt?: string; - /** - * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. - * The client MAY ignore this request. - * - * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client - * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. - */ - includeContext?: 'none' | 'thisServer' | 'allServers'; - /** - * @TJS-type number - */ - temperature?: number; - /** - * The requested maximum number of tokens to sample (to prevent runaway completions). - * - * The client MAY choose to sample fewer tokens than the requested maximum. - */ - maxTokens: number; - stopSequences?: string[]; - /** - * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. - */ - metadata?: object; - /** - * Tools that the model may use during generation. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. - */ - tools?: Tool[]; - /** - * Controls how the model uses tools. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. - * Default is `{ mode: "auto" }`. - */ - toolChoice?: ToolChoice; -} - -/** - * Controls tool selection behavior for sampling requests. - * - * @category `sampling/createMessage` - */ -export interface ToolChoice { - /** - * Controls the tool use ability of the model: - * - "auto": Model decides whether to use tools (default) - * - "required": Model MUST use at least one tool before completing - * - "none": Model MUST NOT use any tools - */ - mode?: 'auto' | 'required' | 'none'; -} - -/** - * 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. - * - * @category `sampling/createMessage` - */ -export interface CreateMessageRequest extends JSONRPCRequest { - method: 'sampling/createMessage'; - params: CreateMessageRequestParams; -} - -/** - * The client's response to a sampling/createMessage request from the server. - * The client should inform the user before returning the sampled message, to allow them - * to inspect the response (human in the loop) and decide whether to allow the server to see it. - * - * @category `sampling/createMessage` - */ -export interface CreateMessageResult extends Result, SamplingMessage { - /** - * The name of the model that generated the message. - */ - model: string; - - /** - * The reason why sampling stopped, if known. - * - * Standard values: - * - "endTurn": Natural end of the assistant's turn - * - "stopSequence": A stop sequence was encountered - * - "maxTokens": Maximum token limit was reached - * - "toolUse": The model wants to use one or more tools - * - * This field is an open string to allow for provider-specific stop reasons. - */ - stopReason?: 'endTurn' | 'stopSequence' | 'maxTokens' | 'toolUse' | string; -} - -/** - * Describes a message issued to or received from an LLM API. - * - * @category `sampling/createMessage` - */ -export interface SamplingMessage { - role: Role; - content: SamplingMessageContentBlock | SamplingMessageContentBlock[]; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; -} -export type SamplingMessageContentBlock = TextContent | ImageContent | AudioContent | ToolUseContent | ToolResultContent; - -/** - * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed - * - * @category Common Types - */ -export interface Annotations { - /** - * Describes who the intended audience of this object or data is. - * - * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). - */ - audience?: Role[]; - - /** - * Describes how important this data is for operating the server. - * - * A value of 1 means "most important," and indicates that the data is - * effectively required, while 0 means "least important," and indicates that - * the data is entirely optional. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - priority?: number; - - /** - * The moment the resource was last modified, as an ISO 8601 formatted string. - * - * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"). - * - * Examples: last activity timestamp in an open file, timestamp when the resource - * was attached, etc. - */ - lastModified?: string; -} - -/** - * @category Content - */ -export type ContentBlock = TextContent | ImageContent | AudioContent | ResourceLink | EmbeddedResource; - -/** - * Text provided to or from an LLM. - * - * @category Content - */ -export interface TextContent { - type: 'text'; - - /** - * The text content of the message. - */ - text: string; - - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; -} - -/** - * An image provided to or from an LLM. - * - * @category Content - */ -export interface ImageContent { - type: 'image'; - - /** - * The base64-encoded image data. - * - * @format byte - */ - data: string; - - /** - * The MIME type of the image. Different providers may support different image types. - */ - mimeType: string; - - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; -} - -/** - * Audio provided to or from an LLM. - * - * @category Content - */ -export interface AudioContent { - type: 'audio'; - - /** - * The base64-encoded audio data. - * - * @format byte - */ - data: string; - - /** - * The MIME type of the audio. Different providers may support different audio types. - */ - mimeType: string; - - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; -} - -/** - * A request from the assistant to call a tool. - * - * @category `sampling/createMessage` - */ -export interface ToolUseContent { - type: 'tool_use'; - - /** - * A unique identifier for this tool use. - * - * This ID is used to match tool results to their corresponding tool uses. - */ - id: string; - - /** - * The name of the tool to call. - */ - name: string; - - /** - * The arguments to pass to the tool, conforming to the tool's input schema. - */ - input: { [key: string]: unknown }; - - /** - * Optional metadata about the tool use. Clients SHOULD preserve this field when - * including tool uses in subsequent sampling requests to enable caching optimizations. - * - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; -} - -/** - * The result of a tool use, provided by the user back to the assistant. - * - * @category `sampling/createMessage` - */ -export interface ToolResultContent { - type: 'tool_result'; - - /** - * The ID of the tool use this result corresponds to. - * - * This MUST match the ID from a previous ToolUseContent. - */ - toolUseId: string; - - /** - * The unstructured result content of the tool use. - * - * This has the same format as CallToolResult.content and can include text, images, - * audio, resource links, and embedded resources. - */ - content: ContentBlock[]; - - /** - * An optional structured result object. - * - * If the tool defined an outputSchema, this SHOULD conform to that schema. - */ - structuredContent?: { [key: string]: unknown }; - - /** - * Whether the tool use resulted in an error. - * - * If true, the content typically describes the error that occurred. - * Default: false - */ - isError?: boolean; - - /** - * Optional metadata about the tool result. Clients SHOULD preserve this field when - * including tool results in subsequent sampling requests to enable caching optimizations. - * - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; -} - -/** - * The server's preferences for model selection, requested of the client during sampling. - * - * Because LLMs can vary along multiple dimensions, choosing the "best" model is - * rarely straightforward. Different models excel in different areas—some are - * faster but less capable, others are more capable but more expensive, and so - * on. This interface allows servers to express their priorities across multiple - * dimensions to help clients make an appropriate selection for their use case. - * - * These preferences are always advisory. The client MAY ignore them. It is also - * up to the client to decide how to interpret these preferences and how to - * balance them against other considerations. - * - * @category `sampling/createMessage` - */ -export interface ModelPreferences { - /** - * Optional hints to use for model selection. - * - * If multiple hints are specified, the client MUST evaluate them in order - * (such that the first match is taken). - * - * The client SHOULD prioritize these hints over the numeric priorities, but - * MAY still use the priorities to select from ambiguous matches. - */ - hints?: ModelHint[]; - - /** - * How much to prioritize cost when selecting a model. A value of 0 means cost - * is not important, while a value of 1 means cost is the most important - * factor. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - costPriority?: number; - - /** - * How much to prioritize sampling speed (latency) when selecting a model. A - * value of 0 means speed is not important, while a value of 1 means speed is - * the most important factor. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - speedPriority?: number; - - /** - * How much to prioritize intelligence and capabilities when selecting a - * model. A value of 0 means intelligence is not important, while a value of 1 - * means intelligence is the most important factor. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - intelligencePriority?: number; -} - -/** - * Hints to use for model selection. - * - * Keys not declared here are currently left unspecified by the spec and are up - * to the client to interpret. - * - * @category `sampling/createMessage` - */ -export interface ModelHint { - /** - * A hint for a model name. - * - * The client SHOULD treat this as a substring of a model name; for example: - * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` - * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. - * - `claude` should match any Claude model - * - * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: - * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` - */ - name?: string; -} - -/* Autocomplete */ -/** - * Parameters for a `completion/complete` request. - * - * @category `completion/complete` - */ -export interface CompleteRequestParams extends RequestParams { - ref: PromptReference | ResourceTemplateReference; - /** - * The argument's information - */ - argument: { - /** - * The name of the argument - */ - name: string; - /** - * The value of the argument to use for completion matching. - */ - value: string; - }; - - /** - * Additional, optional context for completions - */ - context?: { - /** - * Previously-resolved variables in a URI template or prompt. - */ - arguments?: { [key: string]: string }; - }; -} - -/** - * A request from the client to the server, to ask for completion options. - * - * @category `completion/complete` - */ -export interface CompleteRequest extends JSONRPCRequest { - method: 'completion/complete'; - params: CompleteRequestParams; -} - -/** - * The server's response to a completion/complete request - * - * @category `completion/complete` - */ -export interface CompleteResult extends Result { - completion: { - /** - * An array of completion values. Must not exceed 100 items. - */ - values: string[]; - /** - * The total number of completion options available. This can exceed the number of values actually sent in the response. - */ - total?: number; - /** - * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. - */ - hasMore?: boolean; - }; -} - -/** - * A reference to a resource or resource template definition. - * - * @category `completion/complete` - */ -export interface ResourceTemplateReference { - type: 'ref/resource'; - /** - * The URI or URI template of the resource. - * - * @format uri-template - */ - uri: string; -} - -/** - * Identifies a prompt. - * - * @category `completion/complete` - */ -export interface PromptReference extends BaseMetadata { - type: 'ref/prompt'; -} - -/* Roots */ -/** - * Sent from the server to request a list of root URIs from the client. Roots allow - * servers to ask for specific directories or files to operate on. A common example - * for roots is providing a set of repositories or directories a server should operate - * on. - * - * This request is typically used when the server needs to understand the file system - * structure or access specific locations that the client has permission to read from. - * - * @category `roots/list` - */ -export interface ListRootsRequest extends JSONRPCRequest { - method: 'roots/list'; - params?: RequestParams; -} - -/** - * The client's response to a roots/list request from the server. - * This result contains an array of Root objects, each representing a root directory - * or file that the server can operate on. - * - * @category `roots/list` - */ -export interface ListRootsResult extends Result { - roots: Root[]; -} - -/** - * Represents a root directory or file that the server can operate on. - * - * @category `roots/list` - */ -export interface Root { - /** - * The URI identifying the root. This *must* start with file:// for now. - * This restriction may be relaxed in future versions of the protocol to allow - * other URI schemes. - * - * @format uri - */ - uri: string; - /** - * An optional name for the root. This can be used to provide a human-readable - * identifier for the root, which may be useful for display purposes or for - * referencing the root in other parts of the application. - */ - name?: string; - - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; -} - -/** - * A notification from the client to the server, informing it that the list of roots has changed. - * This notification should be sent whenever the client adds, removes, or modifies any root. - * The server should then request an updated list of roots using the ListRootsRequest. - * - * @category `notifications/roots/list_changed` - */ -export interface RootsListChangedNotification extends JSONRPCNotification { - method: 'notifications/roots/list_changed'; - params?: NotificationParams; -} - -/** - * The parameters for a request to elicit non-sensitive information from the user via a form in the client. - * - * @category `elicitation/create` - */ -export interface ElicitRequestFormParams extends TaskAugmentedRequestParams { - /** - * The elicitation mode. - */ - mode?: 'form'; - - /** - * The message to present to the user describing what information is being requested. - */ - message: string; - - /** - * A restricted subset of JSON Schema. - * Only top-level properties are allowed, without nesting. - */ - requestedSchema: { - $schema?: string; - type: 'object'; - properties: { - [key: string]: PrimitiveSchemaDefinition; - }; - required?: string[]; - }; -} - -/** - * The parameters for a request to elicit information from the user via a URL in the client. - * - * @category `elicitation/create` - */ -export interface ElicitRequestURLParams extends TaskAugmentedRequestParams { - /** - * The elicitation mode. - */ - mode: 'url'; - - /** - * The message to present to the user explaining why the interaction is needed. - */ - message: string; - - /** - * The ID of the elicitation, which must be unique within the context of the server. - * The client MUST treat this ID as an opaque value. - */ - elicitationId: string; - - /** - * The URL that the user should navigate to. - * - * @format uri - */ - url: string; -} - -/** - * The parameters for a request to elicit additional information from the user via the client. - * - * @category `elicitation/create` - */ -export type ElicitRequestParams = ElicitRequestFormParams | ElicitRequestURLParams; - -/** - * A request from the server to elicit additional information from the user via the client. - * - * @category `elicitation/create` - */ -export interface ElicitRequest extends JSONRPCRequest { - method: 'elicitation/create'; - params: ElicitRequestParams; -} - -/** - * Restricted schema definitions that only allow primitive types - * without nested objects or arrays. - * - * @category `elicitation/create` - */ -export type PrimitiveSchemaDefinition = StringSchema | NumberSchema | BooleanSchema | EnumSchema; - -/** - * @category `elicitation/create` - */ -export interface StringSchema { - type: 'string'; - title?: string; - description?: string; - minLength?: number; - maxLength?: number; - format?: 'email' | 'uri' | 'date' | 'date-time'; - default?: string; -} - -/** - * @category `elicitation/create` - */ -export interface NumberSchema { - type: 'number' | 'integer'; - title?: string; - description?: string; - minimum?: number; - maximum?: number; - default?: number; -} - -/** - * @category `elicitation/create` - */ -export interface BooleanSchema { - type: 'boolean'; - title?: string; - description?: string; - default?: boolean; -} - -/** - * Schema for single-selection enumeration without display titles for options. - * - * @category `elicitation/create` - */ -export interface UntitledSingleSelectEnumSchema { - type: 'string'; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Array of enum values to choose from. - */ - enum: string[]; - /** - * Optional default value. - */ - default?: string; -} - -/** - * Schema for single-selection enumeration with display titles for each option. - * - * @category `elicitation/create` - */ -export interface TitledSingleSelectEnumSchema { - type: 'string'; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Array of enum options with values and display labels. - */ - oneOf: Array<{ - /** - * The enum value. - */ - const: string; - /** - * Display label for this option. - */ - title: string; - }>; - /** - * Optional default value. - */ - default?: string; -} - -/** - * @category `elicitation/create` - */ -// Combined single selection enumeration -export type SingleSelectEnumSchema = UntitledSingleSelectEnumSchema | TitledSingleSelectEnumSchema; - -/** - * Schema for multiple-selection enumeration without display titles for options. - * - * @category `elicitation/create` - */ -export interface UntitledMultiSelectEnumSchema { - type: 'array'; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Minimum number of items to select. - */ - minItems?: number; - /** - * Maximum number of items to select. - */ - maxItems?: number; - /** - * Schema for the array items. - */ - items: { - type: 'string'; - /** - * Array of enum values to choose from. - */ - enum: string[]; - }; - /** - * Optional default value. - */ - default?: string[]; -} - -/** - * Schema for multiple-selection enumeration with display titles for each option. - * - * @category `elicitation/create` - */ -export interface TitledMultiSelectEnumSchema { - type: 'array'; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Minimum number of items to select. - */ - minItems?: number; - /** - * Maximum number of items to select. - */ - maxItems?: number; - /** - * Schema for array items with enum options and display labels. - */ - items: { - /** - * Array of enum options with values and display labels. - */ - anyOf: Array<{ - /** - * The constant enum value. - */ - const: string; - /** - * Display title for this option. - */ - title: string; - }>; - }; - /** - * Optional default value. - */ - default?: string[]; -} - -/** - * @category `elicitation/create` - */ -// Combined multiple selection enumeration -export type MultiSelectEnumSchema = UntitledMultiSelectEnumSchema | TitledMultiSelectEnumSchema; - -/** - * Use TitledSingleSelectEnumSchema instead. - * This interface will be removed in a future version. - * - * @category `elicitation/create` - */ -export interface LegacyTitledEnumSchema { - type: 'string'; - title?: string; - description?: string; - enum: string[]; - /** - * (Legacy) Display names for enum values. - * Non-standard according to JSON schema 2020-12. - */ - enumNames?: string[]; - default?: string; -} - -/** - * @category `elicitation/create` - */ -// Union type for all enum schemas -export type EnumSchema = SingleSelectEnumSchema | MultiSelectEnumSchema | LegacyTitledEnumSchema; - -/** - * The client's response to an elicitation request. - * - * @category `elicitation/create` - */ -export interface ElicitResult extends Result { - /** - * The user action in response to the elicitation. - * - "accept": User submitted the form/confirmed the action - * - "decline": User explicitly decline the action - * - "cancel": User dismissed without making an explicit choice - */ - action: 'accept' | 'decline' | 'cancel'; - - /** - * The submitted form data, only present when action is "accept" and mode was "form". - * Contains values matching the requested schema. - * Omitted for out-of-band mode responses. - */ - content?: { [key: string]: string | number | boolean | string[] }; -} - -/** - * An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request. - * - * @category `notifications/elicitation/complete` - */ -export interface ElicitationCompleteNotification extends JSONRPCNotification { - method: 'notifications/elicitation/complete'; - params: { - /** - * The ID of the elicitation that completed. - */ - elicitationId: string; - }; -} - -/* Client messages */ -/** @internal */ -export type ClientRequest = - | PingRequest - | InitializeRequest - | CompleteRequest - | SetLevelRequest - | GetPromptRequest - | ListPromptsRequest - | ListResourcesRequest - | ListResourceTemplatesRequest - | ReadResourceRequest - | SubscribeRequest - | UnsubscribeRequest - | CallToolRequest - | ListToolsRequest - | GetTaskRequest - | GetTaskPayloadRequest - | ListTasksRequest - | CancelTaskRequest; - -/** @internal */ -export type ClientNotification = - | CancelledNotification - | ProgressNotification - | InitializedNotification - | RootsListChangedNotification - | TaskStatusNotification; - -/** @internal */ -export type ClientResult = - | EmptyResult - | CreateMessageResult - | ListRootsResult - | ElicitResult - | GetTaskResult - | GetTaskPayloadResult - | ListTasksResult - | CancelTaskResult; - -/* Server messages */ -/** @internal */ -export type ServerRequest = - | PingRequest - | CreateMessageRequest - | ListRootsRequest - | ElicitRequest - | GetTaskRequest - | GetTaskPayloadRequest - | ListTasksRequest - | CancelTaskRequest; - -/** @internal */ -export type ServerNotification = - | CancelledNotification - | ProgressNotification - | LoggingMessageNotification - | ResourceUpdatedNotification - | ResourceListChangedNotification - | ToolListChangedNotification - | PromptListChangedNotification - | ElicitationCompleteNotification - | TaskStatusNotification; - -/** @internal */ -export type ServerResult = - | EmptyResult - | InitializeResult - | CompleteResult - | GetPromptResult - | ListPromptsResult - | ListResourceTemplatesResult - | ListResourcesResult - | ReadResourceResult - | CallToolResult - | ListToolsResult - | GetTaskResult - | GetTaskPayloadResult - | ListTasksResult - | CancelTaskResult; diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.json deleted file mode 100644 index a6838303e4..0000000000 --- a/packages/core/tsconfig.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "@modelcontextprotocol/tsconfig", - "include": ["./"], - "exclude": ["node_modules", "dist"], - "compilerOptions": { - "paths": { - "*": ["./*"], - "@modelcontextprotocol/eslint-config": ["./node_modules/@modelcontextprotocol/eslint-config/tsconfig.json"], - "@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"] - } - } -} diff --git a/packages/core/vitest.config.js b/packages/core/vitest.config.js deleted file mode 100644 index 496fca3200..0000000000 --- a/packages/core/vitest.config.js +++ /dev/null @@ -1,3 +0,0 @@ -import baseConfig from '@modelcontextprotocol/vitest-config'; - -export default baseConfig; diff --git a/packages/server/eslint.config.mjs b/packages/server/eslint.config.mjs deleted file mode 100644 index 4f034f2235..0000000000 --- a/packages/server/eslint.config.mjs +++ /dev/null @@ -1,12 +0,0 @@ -// @ts-check - -import baseConfig from '@modelcontextprotocol/eslint-config'; - -export default [ - ...baseConfig, - { - settings: { - 'import/internal-regex': '^@modelcontextprotocol/core' - } - } -]; diff --git a/packages/server/package.json b/packages/server/package.json deleted file mode 100644 index b039751f61..0000000000 --- a/packages/server/package.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "name": "@modelcontextprotocol/server", - "version": "2.0.0-alpha.0", - "description": "Model Context Protocol implementation for TypeScript", - "license": "MIT", - "author": "Anthropic, PBC (https://anthropic.com)", - "homepage": "https://modelcontextprotocol.io", - "bugs": "https://github.com/modelcontextprotocol/typescript-sdk/issues", - "type": "module", - "repository": { - "type": "git", - "url": "git+https://github.com/modelcontextprotocol/typescript-sdk.git" - }, - "engines": { - "node": ">=20", - "pnpm": ">=10.24.0" - }, - "packageManager": "pnpm@10.24.0", - "keywords": [ - "modelcontextprotocol", - "mcp" - ], - "exports": { - ".": { - "types": "./dist/index.d.mts", - "import": "./dist/index.mjs" - } - }, - "files": [ - "dist" - ], - "scripts": { - "typecheck": "tsgo -p tsconfig.json --noEmit", - "build": "tsdown", - "build:watch": "tsdown --watch", - "prepack": "npm run build", - "lint": "eslint src/ && prettier --ignore-path ../../.prettierignore --check .", - "lint:fix": "eslint src/ --fix && prettier --ignore-path ../../.prettierignore --write .", - "check": "npm run typecheck && npm run lint", - "test": "vitest run", - "test:watch": "vitest", - "start": "npm run server", - "server": "tsx watch --clear-screen=false scripts/cli.ts server", - "client": "tsx scripts/cli.ts client" - }, - "dependencies": { - "content-type": "catalog:runtimeServerOnly", - "cors": "catalog:runtimeServerOnly", - "@hono/node-server": "catalog:runtimeServerOnly", - "hono": "catalog:runtimeServerOnly", - "express": "catalog:runtimeServerOnly", - "express-rate-limit": "catalog:runtimeServerOnly", - "raw-body": "catalog:runtimeServerOnly", - "pkce-challenge": "catalog:runtimeShared", - "zod": "catalog:runtimeShared", - "zod-to-json-schema": "catalog:runtimeShared" - }, - "peerDependencies": { - "@cfworker/json-schema": "catalog:runtimeShared", - "zod": "catalog:runtimeShared" - }, - "peerDependenciesMeta": { - "@cfworker/json-schema": { - "optional": true - }, - "zod": { - "optional": false - } - }, - "devDependencies": { - "@modelcontextprotocol/core": "workspace:^", - "@modelcontextprotocol/tsconfig": "workspace:^", - "@modelcontextprotocol/vitest-config": "workspace:^", - "@modelcontextprotocol/eslint-config": "workspace:^", - "@modelcontextprotocol/test-helpers": "workspace:^", - "@cfworker/json-schema": "catalog:runtimeShared", - "@eslint/js": "catalog:devTools", - "@types/content-type": "catalog:devTools", - "@types/cors": "catalog:devTools", - "@types/cross-spawn": "catalog:devTools", - "@types/eventsource": "catalog:devTools", - "@types/express": "catalog:devTools", - "@types/express-serve-static-core": "catalog:devTools", - "@types/supertest": "catalog:devTools", - "@typescript/native-preview": "catalog:devTools", - "eslint": "catalog:devTools", - "eslint-config-prettier": "catalog:devTools", - "eslint-plugin-n": "catalog:devTools", - "prettier": "catalog:devTools", - "supertest": "catalog:devTools", - "tsdown": "catalog:devTools", - "tsx": "catalog:devTools", - "typescript": "catalog:devTools", - "typescript-eslint": "catalog:devTools", - "vitest": "catalog:devTools" - } -} diff --git a/packages/server/src/experimental/tasks/index.ts b/packages/server/src/experimental/tasks/index.ts deleted file mode 100644 index 51ebd7fec5..0000000000 --- a/packages/server/src/experimental/tasks/index.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * Experimental task features for MCP SDK. - * WARNING: These APIs are experimental and may change without notice. - * - * @experimental - */ - -// SDK implementation interfaces -export * from './interfaces.js'; - -// Wrapper classes -export * from './mcp-server.js'; -export * from './server.js'; diff --git a/packages/server/src/experimental/tasks/interfaces.ts b/packages/server/src/experimental/tasks/interfaces.ts deleted file mode 100644 index 0b32be2130..0000000000 --- a/packages/server/src/experimental/tasks/interfaces.ts +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Experimental task interfaces for MCP SDK. - * WARNING: These APIs are experimental and may change without notice. - */ - -import type { - AnySchema, - CallToolResult, - CreateTaskRequestHandlerExtra, - CreateTaskResult, - GetTaskResult, - Result, - TaskRequestHandlerExtra, - ZodRawShapeCompat -} from '@modelcontextprotocol/core'; - -import type { BaseToolCallback } from '../../server/mcp.js'; - -// ============================================================================ -// Task Handler Types (for registerToolTask) -// ============================================================================ - -/** - * Handler for creating a task. - * @experimental - */ -export type CreateTaskRequestHandler< - SendResultT extends Result, - Args extends undefined | ZodRawShapeCompat | AnySchema = undefined -> = BaseToolCallback; - -/** - * Handler for task operations (get, getResult). - * @experimental - */ -export type TaskRequestHandler< - SendResultT extends Result, - Args extends undefined | ZodRawShapeCompat | AnySchema = undefined -> = BaseToolCallback; - -/** - * Interface for task-based tool handlers. - * @experimental - */ -export interface ToolTaskHandler { - createTask: CreateTaskRequestHandler; - getTask: TaskRequestHandler; - getTaskResult: TaskRequestHandler; -} diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts deleted file mode 100644 index 4b0c420538..0000000000 --- a/packages/server/src/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -export * from './server/completable.js'; -export * from './server/express.js'; -export * from './server/mcp.js'; -export * from './server/server.js'; -export * from './server/sse.js'; -export * from './server/stdio.js'; -export * from './server/streamableHttp.js'; -export * from './server/webStandardStreamableHttp.js'; - -// auth exports -export * from './server/auth/index.js'; - -// experimental exports -export * from './experimental/index.js'; - -// re-export shared types -export * from '@modelcontextprotocol/core'; diff --git a/packages/server/src/server/auth/index.ts b/packages/server/src/server/auth/index.ts deleted file mode 100644 index 5369224cfc..0000000000 --- a/packages/server/src/server/auth/index.ts +++ /dev/null @@ -1,12 +0,0 @@ -export * from './clients.js'; -export * from './handlers/authorize.js'; -export * from './handlers/metadata.js'; -export * from './handlers/register.js'; -export * from './handlers/revoke.js'; -export * from './handlers/token.js'; -export * from './middleware/allowedMethods.js'; -export * from './middleware/bearerAuth.js'; -export * from './middleware/clientAuth.js'; -export * from './provider.js'; -export * from './providers/proxyProvider.js'; -export * from './router.js'; diff --git a/packages/server/src/server/streamableHttp.ts b/packages/server/src/server/streamableHttp.ts deleted file mode 100644 index f9ee07ca88..0000000000 --- a/packages/server/src/server/streamableHttp.ts +++ /dev/null @@ -1,189 +0,0 @@ -/** - * Node.js HTTP Streamable HTTP Server Transport - * - * This is a thin wrapper around `WebStandardStreamableHTTPServerTransport` that provides - * compatibility with Node.js HTTP server (IncomingMessage/ServerResponse). - * - * For web-standard environments (Cloudflare Workers, Deno, Bun), use `WebStandardStreamableHTTPServerTransport` directly. - */ - -import type { IncomingMessage, ServerResponse } from 'node:http'; - -import { getRequestListener } from '@hono/node-server'; -import type { AuthInfo, JSONRPCMessage, MessageExtraInfo, RequestId, Transport } from '@modelcontextprotocol/core'; - -import type { WebStandardStreamableHTTPServerTransportOptions } from './webStandardStreamableHttp.js'; -import { WebStandardStreamableHTTPServerTransport } from './webStandardStreamableHttp.js'; - -/** - * Configuration options for StreamableHTTPServerTransport - * - * This is an alias for WebStandardStreamableHTTPServerTransportOptions for backward compatibility. - */ -export type StreamableHTTPServerTransportOptions = WebStandardStreamableHTTPServerTransportOptions; - -/** - * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. - * It supports both SSE streaming and direct HTTP responses. - * - * This is a wrapper around `WebStandardStreamableHTTPServerTransport` that provides Node.js HTTP compatibility. - * It uses the `@hono/node-server` library to convert between Node.js HTTP and Web Standard APIs. - * - * Usage example: - * - * ```typescript - * // Stateful mode - server sets the session ID - * const statefulTransport = new StreamableHTTPServerTransport({ - * sessionIdGenerator: () => randomUUID(), - * }); - * - * // Stateless mode - explicitly set session ID to undefined - * const statelessTransport = new StreamableHTTPServerTransport({ - * sessionIdGenerator: undefined, - * }); - * - * // Using with pre-parsed request body - * app.post('/mcp', (req, res) => { - * transport.handleRequest(req, res, req.body); - * }); - * ``` - * - * In stateful mode: - * - Session ID is generated and included in response headers - * - Session ID is always included in initialization responses - * - Requests with invalid session IDs are rejected with 404 Not Found - * - Non-initialization requests without a session ID are rejected with 400 Bad Request - * - State is maintained in-memory (connections, message history) - * - * In stateless mode: - * - No Session ID is included in any responses - * - No session validation is performed - */ -export class StreamableHTTPServerTransport implements Transport { - private _webStandardTransport: WebStandardStreamableHTTPServerTransport; - private _requestListener: ReturnType; - // Store auth and parsedBody per request for passing through to handleRequest - private _requestContext: WeakMap = new WeakMap(); - - constructor(options: StreamableHTTPServerTransportOptions = {}) { - this._webStandardTransport = new WebStandardStreamableHTTPServerTransport(options); - - // Create a request listener that wraps the web standard transport - // getRequestListener converts Node.js HTTP to Web Standard and properly handles SSE streaming - this._requestListener = getRequestListener(async (webRequest: Request) => { - // Get context if available (set during handleRequest) - const context = this._requestContext.get(webRequest); - return this._webStandardTransport.handleRequest(webRequest, { - authInfo: context?.authInfo, - parsedBody: context?.parsedBody - }); - }); - } - - /** - * Gets the session ID for this transport instance. - */ - get sessionId(): string | undefined { - return this._webStandardTransport.sessionId; - } - - /** - * Sets callback for when the transport is closed. - */ - set onclose(handler: (() => void) | undefined) { - this._webStandardTransport.onclose = handler; - } - - get onclose(): (() => void) | undefined { - return this._webStandardTransport.onclose; - } - - /** - * Sets callback for transport errors. - */ - set onerror(handler: ((error: Error) => void) | undefined) { - this._webStandardTransport.onerror = handler; - } - - get onerror(): ((error: Error) => void) | undefined { - return this._webStandardTransport.onerror; - } - - /** - * Sets callback for incoming messages. - */ - set onmessage(handler: ((message: JSONRPCMessage, extra?: MessageExtraInfo) => void) | undefined) { - this._webStandardTransport.onmessage = handler; - } - - get onmessage(): ((message: JSONRPCMessage, extra?: MessageExtraInfo) => void) | undefined { - return this._webStandardTransport.onmessage; - } - - /** - * Starts the transport. This is required by the Transport interface but is a no-op - * for the Streamable HTTP transport as connections are managed per-request. - */ - async start(): Promise { - return this._webStandardTransport.start(); - } - - /** - * Closes the transport and all active connections. - */ - async close(): Promise { - return this._webStandardTransport.close(); - } - - /** - * Sends a JSON-RPC message through the transport. - */ - async send(message: JSONRPCMessage, options?: { relatedRequestId?: RequestId }): Promise { - return this._webStandardTransport.send(message, options); - } - - /** - * Handles an incoming HTTP request, whether GET or POST. - * - * This method converts Node.js HTTP objects to Web Standard Request/Response - * and delegates to the underlying WebStandardStreamableHTTPServerTransport. - * - * @param req - Node.js IncomingMessage, optionally with auth property from middleware - * @param res - Node.js ServerResponse - * @param parsedBody - Optional pre-parsed body from body-parser middleware - */ - async handleRequest(req: IncomingMessage & { auth?: AuthInfo }, res: ServerResponse, parsedBody?: unknown): Promise { - // Store context for this request to pass through auth and parsedBody - // We need to intercept the request creation to attach this context - const authInfo = req.auth; - - // Create a custom handler that includes our context - const handler = getRequestListener(async (webRequest: Request) => { - return this._webStandardTransport.handleRequest(webRequest, { - authInfo, - parsedBody - }); - }); - - // Delegate to the request listener which handles all the Node.js <-> Web Standard conversion - // including proper SSE streaming support - await handler(req, res); - } - - /** - * Close an SSE stream for a specific request, triggering client reconnection. - * Use this to implement polling behavior during long-running operations - - * client will reconnect after the retry interval specified in the priming event. - */ - closeSSEStream(requestId: RequestId): void { - this._webStandardTransport.closeSSEStream(requestId); - } - - /** - * Close the standalone GET SSE stream, triggering client reconnection. - * Use this to implement polling behavior for server-initiated notifications. - */ - closeStandaloneSSEStream(): void { - this._webStandardTransport.closeStandaloneSSEStream(); - } -} diff --git a/packages/server/src/server/webStandardStreamableHttp.ts b/packages/server/src/server/webStandardStreamableHttp.ts deleted file mode 100644 index 082c904e1c..0000000000 --- a/packages/server/src/server/webStandardStreamableHttp.ts +++ /dev/null @@ -1,994 +0,0 @@ -/** - * Web Standards Streamable HTTP Server Transport - * - * This is the core transport implementation using Web Standard APIs (Request, Response, ReadableStream). - * It can run on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. - * - * For Node.js Express/HTTP compatibility, use `StreamableHTTPServerTransport` which wraps this transport. - */ - -import { TextEncoder } from 'node:util'; - -import type { AuthInfo, JSONRPCMessage, MessageExtraInfo, RequestId, RequestInfo, Transport } from '@modelcontextprotocol/core'; -import { - DEFAULT_NEGOTIATED_PROTOCOL_VERSION, - isInitializeRequest, - isJSONRPCErrorResponse, - isJSONRPCRequest, - isJSONRPCResultResponse, - JSONRPCMessageSchema, - SUPPORTED_PROTOCOL_VERSIONS -} from '@modelcontextprotocol/core'; - -export type StreamId = string; -export type EventId = string; - -/** - * Interface for resumability support via event storage - */ -export interface EventStore { - /** - * Stores an event for later retrieval - * @param streamId ID of the stream the event belongs to - * @param message The JSON-RPC message to store - * @returns The generated event ID for the stored event - */ - storeEvent(streamId: StreamId, message: JSONRPCMessage): Promise; - - /** - * Get the stream ID associated with a given event ID. - * @param eventId The event ID to look up - * @returns The stream ID, or undefined if not found - * - * Optional: If not provided, the SDK will use the streamId returned by - * replayEventsAfter for stream mapping. - */ - getStreamIdForEventId?(eventId: EventId): Promise; - - replayEventsAfter( - lastEventId: EventId, - { - send - }: { - send: (eventId: EventId, message: JSONRPCMessage) => Promise; - } - ): Promise; -} - -/** - * Internal stream mapping for managing SSE connections - */ -interface StreamMapping { - /** Stream controller for pushing SSE data - only used with ReadableStream approach */ - controller?: ReadableStreamDefaultController; - /** Text encoder for SSE formatting */ - encoder?: TextEncoder; - /** Promise resolver for JSON response mode */ - resolveJson?: (response: Response) => void; - /** Cleanup function to close stream and remove mapping */ - cleanup: () => void; -} - -/** - * Configuration options for WebStandardStreamableHTTPServerTransport - */ -export interface WebStandardStreamableHTTPServerTransportOptions { - /** - * Function that generates a session ID for the transport. - * The session ID SHOULD be globally unique and cryptographically secure (e.g., a securely generated UUID, a JWT, or a cryptographic hash) - * - * If not provided, session management is disabled (stateless mode). - */ - sessionIdGenerator?: () => string; - - /** - * A callback for session initialization events - * This is called when the server initializes a new session. - * Useful in cases when you need to register multiple mcp sessions - * and need to keep track of them. - * @param sessionId The generated session ID - */ - onsessioninitialized?: (sessionId: string) => void | Promise; - - /** - * A callback for session close events - * This is called when the server closes a session due to a DELETE request. - * Useful in cases when you need to clean up resources associated with the session. - * Note that this is different from the transport closing, if you are handling - * HTTP requests from multiple nodes you might want to close each - * WebStandardStreamableHTTPServerTransport after a request is completed while still keeping the - * session open/running. - * @param sessionId The session ID that was closed - */ - onsessionclosed?: (sessionId: string) => void | Promise; - - /** - * If true, the server will return JSON responses instead of starting an SSE stream. - * This can be useful for simple request/response scenarios without streaming. - * Default is false (SSE streams are preferred). - */ - enableJsonResponse?: boolean; - - /** - * Event store for resumability support - * If provided, resumability will be enabled, allowing clients to reconnect and resume messages - */ - eventStore?: EventStore; - - /** - * List of allowed host header values for DNS rebinding protection. - * If not specified, host validation is disabled. - * @deprecated Use external middleware for host validation instead. - */ - allowedHosts?: string[]; - - /** - * List of allowed origin header values for DNS rebinding protection. - * If not specified, origin validation is disabled. - * @deprecated Use external middleware for origin validation instead. - */ - allowedOrigins?: string[]; - - /** - * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). - * Default is false for backwards compatibility. - * @deprecated Use external middleware for DNS rebinding protection instead. - */ - enableDnsRebindingProtection?: boolean; - - /** - * Retry interval in milliseconds to suggest to clients in SSE retry field. - * When set, the server will send a retry field in SSE priming events to control - * client reconnection timing for polling behavior. - */ - retryInterval?: number; -} - -/** - * Options for handling a request - */ -export interface HandleRequestOptions { - /** - * Pre-parsed request body. If provided, the transport will use this instead of parsing req.json(). - * Useful when using body-parser middleware that has already parsed the body. - */ - parsedBody?: unknown; - - /** - * Authentication info from middleware. If provided, will be passed to message handlers. - */ - authInfo?: AuthInfo; -} - -/** - * Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification - * using Web Standard APIs (Request, Response, ReadableStream). - * - * This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. - * - * Usage example: - * - * ```typescript - * // Stateful mode - server sets the session ID - * const statefulTransport = new WebStandardStreamableHTTPServerTransport({ - * sessionIdGenerator: () => crypto.randomUUID(), - * }); - * - * // Stateless mode - explicitly set session ID to undefined - * const statelessTransport = new WebStandardStreamableHTTPServerTransport({ - * sessionIdGenerator: undefined, - * }); - * - * // Hono.js usage - * app.all('/mcp', async (c) => { - * return transport.handleRequest(c.req.raw); - * }); - * - * // Cloudflare Workers usage - * export default { - * async fetch(request: Request): Promise { - * return transport.handleRequest(request); - * } - * }; - * ``` - * - * In stateful mode: - * - Session ID is generated and included in response headers - * - Session ID is always included in initialization responses - * - Requests with invalid session IDs are rejected with 404 Not Found - * - Non-initialization requests without a session ID are rejected with 400 Bad Request - * - State is maintained in-memory (connections, message history) - * - * In stateless mode: - * - No Session ID is included in any responses - * - No session validation is performed - */ -export class WebStandardStreamableHTTPServerTransport implements Transport { - // when sessionId is not set (undefined), it means the transport is in stateless mode - private sessionIdGenerator: (() => string) | undefined; - private _started: boolean = false; - private _streamMapping: Map = new Map(); - private _requestToStreamMapping: Map = new Map(); - private _requestResponseMap: Map = new Map(); - private _initialized: boolean = false; - private _enableJsonResponse: boolean = false; - private _standaloneSseStreamId: string = '_GET_stream'; - private _eventStore?: EventStore; - private _onsessioninitialized?: (sessionId: string) => void | Promise; - private _onsessionclosed?: (sessionId: string) => void | Promise; - private _allowedHosts?: string[]; - private _allowedOrigins?: string[]; - private _enableDnsRebindingProtection: boolean; - private _retryInterval?: number; - - sessionId?: string; - onclose?: () => void; - onerror?: (error: Error) => void; - onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; - - constructor(options: WebStandardStreamableHTTPServerTransportOptions = {}) { - this.sessionIdGenerator = options.sessionIdGenerator; - this._enableJsonResponse = options.enableJsonResponse ?? false; - this._eventStore = options.eventStore; - this._onsessioninitialized = options.onsessioninitialized; - this._onsessionclosed = options.onsessionclosed; - this._allowedHosts = options.allowedHosts; - this._allowedOrigins = options.allowedOrigins; - this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; - this._retryInterval = options.retryInterval; - } - - /** - * Starts the transport. This is required by the Transport interface but is a no-op - * for the Streamable HTTP transport as connections are managed per-request. - */ - async start(): Promise { - if (this._started) { - throw new Error('Transport already started'); - } - this._started = true; - } - - /** - * Helper to create a JSON error response - */ - private createJsonErrorResponse( - status: number, - code: number, - message: string, - options?: { headers?: Record; data?: string } - ): Response { - const error: { code: number; message: string; data?: string } = { code, message }; - if (options?.data !== undefined) { - error.data = options.data; - } - return new Response( - JSON.stringify({ - jsonrpc: '2.0', - error, - id: null - }), - { - status, - headers: { - 'Content-Type': 'application/json', - ...options?.headers - } - } - ); - } - - /** - * Validates request headers for DNS rebinding protection. - * @returns Error response if validation fails, undefined if validation passes. - */ - private validateRequestHeaders(req: Request): Response | undefined { - // Skip validation if protection is not enabled - if (!this._enableDnsRebindingProtection) { - return undefined; - } - - // Validate Host header if allowedHosts is configured - if (this._allowedHosts && this._allowedHosts.length > 0) { - const hostHeader = req.headers.get('host'); - if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { - const error = `Invalid Host header: ${hostHeader}`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(403, -32000, error); - } - } - - // Validate Origin header if allowedOrigins is configured - if (this._allowedOrigins && this._allowedOrigins.length > 0) { - const originHeader = req.headers.get('origin'); - if (originHeader && !this._allowedOrigins.includes(originHeader)) { - const error = `Invalid Origin header: ${originHeader}`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(403, -32000, error); - } - } - - return undefined; - } - - /** - * Handles an incoming HTTP request, whether GET, POST, or DELETE - * Returns a Response object (Web Standard) - */ - async handleRequest(req: Request, options?: HandleRequestOptions): Promise { - // Validate request headers for DNS rebinding protection - const validationError = this.validateRequestHeaders(req); - if (validationError) { - return validationError; - } - - switch (req.method) { - case 'POST': - return this.handlePostRequest(req, options); - case 'GET': - return this.handleGetRequest(req); - case 'DELETE': - return this.handleDeleteRequest(req); - default: - return this.handleUnsupportedRequest(); - } - } - - /** - * Writes a priming event to establish resumption capability. - * Only sends if eventStore is configured (opt-in for resumability) and - * the client's protocol version supports empty SSE data (>= 2025-11-25). - */ - private async writePrimingEvent( - controller: ReadableStreamDefaultController, - encoder: TextEncoder, - streamId: string, - protocolVersion: string - ): Promise { - if (!this._eventStore) { - return; - } - - // Priming events have empty data which older clients cannot handle. - // Only send priming events to clients with protocol version >= 2025-11-25 - // which includes the fix for handling empty SSE data. - if (protocolVersion < '2025-11-25') { - return; - } - - const primingEventId = await this._eventStore.storeEvent(streamId, {} as JSONRPCMessage); - - let primingEvent = `id: ${primingEventId}\ndata: \n\n`; - if (this._retryInterval !== undefined) { - primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; - } - controller.enqueue(encoder.encode(primingEvent)); - } - - /** - * Handles GET requests for SSE stream - */ - private async handleGetRequest(req: Request): Promise { - // The client MUST include an Accept header, listing text/event-stream as a supported content type. - const acceptHeader = req.headers.get('accept'); - if (!acceptHeader?.includes('text/event-stream')) { - return this.createJsonErrorResponse(406, -32000, 'Not Acceptable: Client must accept text/event-stream'); - } - - // If an Mcp-Session-Id is returned by the server during initialization, - // clients using the Streamable HTTP transport MUST include it - // in the Mcp-Session-Id header on all of their subsequent HTTP requests. - const sessionError = this.validateSession(req); - if (sessionError) { - return sessionError; - } - const protocolError = this.validateProtocolVersion(req); - if (protocolError) { - return protocolError; - } - - // Handle resumability: check for Last-Event-ID header - if (this._eventStore) { - const lastEventId = req.headers.get('last-event-id'); - if (lastEventId) { - return this.replayEvents(lastEventId); - } - } - - // Check if there's already an active standalone SSE stream for this session - if (this._streamMapping.get(this._standaloneSseStreamId) !== undefined) { - // Only one GET SSE stream is allowed per session - return this.createJsonErrorResponse(409, -32000, 'Conflict: Only one SSE stream is allowed per session'); - } - - const encoder = new TextEncoder(); - let streamController: ReadableStreamDefaultController; - - // Create a ReadableStream with a controller we can use to push SSE events - const readable = new ReadableStream({ - start: controller => { - streamController = controller; - }, - cancel: () => { - // Stream was cancelled by client - this._streamMapping.delete(this._standaloneSseStreamId); - } - }); - - const headers: Record = { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }; - - // After initialization, always include the session ID if we have one - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - - // Store the stream mapping with the controller for pushing data - this._streamMapping.set(this._standaloneSseStreamId, { - controller: streamController!, - encoder, - cleanup: () => { - this._streamMapping.delete(this._standaloneSseStreamId); - try { - streamController!.close(); - } catch { - // Controller might already be closed - } - } - }); - - return new Response(readable, { headers }); - } - - /** - * Replays events that would have been sent after the specified event ID - * Only used when resumability is enabled - */ - private async replayEvents(lastEventId: string): Promise { - if (!this._eventStore) { - return this.createJsonErrorResponse(400, -32000, 'Event store not configured'); - } - - try { - // If getStreamIdForEventId is available, use it for conflict checking - let streamId: string | undefined; - if (this._eventStore.getStreamIdForEventId) { - streamId = await this._eventStore.getStreamIdForEventId(lastEventId); - - if (!streamId) { - return this.createJsonErrorResponse(400, -32000, 'Invalid event ID format'); - } - - // Check conflict with the SAME streamId we'll use for mapping - if (this._streamMapping.get(streamId) !== undefined) { - return this.createJsonErrorResponse(409, -32000, 'Conflict: Stream already has an active connection'); - } - } - - const headers: Record = { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache, no-transform', - Connection: 'keep-alive' - }; - - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - - // Create a ReadableStream with controller for SSE - const encoder = new TextEncoder(); - let streamController: ReadableStreamDefaultController; - - const readable = new ReadableStream({ - start: controller => { - streamController = controller; - }, - cancel: () => { - // Stream was cancelled by client - // Cleanup will be handled by the mapping - } - }); - - // Replay events - returns the streamId for backwards compatibility - const replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { - send: async (eventId: string, message: JSONRPCMessage) => { - const success = this.writeSSEEvent(streamController!, encoder, message, eventId); - if (!success) { - this.onerror?.(new Error('Failed replay events')); - try { - streamController!.close(); - } catch { - // Controller might already be closed - } - } - } - }); - - this._streamMapping.set(replayedStreamId, { - controller: streamController!, - encoder, - cleanup: () => { - this._streamMapping.delete(replayedStreamId); - try { - streamController!.close(); - } catch { - // Controller might already be closed - } - } - }); - - return new Response(readable, { headers }); - } catch (error) { - this.onerror?.(error as Error); - return this.createJsonErrorResponse(500, -32000, 'Error replaying events'); - } - } - - /** - * Writes an event to an SSE stream via controller with proper formatting - */ - private writeSSEEvent( - controller: ReadableStreamDefaultController, - encoder: TextEncoder, - message: JSONRPCMessage, - eventId?: string - ): boolean { - try { - let eventData = `event: message\n`; - // Include event ID if provided - this is important for resumability - if (eventId) { - eventData += `id: ${eventId}\n`; - } - eventData += `data: ${JSON.stringify(message)}\n\n`; - controller.enqueue(encoder.encode(eventData)); - return true; - } catch { - return false; - } - } - - /** - * Handles unsupported requests (PUT, PATCH, etc.) - */ - private handleUnsupportedRequest(): Response { - return new Response( - JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32000, - message: 'Method not allowed.' - }, - id: null - }), - { - status: 405, - headers: { - Allow: 'GET, POST, DELETE', - 'Content-Type': 'application/json' - } - } - ); - } - - /** - * Handles POST requests containing JSON-RPC messages - */ - private async handlePostRequest(req: Request, options?: HandleRequestOptions): Promise { - try { - // Validate the Accept header - const acceptHeader = req.headers.get('accept'); - // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types. - if (!acceptHeader?.includes('application/json') || !acceptHeader.includes('text/event-stream')) { - return this.createJsonErrorResponse( - 406, - -32000, - 'Not Acceptable: Client must accept both application/json and text/event-stream' - ); - } - - const ct = req.headers.get('content-type'); - if (!ct || !ct.includes('application/json')) { - return this.createJsonErrorResponse(415, -32000, 'Unsupported Media Type: Content-Type must be application/json'); - } - - // Build request info from headers - const requestInfo: RequestInfo = { - headers: Object.fromEntries(req.headers.entries()) - }; - - let rawMessage; - if (options?.parsedBody !== undefined) { - rawMessage = options.parsedBody; - } else { - try { - rawMessage = await req.json(); - } catch { - return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON'); - } - } - - let messages: JSONRPCMessage[]; - - // handle batch and single messages - try { - if (Array.isArray(rawMessage)) { - messages = rawMessage.map(msg => JSONRPCMessageSchema.parse(msg)); - } else { - messages = [JSONRPCMessageSchema.parse(rawMessage)]; - } - } catch { - return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON-RPC message'); - } - - // Check if this is an initialization request - // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/ - const isInitializationRequest = messages.some(isInitializeRequest); - if (isInitializationRequest) { - // If it's a server with session management and the session ID is already set we should reject the request - // to avoid re-initialization. - if (this._initialized && this.sessionId !== undefined) { - return this.createJsonErrorResponse(400, -32600, 'Invalid Request: Server already initialized'); - } - if (messages.length > 1) { - return this.createJsonErrorResponse(400, -32600, 'Invalid Request: Only one initialization request is allowed'); - } - this.sessionId = this.sessionIdGenerator?.(); - this._initialized = true; - - // If we have a session ID and an onsessioninitialized handler, call it immediately - // This is needed in cases where the server needs to keep track of multiple sessions - if (this.sessionId && this._onsessioninitialized) { - await Promise.resolve(this._onsessioninitialized(this.sessionId)); - } - } - if (!isInitializationRequest) { - // If an Mcp-Session-Id is returned by the server during initialization, - // clients using the Streamable HTTP transport MUST include it - // in the Mcp-Session-Id header on all of their subsequent HTTP requests. - const sessionError = this.validateSession(req); - if (sessionError) { - return sessionError; - } - // Mcp-Protocol-Version header is required for all requests after initialization. - const protocolError = this.validateProtocolVersion(req); - if (protocolError) { - return protocolError; - } - } - - // check if it contains requests - const hasRequests = messages.some(isJSONRPCRequest); - - if (!hasRequests) { - // if it only contains notifications or responses, return 202 - for (const message of messages) { - this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo }); - } - return new Response(null, { status: 202 }); - } - - // The default behavior is to use SSE streaming - // but in some cases server will return JSON responses - const streamId = crypto.randomUUID(); - - // Extract protocol version for priming event decision. - // For initialize requests, get from request params. - // For other requests, get from header (already validated). - const initRequest = messages.find(m => isInitializeRequest(m)); - const clientProtocolVersion = initRequest - ? initRequest.params.protocolVersion - : (req.headers.get('mcp-protocol-version') ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION); - - if (this._enableJsonResponse) { - // For JSON response mode, return a Promise that resolves when all responses are ready - return new Promise(resolve => { - this._streamMapping.set(streamId, { - resolveJson: resolve, - cleanup: () => { - this._streamMapping.delete(streamId); - } - }); - - for (const message of messages) { - if (isJSONRPCRequest(message)) { - this._requestToStreamMapping.set(message.id, streamId); - } - } - - for (const message of messages) { - this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo }); - } - }); - } - - // SSE streaming mode - use ReadableStream with controller for more reliable data pushing - const encoder = new TextEncoder(); - let streamController: ReadableStreamDefaultController; - - const readable = new ReadableStream({ - start: controller => { - streamController = controller; - }, - cancel: () => { - // Stream was cancelled by client - this._streamMapping.delete(streamId); - } - }); - - const headers: Record = { - 'Content-Type': 'text/event-stream', - 'Cache-Control': 'no-cache', - Connection: 'keep-alive' - }; - - // After initialization, always include the session ID if we have one - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - - // Store the response for this request to send messages back through this connection - // We need to track by request ID to maintain the connection - for (const message of messages) { - if (isJSONRPCRequest(message)) { - this._streamMapping.set(streamId, { - controller: streamController!, - encoder, - cleanup: () => { - this._streamMapping.delete(streamId); - try { - streamController!.close(); - } catch { - // Controller might already be closed - } - } - }); - this._requestToStreamMapping.set(message.id, streamId); - } - } - - // Write priming event if event store is configured (after mapping is set up) - await this.writePrimingEvent(streamController!, encoder, streamId, clientProtocolVersion); - - // handle each message - for (const message of messages) { - // Build closeSSEStream callback for requests when eventStore is configured - // AND client supports resumability (protocol version >= 2025-11-25). - // Old clients can't resume if the stream is closed early because they - // didn't receive a priming event with an event ID. - let closeSSEStream: (() => void) | undefined; - let closeStandaloneSSEStream: (() => void) | undefined; - if (isJSONRPCRequest(message) && this._eventStore && clientProtocolVersion >= '2025-11-25') { - closeSSEStream = () => { - this.closeSSEStream(message.id); - }; - closeStandaloneSSEStream = () => { - this.closeStandaloneSSEStream(); - }; - } - - this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo, closeSSEStream, closeStandaloneSSEStream }); - } - // The server SHOULD NOT close the SSE stream before sending all JSON-RPC responses - // This will be handled by the send() method when responses are ready - - return new Response(readable, { status: 200, headers }); - } catch (error) { - // return JSON-RPC formatted error - this.onerror?.(error as Error); - return this.createJsonErrorResponse(400, -32700, 'Parse error', { data: String(error) }); - } - } - - /** - * Handles DELETE requests to terminate sessions - */ - private async handleDeleteRequest(req: Request): Promise { - const sessionError = this.validateSession(req); - if (sessionError) { - return sessionError; - } - const protocolError = this.validateProtocolVersion(req); - if (protocolError) { - return protocolError; - } - - await Promise.resolve(this._onsessionclosed?.(this.sessionId!)); - await this.close(); - return new Response(null, { status: 200 }); - } - - /** - * Validates session ID for non-initialization requests. - * Returns Response error if invalid, undefined otherwise - */ - private validateSession(req: Request): Response | undefined { - if (this.sessionIdGenerator === undefined) { - // If the sessionIdGenerator ID is not set, the session management is disabled - // and we don't need to validate the session ID - return undefined; - } - if (!this._initialized) { - // If the server has not been initialized yet, reject all requests - return this.createJsonErrorResponse(400, -32000, 'Bad Request: Server not initialized'); - } - - const sessionId = req.headers.get('mcp-session-id'); - - if (!sessionId) { - // Non-initialization requests without a session ID should return 400 Bad Request - return this.createJsonErrorResponse(400, -32000, 'Bad Request: Mcp-Session-Id header is required'); - } - - if (sessionId !== this.sessionId) { - // Reject requests with invalid session ID with 404 Not Found - return this.createJsonErrorResponse(404, -32001, 'Session not found'); - } - - return undefined; - } - - /** - * Validates the MCP-Protocol-Version header on incoming requests. - * - * For initialization: Version negotiation handles unknown versions gracefully - * (server responds with its supported version). - * - * For subsequent requests with MCP-Protocol-Version header: - * - Accept if in supported list - * - 400 if unsupported - * - * For HTTP requests without the MCP-Protocol-Version header: - * - Accept and default to the version negotiated at initialization - */ - private validateProtocolVersion(req: Request): Response | undefined { - const protocolVersion = req.headers.get('mcp-protocol-version'); - - if (protocolVersion !== null && !SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) { - return this.createJsonErrorResponse( - 400, - -32000, - `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(', ')})` - ); - } - return undefined; - } - - async close(): Promise { - // Close all SSE connections - this._streamMapping.forEach(({ cleanup }) => { - cleanup(); - }); - this._streamMapping.clear(); - - // Clear any pending responses - this._requestResponseMap.clear(); - this.onclose?.(); - } - - /** - * Close an SSE stream for a specific request, triggering client reconnection. - * Use this to implement polling behavior during long-running operations - - * client will reconnect after the retry interval specified in the priming event. - */ - closeSSEStream(requestId: RequestId): void { - const streamId = this._requestToStreamMapping.get(requestId); - if (!streamId) return; - - const stream = this._streamMapping.get(streamId); - if (stream) { - stream.cleanup(); - } - } - - /** - * Close the standalone GET SSE stream, triggering client reconnection. - * Use this to implement polling behavior for server-initiated notifications. - */ - closeStandaloneSSEStream(): void { - const stream = this._streamMapping.get(this._standaloneSseStreamId); - if (stream) { - stream.cleanup(); - } - } - - async send(message: JSONRPCMessage, options?: { relatedRequestId?: RequestId }): Promise { - let requestId = options?.relatedRequestId; - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - // If the message is a response, use the request ID from the message - requestId = message.id; - } - - // Check if this message should be sent on the standalone SSE stream (no request ID) - // Ignore notifications from tools (which have relatedRequestId set) - // Those will be sent via dedicated response SSE streams - if (requestId === undefined) { - // For standalone SSE streams, we can only send requests and notifications - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - throw new Error('Cannot send a response on a standalone SSE stream unless resuming a previous client request'); - } - - // Generate and store event ID if event store is provided - // Store even if stream is disconnected so events can be replayed on reconnect - let eventId: string | undefined; - if (this._eventStore) { - // Stores the event and gets the generated event ID - eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); - } - - const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); - if (standaloneSse === undefined) { - // Stream is disconnected - event is stored for replay, nothing more to do - return; - } - - // Send the message to the standalone SSE stream - if (standaloneSse.controller && standaloneSse.encoder) { - this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); - } - return; - } - - // Get the response for this request - const streamId = this._requestToStreamMapping.get(requestId); - if (!streamId) { - throw new Error(`No connection established for request ID: ${String(requestId)}`); - } - - const stream = this._streamMapping.get(streamId); - - if (!this._enableJsonResponse && stream?.controller && stream?.encoder) { - // For SSE responses, generate event ID if event store is provided - let eventId: string | undefined; - - if (this._eventStore) { - eventId = await this._eventStore.storeEvent(streamId, message); - } - // Write the event to the response stream - this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); - } - - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - this._requestResponseMap.set(requestId, message); - const relatedIds = Array.from(this._requestToStreamMapping.entries()) - .filter(([_, sid]) => sid === streamId) - .map(([id]) => id); - - // Check if we have responses for all requests using this connection - const allResponsesReady = relatedIds.every(id => this._requestResponseMap.has(id)); - - if (allResponsesReady) { - if (!stream) { - throw new Error(`No connection established for request ID: ${String(requestId)}`); - } - if (this._enableJsonResponse && stream.resolveJson) { - // All responses ready, send as JSON - const headers: Record = { - 'Content-Type': 'application/json' - }; - if (this.sessionId !== undefined) { - headers['mcp-session-id'] = this.sessionId; - } - - const responses = relatedIds.map(id => this._requestResponseMap.get(id)!); - - if (responses.length === 1) { - stream.resolveJson(new Response(JSON.stringify(responses[0]), { status: 200, headers })); - } else { - stream.resolveJson(new Response(JSON.stringify(responses), { status: 200, headers })); - } - } else { - // End the SSE stream - stream.cleanup(); - } - // Clean up - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - } - } - } -} diff --git a/packages/server/tsconfig.json b/packages/server/tsconfig.json deleted file mode 100644 index a16bfd7d9d..0000000000 --- a/packages/server/tsconfig.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "extends": "@modelcontextprotocol/tsconfig", - "include": ["./"], - "exclude": ["node_modules", "dist"], - "compilerOptions": { - "paths": { - "*": ["./*"], - "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], - "@modelcontextprotocol/test-helpers": ["./node_modules/@modelcontextprotocol/test-helpers/src/index.ts"] - } - } -} diff --git a/packages/server/tsdown.config.ts b/packages/server/tsdown.config.ts deleted file mode 100644 index c3d38817a6..0000000000 --- a/packages/server/tsdown.config.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { defineConfig } from 'tsdown'; - -export default defineConfig({ - // 1. Entry Points - // Directly matches package.json include/exclude globs - entry: ['src/index.ts'], - - // 2. Output Configuration - format: ['esm'], - outDir: 'dist', - clean: true, // Recommended: Cleans 'dist' before building - sourcemap: true, - - // 3. Platform & Target - target: 'esnext', - platform: 'node', - shims: true, // Polyfills common Node.js shims (__dirname, etc.) - - // 4. Type Definitions - // Bundles d.ts files into a single output - dts: { - resolver: 'tsc', - // override just for DTS generation: - compilerOptions: { - baseUrl: '.', - paths: { - '@modelcontextprotocol/core': ['../core/src/index.ts'] - } - } - }, - // 5. Vendoring Strategy - Bundle the code for this specific package into the output, - // but treat all other dependencies as external (require/import). - noExternal: ['@modelcontextprotocol/core'] -}); diff --git a/packages/server/vitest.config.js b/packages/server/vitest.config.js deleted file mode 100644 index 496fca3200..0000000000 --- a/packages/server/vitest.config.js +++ /dev/null @@ -1,3 +0,0 @@ -import baseConfig from '@modelcontextprotocol/vitest-config'; - -export default baseConfig; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml deleted file mode 100644 index 92dbf8253e..0000000000 --- a/pnpm-lock.yaml +++ /dev/null @@ -1,6136 +0,0 @@ -lockfileVersion: '9.0' - -settings: - autoInstallPeers: true - excludeLinksFromLockfile: false - -catalogs: - devTools: - '@eslint/js': - specifier: ^9.39.1 - version: 9.39.1 - '@types/content-type': - specifier: ^1.1.8 - version: 1.1.9 - '@types/cors': - specifier: ^2.8.17 - version: 2.8.19 - '@types/cross-spawn': - specifier: ^6.0.6 - version: 6.0.6 - '@types/eventsource': - specifier: ^1.1.15 - version: 1.1.15 - '@types/express': - specifier: ^5.0.0 - version: 5.0.5 - '@types/express-serve-static-core': - specifier: ^5.1.0 - version: 5.1.0 - '@types/supertest': - specifier: ^6.0.2 - version: 6.0.3 - '@types/ws': - specifier: ^8.5.12 - version: 8.18.1 - '@typescript/native-preview': - specifier: ^7.0.0-dev.20251217.1 - version: 7.0.0-dev.20251218.3 - eslint: - specifier: ^9.8.0 - version: 9.39.1 - eslint-config-prettier: - specifier: ^10.1.8 - version: 10.1.8 - eslint-plugin-n: - specifier: ^17.23.1 - version: 17.23.1 - prettier: - specifier: 3.6.2 - version: 3.6.2 - supertest: - specifier: ^7.0.0 - version: 7.1.4 - tsdown: - specifier: ^0.18.0 - version: 0.18.0 - tsx: - specifier: ^4.16.5 - version: 4.20.6 - typescript: - specifier: ^5.9.3 - version: 5.9.3 - typescript-eslint: - specifier: ^8.48.1 - version: 8.49.0 - vite-tsconfig-paths: - specifier: ^5.1.4 - version: 5.1.4 - vitest: - specifier: ^4.0.8 - version: 4.0.9 - ws: - specifier: ^8.18.0 - version: 8.18.3 - runtimeClientOnly: - cross-spawn: - specifier: ^7.0.5 - version: 7.0.6 - eventsource: - specifier: ^3.0.2 - version: 3.0.7 - eventsource-parser: - specifier: ^3.0.0 - version: 3.0.6 - jose: - specifier: ^6.1.1 - version: 6.1.3 - runtimeServerOnly: - '@hono/node-server': - specifier: ^1.19.7 - version: 1.19.7 - content-type: - specifier: ^1.0.5 - version: 1.0.5 - cors: - specifier: ^2.8.5 - version: 2.8.5 - express: - specifier: ^5.0.1 - version: 5.1.0 - express-rate-limit: - specifier: ^7.5.0 - version: 7.5.1 - hono: - specifier: ^4.11.1 - version: 4.11.1 - raw-body: - specifier: ^3.0.0 - version: 3.0.1 - runtimeShared: - '@cfworker/json-schema': - specifier: ^4.1.1 - version: 4.1.1 - ajv: - specifier: ^8.17.1 - version: 8.17.1 - ajv-formats: - specifier: ^3.0.1 - version: 3.0.1 - json-schema-typed: - specifier: ^8.0.2 - version: 8.0.2 - pkce-challenge: - specifier: ^5.0.0 - version: 5.0.0 - zod: - specifier: ^3.25 || ^4.0 - version: 3.25.76 - zod-to-json-schema: - specifier: ^3.25.0 - version: 3.25.0 - -overrides: - strip-ansi: 6.0.1 - -importers: - - .: - devDependencies: - '@cfworker/json-schema': - specifier: catalog:runtimeShared - version: 4.1.1 - '@changesets/changelog-github': - specifier: ^0.5.2 - version: 0.5.2 - '@changesets/cli': - specifier: ^2.29.8 - version: 2.29.8(@types/node@24.10.3) - '@eslint/js': - specifier: catalog:devTools - version: 9.39.1 - '@types/content-type': - specifier: catalog:devTools - version: 1.1.9 - '@types/cors': - specifier: catalog:devTools - version: 2.8.19 - '@types/cross-spawn': - specifier: catalog:devTools - version: 6.0.6 - '@types/eventsource': - specifier: catalog:devTools - version: 1.1.15 - '@types/express': - specifier: catalog:devTools - version: 5.0.5 - '@types/express-serve-static-core': - specifier: catalog:devTools - version: 5.1.0 - '@types/node': - specifier: ^24.10.1 - version: 24.10.3 - '@types/supertest': - specifier: catalog:devTools - version: 6.0.3 - '@types/ws': - specifier: catalog:devTools - version: 8.18.1 - '@typescript/native-preview': - specifier: catalog:devTools - version: 7.0.0-dev.20251218.3 - eslint: - specifier: catalog:devTools - version: 9.39.1 - eslint-config-prettier: - specifier: catalog:devTools - version: 10.1.8(eslint@9.39.1) - eslint-plugin-n: - specifier: catalog:devTools - version: 17.23.1(eslint@9.39.1)(typescript@5.9.3) - prettier: - specifier: catalog:devTools - version: 3.6.2 - supertest: - specifier: catalog:devTools - version: 7.1.4 - tsdown: - specifier: catalog:devTools - version: 0.18.0(@typescript/native-preview@7.0.0-dev.20251218.3)(typescript@5.9.3) - tsx: - specifier: catalog:devTools - version: 4.20.6 - typescript: - specifier: catalog:devTools - version: 5.9.3 - typescript-eslint: - specifier: catalog:devTools - version: 8.49.0(eslint@9.39.1)(typescript@5.9.3) - vitest: - specifier: catalog:devTools - version: 4.0.9(@types/node@24.10.3)(tsx@4.20.6) - ws: - specifier: catalog:devTools - version: 8.18.3 - - common/eslint-config: - dependencies: - typescript: - specifier: catalog:devTools - version: 5.9.3 - devDependencies: - '@eslint/js': - specifier: catalog:devTools - version: 9.39.1 - eslint: - specifier: catalog:devTools - version: 9.39.1 - eslint-config-prettier: - specifier: catalog:devTools - version: 10.1.8(eslint@9.39.1) - eslint-import-resolver-typescript: - specifier: ^4.4.4 - version: 4.4.4(eslint-plugin-import@2.32.0)(eslint@9.39.1) - eslint-plugin-import: - specifier: ^2.32.0 - version: 2.32.0(@typescript-eslint/parser@8.49.0(eslint@9.39.1)(typescript@5.9.3))(eslint-import-resolver-typescript@4.4.4)(eslint@9.39.1) - eslint-plugin-n: - specifier: catalog:devTools - version: 17.23.1(eslint@9.39.1)(typescript@5.9.3) - eslint-plugin-simple-import-sort: - specifier: ^12.1.1 - version: 12.1.1(eslint@9.39.1) - prettier: - specifier: catalog:devTools - version: 3.6.2 - typescript-eslint: - specifier: catalog:devTools - version: 8.49.0(eslint@9.39.1)(typescript@5.9.3) - - common/tsconfig: - dependencies: - typescript: - specifier: catalog:devTools - version: 5.9.3 - - common/vitest-config: - dependencies: - typescript: - specifier: catalog:devTools - version: 5.9.3 - devDependencies: - '@modelcontextprotocol/tsconfig': - specifier: workspace:^ - version: link:../tsconfig - vite-tsconfig-paths: - specifier: catalog:devTools - version: 5.1.4(typescript@5.9.3)(vite@7.2.2(@types/node@24.10.3)(tsx@4.20.6)) - - examples/client: - dependencies: - '@modelcontextprotocol/client': - specifier: workspace:^ - version: link:../../packages/client - ajv: - specifier: catalog:runtimeShared - version: 8.17.1 - zod: - specifier: catalog:runtimeShared - version: 3.25.76 - devDependencies: - '@modelcontextprotocol/eslint-config': - specifier: workspace:^ - version: link:../../common/eslint-config - '@modelcontextprotocol/examples-shared': - specifier: workspace:^ - version: link:../shared - '@modelcontextprotocol/tsconfig': - specifier: workspace:^ - version: link:../../common/tsconfig - '@modelcontextprotocol/vitest-config': - specifier: workspace:^ - version: link:../../common/vitest-config - tsdown: - specifier: catalog:devTools - version: 0.18.0(@typescript/native-preview@7.0.0-dev.20251218.3)(typescript@5.9.3) - - examples/server: - dependencies: - '@hono/node-server': - specifier: catalog:runtimeServerOnly - version: 1.19.7(hono@4.11.1) - '@modelcontextprotocol/examples-shared': - specifier: workspace:^ - version: link:../shared - '@modelcontextprotocol/server': - specifier: workspace:^ - version: link:../../packages/server - cors: - specifier: catalog:runtimeServerOnly - version: 2.8.5 - express: - specifier: catalog:runtimeServerOnly - version: 5.1.0 - hono: - specifier: catalog:runtimeServerOnly - version: 4.11.1 - zod: - specifier: catalog:runtimeShared - version: 3.25.76 - devDependencies: - '@modelcontextprotocol/eslint-config': - specifier: workspace:^ - version: link:../../common/eslint-config - '@modelcontextprotocol/tsconfig': - specifier: workspace:^ - version: link:../../common/tsconfig - '@modelcontextprotocol/vitest-config': - specifier: workspace:^ - version: link:../../common/vitest-config - '@types/cors': - specifier: catalog:devTools - version: 2.8.19 - '@types/express': - specifier: catalog:devTools - version: 5.0.5 - tsdown: - specifier: catalog:devTools - version: 0.18.0(@typescript/native-preview@7.0.0-dev.20251218.3)(typescript@5.9.3) - - examples/shared: - dependencies: - '@modelcontextprotocol/server': - specifier: workspace:^ - version: link:../../packages/server - express: - specifier: catalog:runtimeServerOnly - version: 5.1.0 - devDependencies: - '@eslint/js': - specifier: catalog:devTools - version: 9.39.1 - '@modelcontextprotocol/eslint-config': - specifier: workspace:^ - version: link:../../common/eslint-config - '@modelcontextprotocol/test-helpers': - specifier: workspace:^ - version: link:../../test/helpers - '@modelcontextprotocol/tsconfig': - specifier: workspace:^ - version: link:../../common/tsconfig - '@modelcontextprotocol/vitest-config': - specifier: workspace:^ - version: link:../../common/vitest-config - '@types/express': - specifier: catalog:devTools - version: 5.0.5 - '@typescript/native-preview': - specifier: catalog:devTools - version: 7.0.0-dev.20251218.3 - eslint: - specifier: catalog:devTools - version: 9.39.1 - eslint-config-prettier: - specifier: catalog:devTools - version: 10.1.8(eslint@9.39.1) - eslint-plugin-n: - specifier: catalog:devTools - version: 17.23.1(eslint@9.39.1)(typescript@5.9.3) - prettier: - specifier: catalog:devTools - version: 3.6.2 - tsx: - specifier: catalog:devTools - version: 4.20.6 - typescript: - specifier: catalog:devTools - version: 5.9.3 - typescript-eslint: - specifier: catalog:devTools - version: 8.49.0(eslint@9.39.1)(typescript@5.9.3) - vitest: - specifier: catalog:devTools - version: 4.0.9(@types/node@24.10.3)(tsx@4.20.6) - - packages/client: - dependencies: - cross-spawn: - specifier: catalog:runtimeClientOnly - version: 7.0.6 - eventsource: - specifier: catalog:runtimeClientOnly - version: 3.0.7 - eventsource-parser: - specifier: catalog:runtimeClientOnly - version: 3.0.6 - jose: - specifier: catalog:runtimeClientOnly - version: 6.1.3 - pkce-challenge: - specifier: catalog:runtimeShared - version: 5.0.0 - zod: - specifier: catalog:runtimeShared - version: 3.25.76 - devDependencies: - '@cfworker/json-schema': - specifier: catalog:runtimeShared - version: 4.1.1 - '@eslint/js': - specifier: catalog:devTools - version: 9.39.1 - '@modelcontextprotocol/core': - specifier: workspace:^ - version: link:../core - '@modelcontextprotocol/eslint-config': - specifier: workspace:^ - version: link:../../common/eslint-config - '@modelcontextprotocol/test-helpers': - specifier: workspace:^ - version: link:../../test/helpers - '@modelcontextprotocol/tsconfig': - specifier: workspace:^ - version: link:../../common/tsconfig - '@modelcontextprotocol/vitest-config': - specifier: workspace:^ - version: link:../../common/vitest-config - '@types/content-type': - specifier: catalog:devTools - version: 1.1.9 - '@types/cross-spawn': - specifier: catalog:devTools - version: 6.0.6 - '@types/eventsource': - specifier: catalog:devTools - version: 1.1.15 - '@typescript/native-preview': - specifier: catalog:devTools - version: 7.0.0-dev.20251218.3 - eslint: - specifier: catalog:devTools - version: 9.39.1 - eslint-config-prettier: - specifier: catalog:devTools - version: 10.1.8(eslint@9.39.1) - eslint-plugin-n: - specifier: catalog:devTools - version: 17.23.1(eslint@9.39.1)(typescript@5.9.3) - prettier: - specifier: catalog:devTools - version: 3.6.2 - tsdown: - specifier: catalog:devTools - version: 0.18.0(@typescript/native-preview@7.0.0-dev.20251218.3)(typescript@5.9.3) - tsx: - specifier: catalog:devTools - version: 4.20.6 - typescript: - specifier: catalog:devTools - version: 5.9.3 - typescript-eslint: - specifier: catalog:devTools - version: 8.49.0(eslint@9.39.1)(typescript@5.9.3) - vitest: - specifier: catalog:devTools - version: 4.0.9(@types/node@24.10.3)(tsx@4.20.6) - - packages/core: - dependencies: - ajv: - specifier: catalog:runtimeShared - version: 8.17.1 - ajv-formats: - specifier: catalog:runtimeShared - version: 3.0.1(ajv@8.17.1) - json-schema-typed: - specifier: catalog:runtimeShared - version: 8.0.2 - zod: - specifier: catalog:runtimeShared - version: 3.25.76 - zod-to-json-schema: - specifier: catalog:runtimeShared - version: 3.25.0(zod@3.25.76) - devDependencies: - '@cfworker/json-schema': - specifier: catalog:runtimeShared - version: 4.1.1 - '@eslint/js': - specifier: catalog:devTools - version: 9.39.1 - '@modelcontextprotocol/eslint-config': - specifier: workspace:^ - version: link:../../common/eslint-config - '@modelcontextprotocol/tsconfig': - specifier: workspace:^ - version: link:../../common/tsconfig - '@modelcontextprotocol/vitest-config': - specifier: workspace:^ - version: link:../../common/vitest-config - '@types/content-type': - specifier: catalog:devTools - version: 1.1.9 - '@types/cors': - specifier: catalog:devTools - version: 2.8.19 - '@types/cross-spawn': - specifier: catalog:devTools - version: 6.0.6 - '@types/eventsource': - specifier: catalog:devTools - version: 1.1.15 - '@types/express': - specifier: catalog:devTools - version: 5.0.5 - '@types/express-serve-static-core': - specifier: catalog:devTools - version: 5.1.0 - '@typescript/native-preview': - specifier: catalog:devTools - version: 7.0.0-dev.20251218.3 - eslint: - specifier: catalog:devTools - version: 9.39.1 - eslint-config-prettier: - specifier: catalog:devTools - version: 10.1.8(eslint@9.39.1) - eslint-plugin-n: - specifier: catalog:devTools - version: 17.23.1(eslint@9.39.1)(typescript@5.9.3) - prettier: - specifier: catalog:devTools - version: 3.6.2 - tsx: - specifier: catalog:devTools - version: 4.20.6 - typescript: - specifier: catalog:devTools - version: 5.9.3 - typescript-eslint: - specifier: catalog:devTools - version: 8.49.0(eslint@9.39.1)(typescript@5.9.3) - vitest: - specifier: catalog:devTools - version: 4.0.9(@types/node@24.10.3)(tsx@4.20.6) - - packages/server: - dependencies: - '@hono/node-server': - specifier: catalog:runtimeServerOnly - version: 1.19.7(hono@4.11.1) - content-type: - specifier: catalog:runtimeServerOnly - version: 1.0.5 - cors: - specifier: catalog:runtimeServerOnly - version: 2.8.5 - express: - specifier: catalog:runtimeServerOnly - version: 5.1.0 - express-rate-limit: - specifier: catalog:runtimeServerOnly - version: 7.5.1(express@5.1.0) - hono: - specifier: catalog:runtimeServerOnly - version: 4.11.1 - pkce-challenge: - specifier: catalog:runtimeShared - version: 5.0.0 - raw-body: - specifier: catalog:runtimeServerOnly - version: 3.0.1 - zod: - specifier: catalog:runtimeShared - version: 3.25.76 - zod-to-json-schema: - specifier: catalog:runtimeShared - version: 3.25.0(zod@3.25.76) - devDependencies: - '@cfworker/json-schema': - specifier: catalog:runtimeShared - version: 4.1.1 - '@eslint/js': - specifier: catalog:devTools - version: 9.39.1 - '@modelcontextprotocol/core': - specifier: workspace:^ - version: link:../core - '@modelcontextprotocol/eslint-config': - specifier: workspace:^ - version: link:../../common/eslint-config - '@modelcontextprotocol/test-helpers': - specifier: workspace:^ - version: link:../../test/helpers - '@modelcontextprotocol/tsconfig': - specifier: workspace:^ - version: link:../../common/tsconfig - '@modelcontextprotocol/vitest-config': - specifier: workspace:^ - version: link:../../common/vitest-config - '@types/content-type': - specifier: catalog:devTools - version: 1.1.9 - '@types/cors': - specifier: catalog:devTools - version: 2.8.19 - '@types/cross-spawn': - specifier: catalog:devTools - version: 6.0.6 - '@types/eventsource': - specifier: catalog:devTools - version: 1.1.15 - '@types/express': - specifier: catalog:devTools - version: 5.0.5 - '@types/express-serve-static-core': - specifier: catalog:devTools - version: 5.1.0 - '@types/supertest': - specifier: catalog:devTools - version: 6.0.3 - '@typescript/native-preview': - specifier: catalog:devTools - version: 7.0.0-dev.20251218.3 - eslint: - specifier: catalog:devTools - version: 9.39.1 - eslint-config-prettier: - specifier: catalog:devTools - version: 10.1.8(eslint@9.39.1) - eslint-plugin-n: - specifier: catalog:devTools - version: 17.23.1(eslint@9.39.1)(typescript@5.9.3) - prettier: - specifier: catalog:devTools - version: 3.6.2 - supertest: - specifier: catalog:devTools - version: 7.1.4 - tsdown: - specifier: catalog:devTools - version: 0.18.0(@typescript/native-preview@7.0.0-dev.20251218.3)(typescript@5.9.3) - tsx: - specifier: catalog:devTools - version: 4.20.6 - typescript: - specifier: catalog:devTools - version: 5.9.3 - typescript-eslint: - specifier: catalog:devTools - version: 8.49.0(eslint@9.39.1)(typescript@5.9.3) - vitest: - specifier: catalog:devTools - version: 4.0.9(@types/node@24.10.3)(tsx@4.20.6) - - test/helpers: - devDependencies: - '@modelcontextprotocol/client': - specifier: workspace:^ - version: link:../../packages/client - '@modelcontextprotocol/core': - specifier: workspace:^ - version: link:../../packages/core - '@modelcontextprotocol/eslint-config': - specifier: workspace:^ - version: link:../../common/eslint-config - '@modelcontextprotocol/server': - specifier: workspace:^ - version: link:../../packages/server - '@modelcontextprotocol/tsconfig': - specifier: workspace:^ - version: link:../../common/tsconfig - '@modelcontextprotocol/vitest-config': - specifier: workspace:^ - version: link:../../common/vitest-config - vitest: - specifier: catalog:devTools - version: 4.0.9(@types/node@24.10.3)(tsx@4.20.6) - zod: - specifier: catalog:runtimeShared - version: 3.25.76 - - test/integration: - devDependencies: - '@modelcontextprotocol/client': - specifier: workspace:^ - version: link:../../packages/client - '@modelcontextprotocol/core': - specifier: workspace:^ - version: link:../../packages/core - '@modelcontextprotocol/eslint-config': - specifier: workspace:^ - version: link:../../common/eslint-config - '@modelcontextprotocol/server': - specifier: workspace:^ - version: link:../../packages/server - '@modelcontextprotocol/test-helpers': - specifier: workspace:^ - version: link:../helpers - '@modelcontextprotocol/tsconfig': - specifier: workspace:^ - version: link:../../common/tsconfig - '@modelcontextprotocol/vitest-config': - specifier: workspace:^ - version: link:../../common/vitest-config - supertest: - specifier: catalog:devTools - version: 7.1.4 - vitest: - specifier: catalog:devTools - version: 4.0.9(@types/node@24.10.3)(tsx@4.20.6) - zod: - specifier: catalog:runtimeShared - version: 3.25.76 - -packages: - - '@babel/generator@7.28.5': - resolution: {integrity: sha512-3EwLFhZ38J4VyIP6WNtt2kUdW9dokXA9Cr4IVIFHuCpZ3H8/YFOl5JjZHisrn1fATPBmKKqXzDFvh9fUwHz6CQ==} - engines: {node: '>=6.9.0'} - - '@babel/helper-string-parser@7.27.1': - resolution: {integrity: sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==} - engines: {node: '>=6.9.0'} - - '@babel/helper-validator-identifier@7.28.5': - resolution: {integrity: sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==} - engines: {node: '>=6.9.0'} - - '@babel/parser@7.28.5': - resolution: {integrity: sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==} - engines: {node: '>=6.0.0'} - hasBin: true - - '@babel/runtime@7.28.4': - resolution: {integrity: sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==} - engines: {node: '>=6.9.0'} - - '@babel/types@7.28.5': - resolution: {integrity: sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==} - engines: {node: '>=6.9.0'} - - '@cfworker/json-schema@4.1.1': - resolution: {integrity: sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==} - - '@changesets/apply-release-plan@7.0.14': - resolution: {integrity: sha512-ddBvf9PHdy2YY0OUiEl3TV78mH9sckndJR14QAt87KLEbIov81XO0q0QAmvooBxXlqRRP8I9B7XOzZwQG7JkWA==} - - '@changesets/assemble-release-plan@6.0.9': - resolution: {integrity: sha512-tPgeeqCHIwNo8sypKlS3gOPmsS3wP0zHt67JDuL20P4QcXiw/O4Hl7oXiuLnP9yg+rXLQ2sScdV1Kkzde61iSQ==} - - '@changesets/changelog-git@0.2.1': - resolution: {integrity: sha512-x/xEleCFLH28c3bQeQIyeZf8lFXyDFVn1SgcBiR2Tw/r4IAWlk1fzxCEZ6NxQAjF2Nwtczoen3OA2qR+UawQ8Q==} - - '@changesets/changelog-github@0.5.2': - resolution: {integrity: sha512-HeGeDl8HaIGj9fQHo/tv5XKQ2SNEi9+9yl1Bss1jttPqeiASRXhfi0A2wv8yFKCp07kR1gpOI5ge6+CWNm1jPw==} - - '@changesets/cli@2.29.8': - resolution: {integrity: sha512-1weuGZpP63YWUYjay/E84qqwcnt5yJMM0tep10Up7Q5cS/DGe2IZ0Uj3HNMxGhCINZuR7aO9WBMdKnPit5ZDPA==} - hasBin: true - - '@changesets/config@3.1.2': - resolution: {integrity: sha512-CYiRhA4bWKemdYi/uwImjPxqWNpqGPNbEBdX1BdONALFIDK7MCUj6FPkzD+z9gJcvDFUQJn9aDVf4UG7OT6Kog==} - - '@changesets/errors@0.2.0': - resolution: {integrity: sha512-6BLOQUscTpZeGljvyQXlWOItQyU71kCdGz7Pi8H8zdw6BI0g3m43iL4xKUVPWtG+qrrL9DTjpdn8eYuCQSRpow==} - - '@changesets/get-dependents-graph@2.1.3': - resolution: {integrity: sha512-gphr+v0mv2I3Oxt19VdWRRUxq3sseyUpX9DaHpTUmLj92Y10AGy+XOtV+kbM6L/fDcpx7/ISDFK6T8A/P3lOdQ==} - - '@changesets/get-github-info@0.7.0': - resolution: {integrity: sha512-+i67Bmhfj9V4KfDeS1+Tz3iF32btKZB2AAx+cYMqDSRFP7r3/ZdGbjCo+c6qkyViN9ygDuBjzageuPGJtKGe5A==} - - '@changesets/get-release-plan@4.0.14': - resolution: {integrity: sha512-yjZMHpUHgl4Xl5gRlolVuxDkm4HgSJqT93Ri1Uz8kGrQb+5iJ8dkXJ20M2j/Y4iV5QzS2c5SeTxVSKX+2eMI0g==} - - '@changesets/get-version-range-type@0.4.0': - resolution: {integrity: sha512-hwawtob9DryoGTpixy1D3ZXbGgJu1Rhr+ySH2PvTLHvkZuQ7sRT4oQwMh0hbqZH1weAooedEjRsbrWcGLCeyVQ==} - - '@changesets/git@3.0.4': - resolution: {integrity: sha512-BXANzRFkX+XcC1q/d27NKvlJ1yf7PSAgi8JG6dt8EfbHFHi4neau7mufcSca5zRhwOL8j9s6EqsxmT+s+/E6Sw==} - - '@changesets/logger@0.1.1': - resolution: {integrity: sha512-OQtR36ZlnuTxKqoW4Sv6x5YIhOmClRd5pWsjZsddYxpWs517R0HkyiefQPIytCVh4ZcC5x9XaG8KTdd5iRQUfg==} - - '@changesets/parse@0.4.2': - resolution: {integrity: sha512-Uo5MC5mfg4OM0jU3up66fmSn6/NE9INK+8/Vn/7sMVcdWg46zfbvvUSjD9EMonVqPi9fbrJH9SXHn48Tr1f2yA==} - - '@changesets/pre@2.0.2': - resolution: {integrity: sha512-HaL/gEyFVvkf9KFg6484wR9s0qjAXlZ8qWPDkTyKF6+zqjBe/I2mygg3MbpZ++hdi0ToqNUF8cjj7fBy0dg8Ug==} - - '@changesets/read@0.6.6': - resolution: {integrity: sha512-P5QaN9hJSQQKJShzzpBT13FzOSPyHbqdoIBUd2DJdgvnECCyO6LmAOWSV+O8se2TaZJVwSXjL+v9yhb+a9JeJg==} - - '@changesets/should-skip-package@0.1.2': - resolution: {integrity: sha512-qAK/WrqWLNCP22UDdBTMPH5f41elVDlsNyat180A33dWxuUDyNpg6fPi/FyTZwRriVjg0L8gnjJn2F9XAoF0qw==} - - '@changesets/types@4.1.0': - resolution: {integrity: sha512-LDQvVDv5Kb50ny2s25Fhm3d9QSZimsoUGBsUioj6MC3qbMUCuC8GPIvk/M6IvXx3lYhAs0lwWUQLb+VIEUCECw==} - - '@changesets/types@6.1.0': - resolution: {integrity: sha512-rKQcJ+o1nKNgeoYRHKOS07tAMNd3YSN0uHaJOZYjBAgxfV7TUE7JE+z4BzZdQwb5hKaYbayKN5KrYV7ODb2rAA==} - - '@changesets/write@0.4.0': - resolution: {integrity: sha512-CdTLvIOPiCNuH71pyDu3rA+Q0n65cmAbXnwWH84rKGiFumFzkmHNT8KHTMEchcxN+Kl8I54xGUhJ7l3E7X396Q==} - - '@emnapi/core@1.7.1': - resolution: {integrity: sha512-o1uhUASyo921r2XtHYOHy7gdkGLge8ghBEQHMWmyJFoXlpU58kIrhhN3w26lpQb6dspetweapMn2CSNwQ8I4wg==} - - '@emnapi/runtime@1.7.1': - resolution: {integrity: sha512-PVtJr5CmLwYAU9PZDMITZoR5iAOShYREoR45EyyLrbntV50mdePTgUn4AmOw90Ifcj+x2kRjdzr1HP3RrNiHGA==} - - '@emnapi/wasi-threads@1.1.0': - resolution: {integrity: sha512-WI0DdZ8xFSbgMjR1sFsKABJ/C5OnRrjT06JXbZKexJGrDuPTzZdDYfFlsgcCXCyf+suG5QU2e/y1Wo2V/OapLQ==} - - '@esbuild/aix-ppc64@0.25.12': - resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==} - engines: {node: '>=18'} - cpu: [ppc64] - os: [aix] - - '@esbuild/android-arm64@0.25.12': - resolution: {integrity: sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [android] - - '@esbuild/android-arm@0.25.12': - resolution: {integrity: sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==} - engines: {node: '>=18'} - cpu: [arm] - os: [android] - - '@esbuild/android-x64@0.25.12': - resolution: {integrity: sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==} - engines: {node: '>=18'} - cpu: [x64] - os: [android] - - '@esbuild/darwin-arm64@0.25.12': - resolution: {integrity: sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [darwin] - - '@esbuild/darwin-x64@0.25.12': - resolution: {integrity: sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==} - engines: {node: '>=18'} - cpu: [x64] - os: [darwin] - - '@esbuild/freebsd-arm64@0.25.12': - resolution: {integrity: sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [freebsd] - - '@esbuild/freebsd-x64@0.25.12': - resolution: {integrity: sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==} - engines: {node: '>=18'} - cpu: [x64] - os: [freebsd] - - '@esbuild/linux-arm64@0.25.12': - resolution: {integrity: sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==} - engines: {node: '>=18'} - cpu: [arm64] - os: [linux] - - '@esbuild/linux-arm@0.25.12': - resolution: {integrity: sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==} - engines: {node: '>=18'} - cpu: [arm] - os: [linux] - - '@esbuild/linux-ia32@0.25.12': - resolution: {integrity: sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==} - engines: {node: '>=18'} - cpu: [ia32] - os: [linux] - - '@esbuild/linux-loong64@0.25.12': - resolution: {integrity: sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==} - engines: {node: '>=18'} - cpu: [loong64] - os: [linux] - - '@esbuild/linux-mips64el@0.25.12': - resolution: {integrity: sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==} - engines: {node: '>=18'} - cpu: [mips64el] - os: [linux] - - '@esbuild/linux-ppc64@0.25.12': - resolution: {integrity: sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==} - engines: {node: '>=18'} - cpu: [ppc64] - os: [linux] - - '@esbuild/linux-riscv64@0.25.12': - resolution: {integrity: sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==} - engines: {node: '>=18'} - cpu: [riscv64] - os: [linux] - - '@esbuild/linux-s390x@0.25.12': - resolution: {integrity: sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==} - engines: {node: '>=18'} - cpu: [s390x] - os: [linux] - - '@esbuild/linux-x64@0.25.12': - resolution: {integrity: sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==} - engines: {node: '>=18'} - cpu: [x64] - os: [linux] - - '@esbuild/netbsd-arm64@0.25.12': - resolution: {integrity: sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [netbsd] - - '@esbuild/netbsd-x64@0.25.12': - resolution: {integrity: sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==} - engines: {node: '>=18'} - cpu: [x64] - os: [netbsd] - - '@esbuild/openbsd-arm64@0.25.12': - resolution: {integrity: sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==} - engines: {node: '>=18'} - cpu: [arm64] - os: [openbsd] - - '@esbuild/openbsd-x64@0.25.12': - resolution: {integrity: sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==} - engines: {node: '>=18'} - cpu: [x64] - os: [openbsd] - - '@esbuild/openharmony-arm64@0.25.12': - resolution: {integrity: sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [openharmony] - - '@esbuild/sunos-x64@0.25.12': - resolution: {integrity: sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==} - engines: {node: '>=18'} - cpu: [x64] - os: [sunos] - - '@esbuild/win32-arm64@0.25.12': - resolution: {integrity: sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [win32] - - '@esbuild/win32-ia32@0.25.12': - resolution: {integrity: sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==} - engines: {node: '>=18'} - cpu: [ia32] - os: [win32] - - '@esbuild/win32-x64@0.25.12': - resolution: {integrity: sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==} - engines: {node: '>=18'} - cpu: [x64] - os: [win32] - - '@eslint-community/eslint-utils@4.9.0': - resolution: {integrity: sha512-ayVFHdtZ+hsq1t2Dy24wCmGXGe4q9Gu3smhLYALJrr473ZH27MsnSL+LKUlimp4BWJqMDMLmPpx/Q9R3OAlL4g==} - engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - peerDependencies: - eslint: ^6.0.0 || ^7.0.0 || >=8.0.0 - - '@eslint-community/regexpp@4.12.2': - resolution: {integrity: sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==} - engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} - - '@eslint/config-array@0.21.1': - resolution: {integrity: sha512-aw1gNayWpdI/jSYVgzN5pL0cfzU02GT3NBpeT/DXbx1/1x7ZKxFPd9bwrzygx/qiwIQiJ1sw/zD8qY/kRvlGHA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@eslint/config-helpers@0.4.2': - resolution: {integrity: sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@eslint/core@0.17.0': - resolution: {integrity: sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@eslint/eslintrc@3.3.1': - resolution: {integrity: sha512-gtF186CXhIl1p4pJNGZw8Yc6RlshoePRvE0X91oPGb3vZ8pM3qOS9W9NGPat9LziaBV7XrJWGylNQXkGcnM3IQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@eslint/js@9.39.1': - resolution: {integrity: sha512-S26Stp4zCy88tH94QbBv3XCuzRQiZ9yXofEILmglYTh/Ug/a9/umqvgFtYBAo3Lp0nsI/5/qH1CCrbdK3AP1Tw==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@eslint/object-schema@2.1.7': - resolution: {integrity: sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@eslint/plugin-kit@0.4.1': - resolution: {integrity: sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@hono/node-server@1.19.7': - resolution: {integrity: sha512-vUcD0uauS7EU2caukW8z5lJKtoGMokxNbJtBiwHgpqxEXokaHCBkQUmCHhjFB1VUTWdqj25QoMkMKzgjq+uhrw==} - engines: {node: '>=18.14.1'} - peerDependencies: - hono: ^4 - - '@humanfs/core@0.19.1': - resolution: {integrity: sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==} - engines: {node: '>=18.18.0'} - - '@humanfs/node@0.16.7': - resolution: {integrity: sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==} - engines: {node: '>=18.18.0'} - - '@humanwhocodes/module-importer@1.0.1': - resolution: {integrity: sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==} - engines: {node: '>=12.22'} - - '@humanwhocodes/retry@0.4.3': - resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} - engines: {node: '>=18.18'} - - '@inquirer/external-editor@1.0.3': - resolution: {integrity: sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA==} - engines: {node: '>=18'} - peerDependencies: - '@types/node': '>=18' - peerDependenciesMeta: - '@types/node': - optional: true - - '@jridgewell/gen-mapping@0.3.13': - resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} - - '@jridgewell/resolve-uri@3.1.2': - resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} - engines: {node: '>=6.0.0'} - - '@jridgewell/sourcemap-codec@1.5.5': - resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} - - '@jridgewell/trace-mapping@0.3.31': - resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} - - '@manypkg/find-root@1.1.0': - resolution: {integrity: sha512-mki5uBvhHzO8kYYix/WRy2WX8S3B5wdVSc9D6KcU5lQNglP2yt58/VfLuAK49glRXChosY8ap2oJ1qgma3GUVA==} - - '@manypkg/get-packages@1.1.3': - resolution: {integrity: sha512-fo+QhuU3qE/2TQMQmbVMqaQ6EWbMhi4ABWP+O4AM1NqPBuy0OrApV5LO6BrrgnhtAHS2NH6RrVk9OL181tTi8A==} - - '@napi-rs/wasm-runtime@0.2.12': - resolution: {integrity: sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ==} - - '@napi-rs/wasm-runtime@1.1.0': - resolution: {integrity: sha512-Fq6DJW+Bb5jaWE69/qOE0D1TUN9+6uWhCeZpdnSBk14pjLcCWR7Q8n49PTSPHazM37JqrsdpEthXy2xn6jWWiA==} - - '@noble/hashes@1.8.0': - resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==} - engines: {node: ^14.21.3 || >=16} - - '@nodelib/fs.scandir@2.1.5': - resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==} - engines: {node: '>= 8'} - - '@nodelib/fs.stat@2.0.5': - resolution: {integrity: sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==} - engines: {node: '>= 8'} - - '@nodelib/fs.walk@1.2.8': - resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} - engines: {node: '>= 8'} - - '@oxc-project/types@0.101.0': - resolution: {integrity: sha512-nuFhqlUzJX+gVIPPfuE6xurd4lST3mdcWOhyK/rZO0B9XWMKm79SuszIQEnSMmmDhq1DC8WWVYGVd+6F93o1gQ==} - - '@paralleldrive/cuid2@2.3.1': - resolution: {integrity: sha512-XO7cAxhnTZl0Yggq6jOgjiOHhbgcO4NqFqwSmQpjK3b6TEE6Uj/jfSk6wzYyemh3+I0sHirKSetjQwn5cZktFw==} - - '@quansync/fs@1.0.0': - resolution: {integrity: sha512-4TJ3DFtlf1L5LDMaM6CanJ/0lckGNtJcMjQ1NAV6zDmA0tEHKZtxNKin8EgPaVX1YzljbxckyT2tJrpQKAtngQ==} - - '@rolldown/binding-android-arm64@1.0.0-beta.53': - resolution: {integrity: sha512-Ok9V8o7o6YfSdTTYA/uHH30r3YtOxLD6G3wih/U9DO0ucBBFq8WPt/DslU53OgfteLRHITZny9N/qCUxMf9kjQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [android] - - '@rolldown/binding-darwin-arm64@1.0.0-beta.53': - resolution: {integrity: sha512-yIsKqMz0CtRnVa6x3Pa+mzTihr4Ty+Z6HfPbZ7RVbk1Uxnco4+CUn7Qbm/5SBol1JD/7nvY8rphAgyAi7Lj6Vg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [darwin] - - '@rolldown/binding-darwin-x64@1.0.0-beta.53': - resolution: {integrity: sha512-GTXe+mxsCGUnJOFMhfGWmefP7Q9TpYUseHvhAhr21nCTgdS8jPsvirb0tJwM3lN0/u/cg7bpFNa16fQrjKrCjQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [darwin] - - '@rolldown/binding-freebsd-x64@1.0.0-beta.53': - resolution: {integrity: sha512-9Tmp7bBvKqyDkMcL4e089pH3RsjD3SUungjmqWtyhNOxoQMh0fSmINTyYV8KXtE+JkxYMPWvnEt+/mfpVCkk8w==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [freebsd] - - '@rolldown/binding-linux-arm-gnueabihf@1.0.0-beta.53': - resolution: {integrity: sha512-a1y5fiB0iovuzdbjUxa7+Zcvgv+mTmlGGC4XydVIsyl48eoxgaYkA3l9079hyTyhECsPq+mbr0gVQsFU11OJAQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [linux] - - '@rolldown/binding-linux-arm64-gnu@1.0.0-beta.53': - resolution: {integrity: sha512-bpIGX+ov9PhJYV+wHNXl9rzq4F0QvILiURn0y0oepbQx+7stmQsKA0DhPGwmhfvF856wq+gbM8L92SAa/CBcLg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - - '@rolldown/binding-linux-arm64-musl@1.0.0-beta.53': - resolution: {integrity: sha512-bGe5EBB8FVjHBR1mOLOPEFg1Lp3//7geqWkU5NIhxe+yH0W8FVrQ6WRYOap4SUTKdklD/dC4qPLREkMMQ855FA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - - '@rolldown/binding-linux-x64-gnu@1.0.0-beta.53': - resolution: {integrity: sha512-qL+63WKVQs1CMvFedlPt0U9PiEKJOAL/bsHMKUDS6Vp2Q+YAv/QLPu8rcvkfIMvQ0FPU2WL0aX4eWwF6e/GAnA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - - '@rolldown/binding-linux-x64-musl@1.0.0-beta.53': - resolution: {integrity: sha512-VGl9JIGjoJh3H8Mb+7xnVqODajBmrdOOb9lxWXdcmxyI+zjB2sux69br0hZJDTyLJfvBoYm439zPACYbCjGRmw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - - '@rolldown/binding-openharmony-arm64@1.0.0-beta.53': - resolution: {integrity: sha512-B4iIserJXuSnNzA5xBLFUIjTfhNy7d9sq4FUMQY3GhQWGVhS2RWWzzDnkSU6MUt7/aHUrep0CdQfXUJI9D3W7A==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [openharmony] - - '@rolldown/binding-wasm32-wasi@1.0.0-beta.53': - resolution: {integrity: sha512-BUjAEgpABEJXilGq/BPh7jeU3WAJ5o15c1ZEgHaDWSz3LB881LQZnbNJHmUiM4d1JQWMYYyR1Y490IBHi2FPJg==} - engines: {node: '>=14.0.0'} - cpu: [wasm32] - - '@rolldown/binding-win32-arm64-msvc@1.0.0-beta.53': - resolution: {integrity: sha512-s27uU7tpCWSjHBnxyVXHt3rMrQdJq5MHNv3BzsewCIroIw3DJFjMH1dzCPPMUFxnh1r52Nf9IJ/eWp6LDoyGcw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [win32] - - '@rolldown/binding-win32-x64-msvc@1.0.0-beta.53': - resolution: {integrity: sha512-cjWL/USPJ1g0en2htb4ssMjIycc36RvdQAx1WlXnS6DpULswiUTVXPDesTifSKYSyvx24E0YqQkEm0K/M2Z/AA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [win32] - - '@rolldown/pluginutils@1.0.0-beta.53': - resolution: {integrity: sha512-vENRlFU4YbrwVqNDZ7fLvy+JR1CRkyr01jhSiDpE1u6py3OMzQfztQU2jxykW3ALNxO4kSlqIDeYyD0Y9RcQeQ==} - - '@rollup/rollup-android-arm-eabi@4.53.2': - resolution: {integrity: sha512-yDPzwsgiFO26RJA4nZo8I+xqzh7sJTZIWQOxn+/XOdPE31lAvLIYCKqjV+lNH/vxE2L2iH3plKxDCRK6i+CwhA==} - cpu: [arm] - os: [android] - - '@rollup/rollup-android-arm64@4.53.2': - resolution: {integrity: sha512-k8FontTxIE7b0/OGKeSN5B6j25EuppBcWM33Z19JoVT7UTXFSo3D9CdU39wGTeb29NO3XxpMNauh09B+Ibw+9g==} - cpu: [arm64] - os: [android] - - '@rollup/rollup-darwin-arm64@4.53.2': - resolution: {integrity: sha512-A6s4gJpomNBtJ2yioj8bflM2oogDwzUiMl2yNJ2v9E7++sHrSrsQ29fOfn5DM/iCzpWcebNYEdXpaK4tr2RhfQ==} - cpu: [arm64] - os: [darwin] - - '@rollup/rollup-darwin-x64@4.53.2': - resolution: {integrity: sha512-e6XqVmXlHrBlG56obu9gDRPW3O3hLxpwHpLsBJvuI8qqnsrtSZ9ERoWUXtPOkY8c78WghyPHZdmPhHLWNdAGEw==} - cpu: [x64] - os: [darwin] - - '@rollup/rollup-freebsd-arm64@4.53.2': - resolution: {integrity: sha512-v0E9lJW8VsrwPux5Qe5CwmH/CF/2mQs6xU1MF3nmUxmZUCHazCjLgYvToOk+YuuUqLQBio1qkkREhxhc656ViA==} - cpu: [arm64] - os: [freebsd] - - '@rollup/rollup-freebsd-x64@4.53.2': - resolution: {integrity: sha512-ClAmAPx3ZCHtp6ysl4XEhWU69GUB1D+s7G9YjHGhIGCSrsg00nEGRRZHmINYxkdoJehde8VIsDC5t9C0gb6yqA==} - cpu: [x64] - os: [freebsd] - - '@rollup/rollup-linux-arm-gnueabihf@4.53.2': - resolution: {integrity: sha512-EPlb95nUsz6Dd9Qy13fI5kUPXNSljaG9FiJ4YUGU1O/Q77i5DYFW5KR8g1OzTcdZUqQQ1KdDqsTohdFVwCwjqg==} - cpu: [arm] - os: [linux] - - '@rollup/rollup-linux-arm-musleabihf@4.53.2': - resolution: {integrity: sha512-BOmnVW+khAUX+YZvNfa0tGTEMVVEerOxN0pDk2E6N6DsEIa2Ctj48FOMfNDdrwinocKaC7YXUZ1pHlKpnkja/Q==} - cpu: [arm] - os: [linux] - - '@rollup/rollup-linux-arm64-gnu@4.53.2': - resolution: {integrity: sha512-Xt2byDZ+6OVNuREgBXr4+CZDJtrVso5woFtpKdGPhpTPHcNG7D8YXeQzpNbFRxzTVqJf7kvPMCub/pcGUWgBjA==} - cpu: [arm64] - os: [linux] - - '@rollup/rollup-linux-arm64-musl@4.53.2': - resolution: {integrity: sha512-+LdZSldy/I9N8+klim/Y1HsKbJ3BbInHav5qE9Iy77dtHC/pibw1SR/fXlWyAk0ThnpRKoODwnAuSjqxFRDHUQ==} - cpu: [arm64] - os: [linux] - - '@rollup/rollup-linux-loong64-gnu@4.53.2': - resolution: {integrity: sha512-8ms8sjmyc1jWJS6WdNSA23rEfdjWB30LH8Wqj0Cqvv7qSHnvw6kgMMXRdop6hkmGPlyYBdRPkjJnj3KCUHV/uQ==} - cpu: [loong64] - os: [linux] - - '@rollup/rollup-linux-ppc64-gnu@4.53.2': - resolution: {integrity: sha512-3HRQLUQbpBDMmzoxPJYd3W6vrVHOo2cVW8RUo87Xz0JPJcBLBr5kZ1pGcQAhdZgX9VV7NbGNipah1omKKe23/g==} - cpu: [ppc64] - os: [linux] - - '@rollup/rollup-linux-riscv64-gnu@4.53.2': - resolution: {integrity: sha512-fMjKi+ojnmIvhk34gZP94vjogXNNUKMEYs+EDaB/5TG/wUkoeua7p7VCHnE6T2Tx+iaghAqQX8teQzcvrYpaQA==} - cpu: [riscv64] - os: [linux] - - '@rollup/rollup-linux-riscv64-musl@4.53.2': - resolution: {integrity: sha512-XuGFGU+VwUUV5kLvoAdi0Wz5Xbh2SrjIxCtZj6Wq8MDp4bflb/+ThZsVxokM7n0pcbkEr2h5/pzqzDYI7cCgLQ==} - cpu: [riscv64] - os: [linux] - - '@rollup/rollup-linux-s390x-gnu@4.53.2': - resolution: {integrity: sha512-w6yjZF0P+NGzWR3AXWX9zc0DNEGdtvykB03uhonSHMRa+oWA6novflo2WaJr6JZakG2ucsyb+rvhrKac6NIy+w==} - cpu: [s390x] - os: [linux] - - '@rollup/rollup-linux-x64-gnu@4.53.2': - resolution: {integrity: sha512-yo8d6tdfdeBArzC7T/PnHd7OypfI9cbuZzPnzLJIyKYFhAQ8SvlkKtKBMbXDxe1h03Rcr7u++nFS7tqXz87Gtw==} - cpu: [x64] - os: [linux] - - '@rollup/rollup-linux-x64-musl@4.53.2': - resolution: {integrity: sha512-ah59c1YkCxKExPP8O9PwOvs+XRLKwh/mV+3YdKqQ5AMQ0r4M4ZDuOrpWkUaqO7fzAHdINzV9tEVu8vNw48z0lA==} - cpu: [x64] - os: [linux] - - '@rollup/rollup-openharmony-arm64@4.53.2': - resolution: {integrity: sha512-4VEd19Wmhr+Zy7hbUsFZ6YXEiP48hE//KPLCSVNY5RMGX2/7HZ+QkN55a3atM1C/BZCGIgqN+xrVgtdak2S9+A==} - cpu: [arm64] - os: [openharmony] - - '@rollup/rollup-win32-arm64-msvc@4.53.2': - resolution: {integrity: sha512-IlbHFYc/pQCgew/d5fslcy1KEaYVCJ44G8pajugd8VoOEI8ODhtb/j8XMhLpwHCMB3yk2J07ctup10gpw2nyMA==} - cpu: [arm64] - os: [win32] - - '@rollup/rollup-win32-ia32-msvc@4.53.2': - resolution: {integrity: sha512-lNlPEGgdUfSzdCWU176ku/dQRnA7W+Gp8d+cWv73jYrb8uT7HTVVxq62DUYxjbaByuf1Yk0RIIAbDzp+CnOTFg==} - cpu: [ia32] - os: [win32] - - '@rollup/rollup-win32-x64-gnu@4.53.2': - resolution: {integrity: sha512-S6YojNVrHybQis2lYov1sd+uj7K0Q05NxHcGktuMMdIQ2VixGwAfbJ23NnlvvVV1bdpR2m5MsNBViHJKcA4ADw==} - cpu: [x64] - os: [win32] - - '@rollup/rollup-win32-x64-msvc@4.53.2': - resolution: {integrity: sha512-k+/Rkcyx//P6fetPoLMb8pBeqJBNGx81uuf7iljX9++yNBVRDQgD04L+SVXmXmh5ZP4/WOp4mWF0kmi06PW2tA==} - cpu: [x64] - os: [win32] - - '@rtsao/scc@1.1.0': - resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==} - - '@standard-schema/spec@1.0.0': - resolution: {integrity: sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA==} - - '@tybys/wasm-util@0.10.1': - resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==} - - '@types/body-parser@1.19.6': - resolution: {integrity: sha512-HLFeCYgz89uk22N5Qg3dvGvsv46B8GLvKKo1zKG4NybA8U2DiEO3w9lqGg29t/tfLRJpJ6iQxnVw4OnB7MoM9g==} - - '@types/chai@5.2.3': - resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} - - '@types/connect@3.4.38': - resolution: {integrity: sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==} - - '@types/content-type@1.1.9': - resolution: {integrity: sha512-Hq9IMnfekuOCsEmYl4QX2HBrT+XsfXiupfrLLY8Dcf3Puf4BkBOxSbWYTITSOQAhJoYPBez+b4MJRpIYL65z8A==} - - '@types/cookiejar@2.1.5': - resolution: {integrity: sha512-he+DHOWReW0nghN24E1WUqM0efK4kI9oTqDm6XmK8ZPe2djZ90BSNdGnIyCLzCPw7/pogPlGbzI2wHGGmi4O/Q==} - - '@types/cors@2.8.19': - resolution: {integrity: sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==} - - '@types/cross-spawn@6.0.6': - resolution: {integrity: sha512-fXRhhUkG4H3TQk5dBhQ7m/JDdSNHKwR2BBia62lhwEIq9xGiQKLxd6LymNhn47SjXhsUEPmxi+PKw2OkW4LLjA==} - - '@types/deep-eql@4.0.2': - resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} - - '@types/estree@1.0.8': - resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==} - - '@types/eventsource@1.1.15': - resolution: {integrity: sha512-XQmGcbnxUNa06HR3VBVkc9+A2Vpi9ZyLJcdS5dwaQQ/4ZMWFO+5c90FnMUpbtMZwB/FChoYHwuVg8TvkECacTA==} - - '@types/express-serve-static-core@5.1.0': - resolution: {integrity: sha512-jnHMsrd0Mwa9Cf4IdOzbz543y4XJepXrbia2T4b6+spXC2We3t1y6K44D3mR8XMFSXMCf3/l7rCgddfx7UNVBA==} - - '@types/express@5.0.5': - resolution: {integrity: sha512-LuIQOcb6UmnF7C1PCFmEU1u2hmiHL43fgFQX67sN3H4Z+0Yk0Neo++mFsBjhOAuLzvlQeqAAkeDOZrJs9rzumQ==} - - '@types/http-errors@2.0.5': - resolution: {integrity: sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==} - - '@types/json-schema@7.0.15': - resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} - - '@types/json5@0.0.29': - resolution: {integrity: sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==} - - '@types/methods@1.1.4': - resolution: {integrity: sha512-ymXWVrDiCxTBE3+RIrrP533E70eA+9qu7zdWoHuOmGujkYtzf4HQF96b8nwHLqhuf4ykX61IGRIB38CC6/sImQ==} - - '@types/mime@1.3.5': - resolution: {integrity: sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==} - - '@types/node@12.20.55': - resolution: {integrity: sha512-J8xLz7q2OFulZ2cyGTLE1TbbZcjpno7FaN6zdJNrgAdrJ+DZzh/uFR6YrTb4C+nXakvud8Q4+rbhoIWlYQbUFQ==} - - '@types/node@24.10.3': - resolution: {integrity: sha512-gqkrWUsS8hcm0r44yn7/xZeV1ERva/nLgrLxFRUGb7aoNMIJfZJ3AC261zDQuOAKC7MiXai1WCpYc48jAHoShQ==} - - '@types/qs@6.14.0': - resolution: {integrity: sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ==} - - '@types/range-parser@1.2.7': - resolution: {integrity: sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==} - - '@types/send@0.17.6': - resolution: {integrity: sha512-Uqt8rPBE8SY0RK8JB1EzVOIZ32uqy8HwdxCnoCOsYrvnswqmFZ/k+9Ikidlk/ImhsdvBsloHbAlewb2IEBV/Og==} - - '@types/send@1.2.1': - resolution: {integrity: sha512-arsCikDvlU99zl1g69TcAB3mzZPpxgw0UQnaHeC1Nwb015xp8bknZv5rIfri9xTOcMuaVgvabfIRA7PSZVuZIQ==} - - '@types/serve-static@1.15.10': - resolution: {integrity: sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==} - - '@types/superagent@8.1.9': - resolution: {integrity: sha512-pTVjI73witn+9ILmoJdajHGW2jkSaOzhiFYF1Rd3EQ94kymLqB9PjD9ISg7WaALC7+dCHT0FGe9T2LktLq/3GQ==} - - '@types/supertest@6.0.3': - resolution: {integrity: sha512-8WzXq62EXFhJ7QsH3Ocb/iKQ/Ty9ZVWnVzoTKc9tyyFRRF3a74Tk2+TLFgaFFw364Ere+npzHKEJ6ga2LzIL7w==} - - '@types/ws@8.18.1': - resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==} - - '@typescript-eslint/eslint-plugin@8.49.0': - resolution: {integrity: sha512-JXij0vzIaTtCwu6SxTh8qBc66kmf1xs7pI4UOiMDFVct6q86G0Zs7KRcEoJgY3Cav3x5Tq0MF5jwgpgLqgKG3A==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - '@typescript-eslint/parser': ^8.49.0 - eslint: ^8.57.0 || ^9.0.0 - typescript: '>=4.8.4 <6.0.0' - - '@typescript-eslint/parser@8.49.0': - resolution: {integrity: sha512-N9lBGA9o9aqb1hVMc9hzySbhKibHmB+N3IpoShyV6HyQYRGIhlrO5rQgttypi+yEeKsKI4idxC8Jw6gXKD4THA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - eslint: ^8.57.0 || ^9.0.0 - typescript: '>=4.8.4 <6.0.0' - - '@typescript-eslint/project-service@8.49.0': - resolution: {integrity: sha512-/wJN0/DKkmRUMXjZUXYZpD1NEQzQAAn9QWfGwo+Ai8gnzqH7tvqS7oNVdTjKqOcPyVIdZdyCMoqN66Ia789e7g==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <6.0.0' - - '@typescript-eslint/scope-manager@8.49.0': - resolution: {integrity: sha512-npgS3zi+/30KSOkXNs0LQXtsg9ekZ8OISAOLGWA/ZOEn0ZH74Ginfl7foziV8DT+D98WfQ5Kopwqb/PZOaIJGg==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@typescript-eslint/tsconfig-utils@8.49.0': - resolution: {integrity: sha512-8prixNi1/6nawsRYxet4YOhnbW+W9FK/bQPxsGB1D3ZrDzbJ5FXw5XmzxZv82X3B+ZccuSxo/X8q9nQ+mFecWA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <6.0.0' - - '@typescript-eslint/type-utils@8.49.0': - resolution: {integrity: sha512-KTExJfQ+svY8I10P4HdxKzWsvtVnsuCifU5MvXrRwoP2KOlNZ9ADNEWWsQTJgMxLzS5VLQKDjkCT/YzgsnqmZg==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - eslint: ^8.57.0 || ^9.0.0 - typescript: '>=4.8.4 <6.0.0' - - '@typescript-eslint/types@8.49.0': - resolution: {integrity: sha512-e9k/fneezorUo6WShlQpMxXh8/8wfyc+biu6tnAqA81oWrEic0k21RHzP9uqqpyBBeBKu4T+Bsjy9/b8u7obXQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@typescript-eslint/typescript-estree@8.49.0': - resolution: {integrity: sha512-jrLdRuAbPfPIdYNppHJ/D0wN+wwNfJ32YTAm10eJVsFmrVpXQnDWBn8niCSMlWjvml8jsce5E/O+86IQtTbJWA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - typescript: '>=4.8.4 <6.0.0' - - '@typescript-eslint/utils@8.49.0': - resolution: {integrity: sha512-N3W7rJw7Rw+z1tRsHZbK395TWSYvufBXumYtEGzypgMUthlg0/hmCImeA8hgO2d2G4pd7ftpxxul2J8OdtdaFA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - eslint: ^8.57.0 || ^9.0.0 - typescript: '>=4.8.4 <6.0.0' - - '@typescript-eslint/visitor-keys@8.49.0': - resolution: {integrity: sha512-LlKaciDe3GmZFphXIc79THF/YYBugZ7FS1pO581E/edlVVNbZKDy93evqmrfQ9/Y4uN0vVhX4iuchq26mK/iiA==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - '@typescript/native-preview-darwin-arm64@7.0.0-dev.20251218.3': - resolution: {integrity: sha512-4Ew2waH0alZk3fuTIFJ7EsfjIqDj3mNYLa9aTQse6Xnfv16uFEwHbMs4RR1k6qPbPMnyKMC9fpY6f6p1WAPw4A==} - cpu: [arm64] - os: [darwin] - - '@typescript/native-preview-darwin-x64@7.0.0-dev.20251218.3': - resolution: {integrity: sha512-d+6aZW6ig5QdeZzGct6pm0/QoY+cDjUNggG34EefU8m13ThQUCYZ8xMxtSBJsPpFB7AX+iewE2DJtBdgoEbPdg==} - cpu: [x64] - os: [darwin] - - '@typescript/native-preview-linux-arm64@7.0.0-dev.20251218.3': - resolution: {integrity: sha512-0LY5RZTvShYYKyxy6ApDqpR0fMUaZUwpNYt9tRUoO4zfTLQdn38xMC4vgRZ3AtYSFX0Y185vLraa+tsdVJcvRw==} - cpu: [arm64] - os: [linux] - - '@typescript/native-preview-linux-arm@7.0.0-dev.20251218.3': - resolution: {integrity: sha512-V62lMa3P4Tqynh2qdIEg9MA43Q19YoVbiG+Am6+TL3JV1gkPNCKr17risKz2GXuNRDJvaxrOm6OTRkceoK8Wgg==} - cpu: [arm] - os: [linux] - - '@typescript/native-preview-linux-x64@7.0.0-dev.20251218.3': - resolution: {integrity: sha512-Qi51LQVNiyKcMUnmx2rwSSBWjcxZ+Ec0nkpmeimV0WT1LZJ7ZipJ7KvRRcqLHF2WRk14kknFqDAS83RjdSkPfQ==} - cpu: [x64] - os: [linux] - - '@typescript/native-preview-win32-arm64@7.0.0-dev.20251218.3': - resolution: {integrity: sha512-y2EQoWU9CfVY3qBUbv0JJqddwsUrz7sRx+08mFg3XZOAMPfq6nwmsGrjNeiYBVwIg7gkZO4BqHL0Ktn6PZ9unA==} - cpu: [arm64] - os: [win32] - - '@typescript/native-preview-win32-x64@7.0.0-dev.20251218.3': - resolution: {integrity: sha512-X1s/tIpHhJP3OL/1qAXnfl8XUoCpv5DmWZhLcFB6F7ZjtH4EmvorrCaeSxdb88/KiL8gcxwipdm69eJb0fZWvA==} - cpu: [x64] - os: [win32] - - '@typescript/native-preview@7.0.0-dev.20251218.3': - resolution: {integrity: sha512-FxHW0n7KFG3QhcwRDsP/EWzkvjQYnIqfuDn1y0w4pl6KNh2aK9CRvHjA7bwpft64Tm5eCtYTHM+Gts7MElo9fA==} - hasBin: true - - '@unrs/resolver-binding-android-arm-eabi@1.11.1': - resolution: {integrity: sha512-ppLRUgHVaGRWUx0R0Ut06Mjo9gBaBkg3v/8AxusGLhsIotbBLuRk51rAzqLC8gq6NyyAojEXglNjzf6R948DNw==} - cpu: [arm] - os: [android] - - '@unrs/resolver-binding-android-arm64@1.11.1': - resolution: {integrity: sha512-lCxkVtb4wp1v+EoN+HjIG9cIIzPkX5OtM03pQYkG+U5O/wL53LC4QbIeazgiKqluGeVEeBlZahHalCaBvU1a2g==} - cpu: [arm64] - os: [android] - - '@unrs/resolver-binding-darwin-arm64@1.11.1': - resolution: {integrity: sha512-gPVA1UjRu1Y/IsB/dQEsp2V1pm44Of6+LWvbLc9SDk1c2KhhDRDBUkQCYVWe6f26uJb3fOK8saWMgtX8IrMk3g==} - cpu: [arm64] - os: [darwin] - - '@unrs/resolver-binding-darwin-x64@1.11.1': - resolution: {integrity: sha512-cFzP7rWKd3lZaCsDze07QX1SC24lO8mPty9vdP+YVa3MGdVgPmFc59317b2ioXtgCMKGiCLxJ4HQs62oz6GfRQ==} - cpu: [x64] - os: [darwin] - - '@unrs/resolver-binding-freebsd-x64@1.11.1': - resolution: {integrity: sha512-fqtGgak3zX4DCB6PFpsH5+Kmt/8CIi4Bry4rb1ho6Av2QHTREM+47y282Uqiu3ZRF5IQioJQ5qWRV6jduA+iGw==} - cpu: [x64] - os: [freebsd] - - '@unrs/resolver-binding-linux-arm-gnueabihf@1.11.1': - resolution: {integrity: sha512-u92mvlcYtp9MRKmP+ZvMmtPN34+/3lMHlyMj7wXJDeXxuM0Vgzz0+PPJNsro1m3IZPYChIkn944wW8TYgGKFHw==} - cpu: [arm] - os: [linux] - - '@unrs/resolver-binding-linux-arm-musleabihf@1.11.1': - resolution: {integrity: sha512-cINaoY2z7LVCrfHkIcmvj7osTOtm6VVT16b5oQdS4beibX2SYBwgYLmqhBjA1t51CarSaBuX5YNsWLjsqfW5Cw==} - cpu: [arm] - os: [linux] - - '@unrs/resolver-binding-linux-arm64-gnu@1.11.1': - resolution: {integrity: sha512-34gw7PjDGB9JgePJEmhEqBhWvCiiWCuXsL9hYphDF7crW7UgI05gyBAi6MF58uGcMOiOqSJ2ybEeCvHcq0BCmQ==} - cpu: [arm64] - os: [linux] - - '@unrs/resolver-binding-linux-arm64-musl@1.11.1': - resolution: {integrity: sha512-RyMIx6Uf53hhOtJDIamSbTskA99sPHS96wxVE/bJtePJJtpdKGXO1wY90oRdXuYOGOTuqjT8ACccMc4K6QmT3w==} - cpu: [arm64] - os: [linux] - - '@unrs/resolver-binding-linux-ppc64-gnu@1.11.1': - resolution: {integrity: sha512-D8Vae74A4/a+mZH0FbOkFJL9DSK2R6TFPC9M+jCWYia/q2einCubX10pecpDiTmkJVUH+y8K3BZClycD8nCShA==} - cpu: [ppc64] - os: [linux] - - '@unrs/resolver-binding-linux-riscv64-gnu@1.11.1': - resolution: {integrity: sha512-frxL4OrzOWVVsOc96+V3aqTIQl1O2TjgExV4EKgRY09AJ9leZpEg8Ak9phadbuX0BA4k8U5qtvMSQQGGmaJqcQ==} - cpu: [riscv64] - os: [linux] - - '@unrs/resolver-binding-linux-riscv64-musl@1.11.1': - resolution: {integrity: sha512-mJ5vuDaIZ+l/acv01sHoXfpnyrNKOk/3aDoEdLO/Xtn9HuZlDD6jKxHlkN8ZhWyLJsRBxfv9GYM2utQ1SChKew==} - cpu: [riscv64] - os: [linux] - - '@unrs/resolver-binding-linux-s390x-gnu@1.11.1': - resolution: {integrity: sha512-kELo8ebBVtb9sA7rMe1Cph4QHreByhaZ2QEADd9NzIQsYNQpt9UkM9iqr2lhGr5afh885d/cB5QeTXSbZHTYPg==} - cpu: [s390x] - os: [linux] - - '@unrs/resolver-binding-linux-x64-gnu@1.11.1': - resolution: {integrity: sha512-C3ZAHugKgovV5YvAMsxhq0gtXuwESUKc5MhEtjBpLoHPLYM+iuwSj3lflFwK3DPm68660rZ7G8BMcwSro7hD5w==} - cpu: [x64] - os: [linux] - - '@unrs/resolver-binding-linux-x64-musl@1.11.1': - resolution: {integrity: sha512-rV0YSoyhK2nZ4vEswT/QwqzqQXw5I6CjoaYMOX0TqBlWhojUf8P94mvI7nuJTeaCkkds3QE4+zS8Ko+GdXuZtA==} - cpu: [x64] - os: [linux] - - '@unrs/resolver-binding-wasm32-wasi@1.11.1': - resolution: {integrity: sha512-5u4RkfxJm+Ng7IWgkzi3qrFOvLvQYnPBmjmZQ8+szTK/b31fQCnleNl1GgEt7nIsZRIf5PLhPwT0WM+q45x/UQ==} - engines: {node: '>=14.0.0'} - cpu: [wasm32] - - '@unrs/resolver-binding-win32-arm64-msvc@1.11.1': - resolution: {integrity: sha512-nRcz5Il4ln0kMhfL8S3hLkxI85BXs3o8EYoattsJNdsX4YUU89iOkVn7g0VHSRxFuVMdM4Q1jEpIId1Ihim/Uw==} - cpu: [arm64] - os: [win32] - - '@unrs/resolver-binding-win32-ia32-msvc@1.11.1': - resolution: {integrity: sha512-DCEI6t5i1NmAZp6pFonpD5m7i6aFrpofcp4LA2i8IIq60Jyo28hamKBxNrZcyOwVOZkgsRp9O2sXWBWP8MnvIQ==} - cpu: [ia32] - os: [win32] - - '@unrs/resolver-binding-win32-x64-msvc@1.11.1': - resolution: {integrity: sha512-lrW200hZdbfRtztbygyaq/6jP6AKE8qQN2KvPcJ+x7wiD038YtnYtZ82IMNJ69GJibV7bwL3y9FgK+5w/pYt6g==} - cpu: [x64] - os: [win32] - - '@vitest/expect@4.0.9': - resolution: {integrity: sha512-C2vyXf5/Jfj1vl4DQYxjib3jzyuswMi/KHHVN2z+H4v16hdJ7jMZ0OGe3uOVIt6LyJsAofDdaJNIFEpQcrSTFw==} - - '@vitest/mocker@4.0.9': - resolution: {integrity: sha512-PUyaowQFHW+9FKb4dsvvBM4o025rWMlEDXdWRxIOilGaHREYTi5Q2Rt9VCgXgPy/hHZu1LeuXtrA/GdzOatP2g==} - peerDependencies: - msw: ^2.4.9 - vite: ^6.0.0 || ^7.0.0-0 - peerDependenciesMeta: - msw: - optional: true - vite: - optional: true - - '@vitest/pretty-format@4.0.9': - resolution: {integrity: sha512-Hor0IBTwEi/uZqB7pvGepyElaM8J75pYjrrqbC8ZYMB9/4n5QA63KC15xhT+sqHpdGWfdnPo96E8lQUxs2YzSQ==} - - '@vitest/runner@4.0.9': - resolution: {integrity: sha512-aF77tsXdEvIJRkj9uJZnHtovsVIx22Ambft9HudC+XuG/on1NY/bf5dlDti1N35eJT+QZLb4RF/5dTIG18s98w==} - - '@vitest/snapshot@4.0.9': - resolution: {integrity: sha512-r1qR4oYstPbnOjg0Vgd3E8ADJbi4ditCzqr+Z9foUrRhIy778BleNyZMeAJ2EjV+r4ASAaDsdciC9ryMy8xMMg==} - - '@vitest/spy@4.0.9': - resolution: {integrity: sha512-J9Ttsq0hDXmxmT8CUOWUr1cqqAj2FJRGTdyEjSR+NjoOGKEqkEWj+09yC0HhI8t1W6t4Ctqawl1onHgipJve1A==} - - '@vitest/utils@4.0.9': - resolution: {integrity: sha512-cEol6ygTzY4rUPvNZM19sDf7zGa35IYTm9wfzkHoT/f5jX10IOY7QleWSOh5T0e3I3WVozwK5Asom79qW8DiuQ==} - - accepts@2.0.0: - resolution: {integrity: sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==} - engines: {node: '>= 0.6'} - - acorn-jsx@5.3.2: - resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} - peerDependencies: - acorn: ^6.0.0 || ^7.0.0 || ^8.0.0 - - acorn@8.15.0: - resolution: {integrity: sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==} - engines: {node: '>=0.4.0'} - hasBin: true - - ajv-formats@3.0.1: - resolution: {integrity: sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==} - peerDependencies: - ajv: ^8.0.0 - peerDependenciesMeta: - ajv: - optional: true - - ajv@6.12.6: - resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==} - - ajv@8.17.1: - resolution: {integrity: sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==} - - ansi-colors@4.1.3: - resolution: {integrity: sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==} - engines: {node: '>=6'} - - ansi-regex@5.0.1: - resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} - engines: {node: '>=8'} - - ansi-styles@4.3.0: - resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} - engines: {node: '>=8'} - - ansis@4.2.0: - resolution: {integrity: sha512-HqZ5rWlFjGiV0tDm3UxxgNRqsOTniqoKZu0pIAfh7TZQMGuZK+hH0drySty0si0QXj1ieop4+SkSfPZBPPkHig==} - engines: {node: '>=14'} - - argparse@1.0.10: - resolution: {integrity: sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==} - - argparse@2.0.1: - resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} - - array-buffer-byte-length@1.0.2: - resolution: {integrity: sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==} - engines: {node: '>= 0.4'} - - array-includes@3.1.9: - resolution: {integrity: sha512-FmeCCAenzH0KH381SPT5FZmiA/TmpndpcaShhfgEN9eCVjnFBqq3l1xrI42y8+PPLI6hypzou4GXw00WHmPBLQ==} - engines: {node: '>= 0.4'} - - array-union@2.1.0: - resolution: {integrity: sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw==} - engines: {node: '>=8'} - - array.prototype.findlastindex@1.2.6: - resolution: {integrity: sha512-F/TKATkzseUExPlfvmwQKGITM3DGTK+vkAsCZoDc5daVygbJBnjEUCbgkAvVFsgfXfX4YIqZ/27G3k3tdXrTxQ==} - engines: {node: '>= 0.4'} - - array.prototype.flat@1.3.3: - resolution: {integrity: sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==} - engines: {node: '>= 0.4'} - - array.prototype.flatmap@1.3.3: - resolution: {integrity: sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==} - engines: {node: '>= 0.4'} - - arraybuffer.prototype.slice@1.0.4: - resolution: {integrity: sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==} - engines: {node: '>= 0.4'} - - asap@2.0.6: - resolution: {integrity: sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==} - - assertion-error@2.0.1: - resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} - engines: {node: '>=12'} - - ast-kit@2.2.0: - resolution: {integrity: sha512-m1Q/RaVOnTp9JxPX+F+Zn7IcLYMzM8kZofDImfsKZd8MbR+ikdOzTeztStWqfrqIxZnYWryyI9ePm3NGjnZgGw==} - engines: {node: '>=20.19.0'} - - async-function@1.0.0: - resolution: {integrity: sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==} - engines: {node: '>= 0.4'} - - asynckit@0.4.0: - resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} - - available-typed-arrays@1.0.7: - resolution: {integrity: sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==} - engines: {node: '>= 0.4'} - - balanced-match@1.0.2: - resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} - - better-path-resolve@1.0.0: - resolution: {integrity: sha512-pbnl5XzGBdrFU/wT4jqmJVPn2B6UHPBOhzMQkY/SPUPB6QtUXtmBHBIwCbXJol93mOpGMnQyP/+BB19q04xj7g==} - engines: {node: '>=4'} - - birpc@3.0.0: - resolution: {integrity: sha512-by+04pHuxpCEQcucAXqzopqfhyI8TLK5Qg5MST0cB6MP+JhHna9ollrtK9moVh27aq6Q6MEJgebD0cVm//yBkg==} - - body-parser@2.2.0: - resolution: {integrity: sha512-02qvAaxv8tp7fBa/mw1ga98OGm+eCbqzJOKoRt70sLmfEEi+jyBYVTDGfCL/k06/4EMk/z01gCe7HoCH/f2LTg==} - engines: {node: '>=18'} - - brace-expansion@1.1.12: - resolution: {integrity: sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==} - - brace-expansion@2.0.2: - resolution: {integrity: sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==} - - braces@3.0.3: - resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} - engines: {node: '>=8'} - - bytes@3.1.2: - resolution: {integrity: sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==} - engines: {node: '>= 0.8'} - - cac@6.7.14: - resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} - engines: {node: '>=8'} - - call-bind-apply-helpers@1.0.2: - resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} - engines: {node: '>= 0.4'} - - call-bind@1.0.8: - resolution: {integrity: sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==} - engines: {node: '>= 0.4'} - - call-bound@1.0.4: - resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==} - engines: {node: '>= 0.4'} - - callsites@3.1.0: - resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} - engines: {node: '>=6'} - - chai@6.2.1: - resolution: {integrity: sha512-p4Z49OGG5W/WBCPSS/dH3jQ73kD6tiMmUM+bckNK6Jr5JHMG3k9bg/BvKR8lKmtVBKmOiuVaV2ws8s9oSbwysg==} - engines: {node: '>=18'} - - chalk@4.1.2: - resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} - engines: {node: '>=10'} - - chardet@2.1.1: - resolution: {integrity: sha512-PsezH1rqdV9VvyNhxxOW32/d75r01NY7TQCmOqomRo15ZSOKbpTFVsfjghxo6JloQUCGnH4k1LGu0R4yCLlWQQ==} - - ci-info@3.9.0: - resolution: {integrity: sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==} - engines: {node: '>=8'} - - color-convert@2.0.1: - resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} - engines: {node: '>=7.0.0'} - - color-name@1.1.4: - resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} - - combined-stream@1.0.8: - resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} - engines: {node: '>= 0.8'} - - component-emitter@1.3.1: - resolution: {integrity: sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ==} - - concat-map@0.0.1: - resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} - - content-disposition@1.0.0: - resolution: {integrity: sha512-Au9nRL8VNUut/XSzbQA38+M78dzP4D+eqg3gfJHMIHHYa3bg067xj1KxMUWj+VULbiZMowKngFFbKczUrNJ1mg==} - engines: {node: '>= 0.6'} - - content-type@1.0.5: - resolution: {integrity: sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==} - engines: {node: '>= 0.6'} - - cookie-signature@1.2.2: - resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==} - engines: {node: '>=6.6.0'} - - cookie@0.7.2: - resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==} - engines: {node: '>= 0.6'} - - cookiejar@2.1.4: - resolution: {integrity: sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==} - - cors@2.8.5: - resolution: {integrity: sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==} - engines: {node: '>= 0.10'} - - cross-spawn@7.0.6: - resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} - engines: {node: '>= 8'} - - data-view-buffer@1.0.2: - resolution: {integrity: sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==} - engines: {node: '>= 0.4'} - - data-view-byte-length@1.0.2: - resolution: {integrity: sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==} - engines: {node: '>= 0.4'} - - data-view-byte-offset@1.0.1: - resolution: {integrity: sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==} - engines: {node: '>= 0.4'} - - dataloader@1.4.0: - resolution: {integrity: sha512-68s5jYdlvasItOJnCuI2Q9s4q98g0pCyL3HrcKJu8KNugUl8ahgmZYg38ysLTgQjjXX3H8CJLkAvWrclWfcalw==} - - debug@3.2.7: - resolution: {integrity: sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==} - peerDependencies: - supports-color: '*' - peerDependenciesMeta: - supports-color: - optional: true - - debug@4.4.3: - resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} - engines: {node: '>=6.0'} - peerDependencies: - supports-color: '*' - peerDependenciesMeta: - supports-color: - optional: true - - deep-is@0.1.4: - resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} - - define-data-property@1.1.4: - resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==} - engines: {node: '>= 0.4'} - - define-properties@1.2.1: - resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==} - engines: {node: '>= 0.4'} - - defu@6.1.4: - resolution: {integrity: sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg==} - - delayed-stream@1.0.0: - resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} - engines: {node: '>=0.4.0'} - - depd@2.0.0: - resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} - engines: {node: '>= 0.8'} - - detect-indent@6.1.0: - resolution: {integrity: sha512-reYkTUJAZb9gUuZ2RvVCNhVHdg62RHnJ7WJl8ftMi4diZ6NWlciOzQN88pUhSELEwflJht4oQDv0F0BMlwaYtA==} - engines: {node: '>=8'} - - dezalgo@1.0.4: - resolution: {integrity: sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==} - - dir-glob@3.0.1: - resolution: {integrity: sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA==} - engines: {node: '>=8'} - - doctrine@2.1.0: - resolution: {integrity: sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==} - engines: {node: '>=0.10.0'} - - dotenv@8.6.0: - resolution: {integrity: sha512-IrPdXQsk2BbzvCBGBOTmmSH5SodmqZNt4ERAZDmW4CT+tL8VtvinqywuANaFu4bOMWki16nqf0e4oC0QIaDr/g==} - engines: {node: '>=10'} - - dts-resolver@2.1.3: - resolution: {integrity: sha512-bihc7jPC90VrosXNzK0LTE2cuLP6jr0Ro8jk+kMugHReJVLIpHz/xadeq3MhuwyO4TD4OA3L1Q8pBBFRc08Tsw==} - engines: {node: '>=20.19.0'} - peerDependencies: - oxc-resolver: '>=11.0.0' - peerDependenciesMeta: - oxc-resolver: - optional: true - - dunder-proto@1.0.1: - resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} - engines: {node: '>= 0.4'} - - ee-first@1.1.1: - resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==} - - empathic@2.0.0: - resolution: {integrity: sha512-i6UzDscO/XfAcNYD75CfICkmfLedpyPDdozrLMmQc5ORaQcdMoc21OnlEylMIqI7U8eniKrPMxxtj8k0vhmJhA==} - engines: {node: '>=14'} - - encodeurl@2.0.0: - resolution: {integrity: sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==} - engines: {node: '>= 0.8'} - - enhanced-resolve@5.18.3: - resolution: {integrity: sha512-d4lC8xfavMeBjzGr2vECC3fsGXziXZQyJxD868h2M/mBI3PwAuODxAkLkq5HYuvrPYcUtiLzsTo8U3PgX3Ocww==} - engines: {node: '>=10.13.0'} - - enquirer@2.4.1: - resolution: {integrity: sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ==} - engines: {node: '>=8.6'} - - es-abstract@1.24.0: - resolution: {integrity: sha512-WSzPgsdLtTcQwm4CROfS5ju2Wa1QQcVeT37jFjYzdFz1r9ahadC8B8/a4qxJxM+09F18iumCdRmlr96ZYkQvEg==} - engines: {node: '>= 0.4'} - - es-define-property@1.0.1: - resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} - engines: {node: '>= 0.4'} - - es-errors@1.3.0: - resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} - engines: {node: '>= 0.4'} - - es-module-lexer@1.7.0: - resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==} - - es-object-atoms@1.1.1: - resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==} - engines: {node: '>= 0.4'} - - es-set-tostringtag@2.1.0: - resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} - engines: {node: '>= 0.4'} - - es-shim-unscopables@1.1.0: - resolution: {integrity: sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==} - engines: {node: '>= 0.4'} - - es-to-primitive@1.3.0: - resolution: {integrity: sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==} - engines: {node: '>= 0.4'} - - esbuild@0.25.12: - resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==} - engines: {node: '>=18'} - hasBin: true - - escape-html@1.0.3: - resolution: {integrity: sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==} - - escape-string-regexp@4.0.0: - resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} - engines: {node: '>=10'} - - eslint-compat-utils@0.5.1: - resolution: {integrity: sha512-3z3vFexKIEnjHE3zCMRo6fn/e44U7T1khUjg+Hp0ZQMCigh28rALD0nPFBcGZuiLC5rLZa2ubQHDRln09JfU2Q==} - engines: {node: '>=12'} - peerDependencies: - eslint: '>=6.0.0' - - eslint-config-prettier@10.1.8: - resolution: {integrity: sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w==} - hasBin: true - peerDependencies: - eslint: '>=7.0.0' - - eslint-import-context@0.1.9: - resolution: {integrity: sha512-K9Hb+yRaGAGUbwjhFNHvSmmkZs9+zbuoe3kFQ4V1wYjrepUFYM2dZAfNtjbbj3qsPfUfsA68Bx/ICWQMi+C8Eg==} - engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0} - peerDependencies: - unrs-resolver: ^1.0.0 - peerDependenciesMeta: - unrs-resolver: - optional: true - - eslint-import-resolver-node@0.3.9: - resolution: {integrity: sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g==} - - eslint-import-resolver-typescript@4.4.4: - resolution: {integrity: sha512-1iM2zeBvrYmUNTj2vSC/90JTHDth+dfOfiNKkxApWRsTJYNrc8rOdxxIf5vazX+BiAXTeOT0UvWpGI/7qIWQOw==} - engines: {node: ^16.17.0 || >=18.6.0} - peerDependencies: - eslint: '*' - eslint-plugin-import: '*' - eslint-plugin-import-x: '*' - peerDependenciesMeta: - eslint-plugin-import: - optional: true - eslint-plugin-import-x: - optional: true - - eslint-module-utils@2.12.1: - resolution: {integrity: sha512-L8jSWTze7K2mTg0vos/RuLRS5soomksDPoJLXIslC7c8Wmut3bx7CPpJijDcBZtxQ5lrbUdM+s0OlNbz0DCDNw==} - engines: {node: '>=4'} - peerDependencies: - '@typescript-eslint/parser': '*' - eslint: '*' - eslint-import-resolver-node: '*' - eslint-import-resolver-typescript: '*' - eslint-import-resolver-webpack: '*' - peerDependenciesMeta: - '@typescript-eslint/parser': - optional: true - eslint: - optional: true - eslint-import-resolver-node: - optional: true - eslint-import-resolver-typescript: - optional: true - eslint-import-resolver-webpack: - optional: true - - eslint-plugin-es-x@7.8.0: - resolution: {integrity: sha512-7Ds8+wAAoV3T+LAKeu39Y5BzXCrGKrcISfgKEqTS4BDN8SFEDQd0S43jiQ8vIa3wUKD07qitZdfzlenSi8/0qQ==} - engines: {node: ^14.18.0 || >=16.0.0} - peerDependencies: - eslint: '>=8' - - eslint-plugin-import@2.32.0: - resolution: {integrity: sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==} - engines: {node: '>=4'} - peerDependencies: - '@typescript-eslint/parser': '*' - eslint: ^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 || ^9 - peerDependenciesMeta: - '@typescript-eslint/parser': - optional: true - - eslint-plugin-n@17.23.1: - resolution: {integrity: sha512-68PealUpYoHOBh332JLLD9Sj7OQUDkFpmcfqt8R9sySfFSeuGJjMTJQvCRRB96zO3A/PELRLkPrzsHmzEFQQ5A==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - eslint: '>=8.23.0' - - eslint-plugin-simple-import-sort@12.1.1: - resolution: {integrity: sha512-6nuzu4xwQtE3332Uz0to+TxDQYRLTKRESSc2hefVT48Zc8JthmN23Gx9lnYhu0FtkRSL1oxny3kJ2aveVhmOVA==} - peerDependencies: - eslint: '>=5.0.0' - - eslint-scope@8.4.0: - resolution: {integrity: sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - eslint-visitor-keys@3.4.3: - resolution: {integrity: sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==} - engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - - eslint-visitor-keys@4.2.1: - resolution: {integrity: sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - eslint@9.39.1: - resolution: {integrity: sha512-BhHmn2yNOFA9H9JmmIVKJmd288g9hrVRDkdoIgRCRuSySRUHH7r/DI6aAXW9T1WwUuY3DFgrcaqB+deURBLR5g==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - hasBin: true - peerDependencies: - jiti: '*' - peerDependenciesMeta: - jiti: - optional: true - - espree@10.4.0: - resolution: {integrity: sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - - esprima@4.0.1: - resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==} - engines: {node: '>=4'} - hasBin: true - - esquery@1.6.0: - resolution: {integrity: sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==} - engines: {node: '>=0.10'} - - esrecurse@4.3.0: - resolution: {integrity: sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==} - engines: {node: '>=4.0'} - - estraverse@5.3.0: - resolution: {integrity: sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==} - engines: {node: '>=4.0'} - - estree-walker@3.0.3: - resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} - - esutils@2.0.3: - resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} - engines: {node: '>=0.10.0'} - - etag@1.8.1: - resolution: {integrity: sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==} - engines: {node: '>= 0.6'} - - eventsource-parser@3.0.6: - resolution: {integrity: sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==} - engines: {node: '>=18.0.0'} - - eventsource@3.0.7: - resolution: {integrity: sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==} - engines: {node: '>=18.0.0'} - - expect-type@1.2.2: - resolution: {integrity: sha512-JhFGDVJ7tmDJItKhYgJCGLOWjuK9vPxiXoUFLwLDc99NlmklilbiQJwoctZtt13+xMw91MCk/REan6MWHqDjyA==} - engines: {node: '>=12.0.0'} - - express-rate-limit@7.5.1: - resolution: {integrity: sha512-7iN8iPMDzOMHPUYllBEsQdWVB6fPDMPqwjBaFrgr4Jgr/+okjvzAy+UHlYYL/Vs0OsOrMkwS6PJDkFlJwoxUnw==} - engines: {node: '>= 16'} - peerDependencies: - express: '>= 4.11' - - express@5.1.0: - resolution: {integrity: sha512-DT9ck5YIRU+8GYzzU5kT3eHGA5iL+1Zd0EutOmTE9Dtk+Tvuzd23VBU+ec7HPNSTxXYO55gPV/hq4pSBJDjFpA==} - engines: {node: '>= 18'} - - extendable-error@0.1.7: - resolution: {integrity: sha512-UOiS2in6/Q0FK0R0q6UY9vYpQ21mr/Qn1KOnte7vsACuNJf514WvCCUHSRCPcgjPT2bAhNIJdlE6bVap1GKmeg==} - - fast-deep-equal@3.1.3: - resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} - - fast-glob@3.3.3: - resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==} - engines: {node: '>=8.6.0'} - - fast-json-stable-stringify@2.1.0: - resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} - - fast-levenshtein@2.0.6: - resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} - - fast-safe-stringify@2.1.1: - resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==} - - fast-uri@3.1.0: - resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==} - - fastq@1.19.1: - resolution: {integrity: sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==} - - fdir@6.5.0: - resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} - engines: {node: '>=12.0.0'} - peerDependencies: - picomatch: ^3 || ^4 - peerDependenciesMeta: - picomatch: - optional: true - - file-entry-cache@8.0.0: - resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} - engines: {node: '>=16.0.0'} - - fill-range@7.1.1: - resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} - engines: {node: '>=8'} - - finalhandler@2.1.0: - resolution: {integrity: sha512-/t88Ty3d5JWQbWYgaOGCCYfXRwV1+be02WqYYlL6h0lEiUAMPM8o8qKGO01YIkOHzka2up08wvgYD0mDiI+q3Q==} - engines: {node: '>= 0.8'} - - find-up@4.1.0: - resolution: {integrity: sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==} - engines: {node: '>=8'} - - find-up@5.0.0: - resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} - engines: {node: '>=10'} - - flat-cache@4.0.1: - resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} - engines: {node: '>=16'} - - flatted@3.3.3: - resolution: {integrity: sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==} - - for-each@0.3.5: - resolution: {integrity: sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==} - engines: {node: '>= 0.4'} - - form-data@4.0.4: - resolution: {integrity: sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==} - engines: {node: '>= 6'} - - formidable@3.5.4: - resolution: {integrity: sha512-YikH+7CUTOtP44ZTnUhR7Ic2UASBPOqmaRkRKxRbywPTe5VxF7RRCck4af9wutiZ/QKM5nME9Bie2fFaPz5Gug==} - engines: {node: '>=14.0.0'} - - forwarded@0.2.0: - resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==} - engines: {node: '>= 0.6'} - - fresh@2.0.0: - resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==} - engines: {node: '>= 0.8'} - - fs-extra@7.0.1: - resolution: {integrity: sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==} - engines: {node: '>=6 <7 || >=8'} - - fs-extra@8.1.0: - resolution: {integrity: sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==} - engines: {node: '>=6 <7 || >=8'} - - fsevents@2.3.3: - resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} - engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} - os: [darwin] - - function-bind@1.1.2: - resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} - - function.prototype.name@1.1.8: - resolution: {integrity: sha512-e5iwyodOHhbMr/yNrc7fDYG4qlbIvI5gajyzPnb5TCwyhjApznQh1BMFou9b30SevY43gCJKXycoCBjMbsuW0Q==} - engines: {node: '>= 0.4'} - - functions-have-names@1.2.3: - resolution: {integrity: sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==} - - generator-function@2.0.1: - resolution: {integrity: sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==} - engines: {node: '>= 0.4'} - - get-intrinsic@1.3.0: - resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} - engines: {node: '>= 0.4'} - - get-proto@1.0.1: - resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} - engines: {node: '>= 0.4'} - - get-symbol-description@1.1.0: - resolution: {integrity: sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==} - engines: {node: '>= 0.4'} - - get-tsconfig@4.13.0: - resolution: {integrity: sha512-1VKTZJCwBrvbd+Wn3AOgQP/2Av+TfTCOlE4AcRJE72W1ksZXbAx8PPBR9RzgTeSPzlPMHrbANMH3LbltH73wxQ==} - - glob-parent@5.1.2: - resolution: {integrity: sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==} - engines: {node: '>= 6'} - - glob-parent@6.0.2: - resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} - engines: {node: '>=10.13.0'} - - globals@14.0.0: - resolution: {integrity: sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==} - engines: {node: '>=18'} - - globals@15.15.0: - resolution: {integrity: sha512-7ACyT3wmyp3I61S4fG682L0VA2RGD9otkqGJIwNUMF1SWUombIIk+af1unuDYgMm082aHYwD+mzJvv9Iu8dsgg==} - engines: {node: '>=18'} - - globalthis@1.0.4: - resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==} - engines: {node: '>= 0.4'} - - globby@11.1.0: - resolution: {integrity: sha512-jhIXaOzy1sb8IyocaruWSn1TjmnBVs8Ayhcy83rmxNJ8q2uWKCAj3CnJY+KpGSXCueAPc0i05kVvVKtP1t9S3g==} - engines: {node: '>=10'} - - globrex@0.1.2: - resolution: {integrity: sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg==} - - gopd@1.2.0: - resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} - engines: {node: '>= 0.4'} - - graceful-fs@4.2.11: - resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} - - has-bigints@1.1.0: - resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==} - engines: {node: '>= 0.4'} - - has-flag@4.0.0: - resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} - engines: {node: '>=8'} - - has-property-descriptors@1.0.2: - resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==} - - has-proto@1.2.0: - resolution: {integrity: sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==} - engines: {node: '>= 0.4'} - - has-symbols@1.1.0: - resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} - engines: {node: '>= 0.4'} - - has-tostringtag@1.0.2: - resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==} - engines: {node: '>= 0.4'} - - hasown@2.0.2: - resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} - engines: {node: '>= 0.4'} - - hono@4.11.1: - resolution: {integrity: sha512-KsFcH0xxHes0J4zaQgWbYwmz3UPOOskdqZmItstUG93+Wk1ePBLkLGwbP9zlmh1BFUiL8Qp+Xfu9P7feJWpGNg==} - engines: {node: '>=16.9.0'} - - hookable@5.5.3: - resolution: {integrity: sha512-Yc+BQe8SvoXH1643Qez1zqLRmbA5rCL+sSmk6TVos0LWVfNIB7PGncdlId77WzLGSIB5KaWgTaNTs2lNVEI6VQ==} - - http-errors@2.0.0: - resolution: {integrity: sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==} - engines: {node: '>= 0.8'} - - human-id@4.1.3: - resolution: {integrity: sha512-tsYlhAYpjCKa//8rXZ9DqKEawhPoSytweBC2eNvcaDK+57RZLHGqNs3PZTQO6yekLFSuvA6AlnAfrw1uBvtb+Q==} - hasBin: true - - iconv-lite@0.6.3: - resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==} - engines: {node: '>=0.10.0'} - - iconv-lite@0.7.0: - resolution: {integrity: sha512-cf6L2Ds3h57VVmkZe+Pn+5APsT7FpqJtEhhieDCvrE2MK5Qk9MyffgQyuxQTm6BChfeZNtcOLHp9IcWRVcIcBQ==} - engines: {node: '>=0.10.0'} - - ignore@5.3.2: - resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} - engines: {node: '>= 4'} - - ignore@7.0.5: - resolution: {integrity: sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==} - engines: {node: '>= 4'} - - import-fresh@3.3.1: - resolution: {integrity: sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==} - engines: {node: '>=6'} - - import-without-cache@0.2.3: - resolution: {integrity: sha512-roCvX171VqJ7+7pQt1kSRfwaJvFAC2zhThJWXal1rN8EqzPS3iapkAoNpHh4lM8Na1BDen+n9rVfo73RN+Y87g==} - engines: {node: '>=20.19.0'} - - imurmurhash@0.1.4: - resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} - engines: {node: '>=0.8.19'} - - inherits@2.0.4: - resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} - - internal-slot@1.1.0: - resolution: {integrity: sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==} - engines: {node: '>= 0.4'} - - ipaddr.js@1.9.1: - resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==} - engines: {node: '>= 0.10'} - - is-array-buffer@3.0.5: - resolution: {integrity: sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==} - engines: {node: '>= 0.4'} - - is-async-function@2.1.1: - resolution: {integrity: sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==} - engines: {node: '>= 0.4'} - - is-bigint@1.1.0: - resolution: {integrity: sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==} - engines: {node: '>= 0.4'} - - is-boolean-object@1.2.2: - resolution: {integrity: sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==} - engines: {node: '>= 0.4'} - - is-bun-module@2.0.0: - resolution: {integrity: sha512-gNCGbnnnnFAUGKeZ9PdbyeGYJqewpmc2aKHUEMO5nQPWU9lOmv7jcmQIv+qHD8fXW6W7qfuCwX4rY9LNRjXrkQ==} - - is-callable@1.2.7: - resolution: {integrity: sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==} - engines: {node: '>= 0.4'} - - is-core-module@2.16.1: - resolution: {integrity: sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==} - engines: {node: '>= 0.4'} - - is-data-view@1.0.2: - resolution: {integrity: sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==} - engines: {node: '>= 0.4'} - - is-date-object@1.1.0: - resolution: {integrity: sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==} - engines: {node: '>= 0.4'} - - is-extglob@2.1.1: - resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==} - engines: {node: '>=0.10.0'} - - is-finalizationregistry@1.1.1: - resolution: {integrity: sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==} - engines: {node: '>= 0.4'} - - is-generator-function@1.1.2: - resolution: {integrity: sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==} - engines: {node: '>= 0.4'} - - is-glob@4.0.3: - resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==} - engines: {node: '>=0.10.0'} - - is-map@2.0.3: - resolution: {integrity: sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==} - engines: {node: '>= 0.4'} - - is-negative-zero@2.0.3: - resolution: {integrity: sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==} - engines: {node: '>= 0.4'} - - is-number-object@1.1.1: - resolution: {integrity: sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==} - engines: {node: '>= 0.4'} - - is-number@7.0.0: - resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} - engines: {node: '>=0.12.0'} - - is-promise@4.0.0: - resolution: {integrity: sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==} - - is-regex@1.2.1: - resolution: {integrity: sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==} - engines: {node: '>= 0.4'} - - is-set@2.0.3: - resolution: {integrity: sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==} - engines: {node: '>= 0.4'} - - is-shared-array-buffer@1.0.4: - resolution: {integrity: sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==} - engines: {node: '>= 0.4'} - - is-string@1.1.1: - resolution: {integrity: sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==} - engines: {node: '>= 0.4'} - - is-subdir@1.2.0: - resolution: {integrity: sha512-2AT6j+gXe/1ueqbW6fLZJiIw3F8iXGJtt0yDrZaBhAZEG1raiTxKWU+IPqMCzQAXOUCKdA4UDMgacKH25XG2Cw==} - engines: {node: '>=4'} - - is-symbol@1.1.1: - resolution: {integrity: sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==} - engines: {node: '>= 0.4'} - - is-typed-array@1.1.15: - resolution: {integrity: sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==} - engines: {node: '>= 0.4'} - - is-weakmap@2.0.2: - resolution: {integrity: sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==} - engines: {node: '>= 0.4'} - - is-weakref@1.1.1: - resolution: {integrity: sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==} - engines: {node: '>= 0.4'} - - is-weakset@2.0.4: - resolution: {integrity: sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==} - engines: {node: '>= 0.4'} - - is-windows@1.0.2: - resolution: {integrity: sha512-eXK1UInq2bPmjyX6e3VHIzMLobc4J94i4AWn+Hpq3OU5KkrRC96OAcR3PRJ/pGu6m8TRnBHP9dkXQVsT/COVIA==} - engines: {node: '>=0.10.0'} - - isarray@2.0.5: - resolution: {integrity: sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==} - - isexe@2.0.0: - resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} - - jose@6.1.3: - resolution: {integrity: sha512-0TpaTfihd4QMNwrz/ob2Bp7X04yuxJkjRGi4aKmOqwhov54i6u79oCv7T+C7lo70MKH6BesI3vscD1yb/yzKXQ==} - - js-yaml@3.14.2: - resolution: {integrity: sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==} - hasBin: true - - js-yaml@4.1.0: - resolution: {integrity: sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==} - hasBin: true - - js-yaml@4.1.1: - resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==} - hasBin: true - - jsesc@3.1.0: - resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==} - engines: {node: '>=6'} - hasBin: true - - json-buffer@3.0.1: - resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==} - - json-schema-traverse@0.4.1: - resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} - - json-schema-traverse@1.0.0: - resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} - - json-schema-typed@8.0.2: - resolution: {integrity: sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==} - - json-stable-stringify-without-jsonify@1.0.1: - resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} - - json5@1.0.2: - resolution: {integrity: sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==} - hasBin: true - - jsonfile@4.0.0: - resolution: {integrity: sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==} - - keyv@4.5.4: - resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} - - levn@0.4.1: - resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} - engines: {node: '>= 0.8.0'} - - locate-path@5.0.0: - resolution: {integrity: sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==} - engines: {node: '>=8'} - - locate-path@6.0.0: - resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} - engines: {node: '>=10'} - - lodash.merge@4.6.2: - resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==} - - lodash.startcase@4.4.0: - resolution: {integrity: sha512-+WKqsK294HMSc2jEbNgpHpd0JfIBhp7rEV4aqXWqFr6AlXov+SlcgB1Fv01y2kGe3Gc8nMW7VA0SrGuSkRfIEg==} - - magic-string@0.30.21: - resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} - - math-intrinsics@1.1.0: - resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} - engines: {node: '>= 0.4'} - - media-typer@1.1.0: - resolution: {integrity: sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw==} - engines: {node: '>= 0.8'} - - merge-descriptors@2.0.0: - resolution: {integrity: sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==} - engines: {node: '>=18'} - - merge2@1.4.1: - resolution: {integrity: sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==} - engines: {node: '>= 8'} - - methods@1.1.2: - resolution: {integrity: sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==} - engines: {node: '>= 0.6'} - - micromatch@4.0.8: - resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==} - engines: {node: '>=8.6'} - - mime-db@1.52.0: - resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==} - engines: {node: '>= 0.6'} - - mime-db@1.54.0: - resolution: {integrity: sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==} - engines: {node: '>= 0.6'} - - mime-types@2.1.35: - resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} - engines: {node: '>= 0.6'} - - mime-types@3.0.1: - resolution: {integrity: sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA==} - engines: {node: '>= 0.6'} - - mime@2.6.0: - resolution: {integrity: sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==} - engines: {node: '>=4.0.0'} - hasBin: true - - minimatch@3.1.2: - resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==} - - minimatch@9.0.5: - resolution: {integrity: sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==} - engines: {node: '>=16 || 14 >=14.17'} - - minimist@1.2.8: - resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} - - mri@1.2.0: - resolution: {integrity: sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==} - engines: {node: '>=4'} - - ms@2.1.3: - resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - - nanoid@3.3.11: - resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==} - engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} - hasBin: true - - napi-postinstall@0.3.4: - resolution: {integrity: sha512-PHI5f1O0EP5xJ9gQmFGMS6IZcrVvTjpXjz7Na41gTE7eE2hK11lg04CECCYEEjdc17EV4DO+fkGEtt7TpTaTiQ==} - engines: {node: ^12.20.0 || ^14.18.0 || >=16.0.0} - hasBin: true - - natural-compare@1.4.0: - resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} - - negotiator@1.0.0: - resolution: {integrity: sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg==} - engines: {node: '>= 0.6'} - - node-fetch@2.7.0: - resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==} - engines: {node: 4.x || >=6.0.0} - peerDependencies: - encoding: ^0.1.0 - peerDependenciesMeta: - encoding: - optional: true - - object-assign@4.1.1: - resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} - engines: {node: '>=0.10.0'} - - object-inspect@1.13.4: - resolution: {integrity: sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==} - engines: {node: '>= 0.4'} - - object-keys@1.1.1: - resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==} - engines: {node: '>= 0.4'} - - object.assign@4.1.7: - resolution: {integrity: sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==} - engines: {node: '>= 0.4'} - - object.fromentries@2.0.8: - resolution: {integrity: sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==} - engines: {node: '>= 0.4'} - - object.groupby@1.0.3: - resolution: {integrity: sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==} - engines: {node: '>= 0.4'} - - object.values@1.2.1: - resolution: {integrity: sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==} - engines: {node: '>= 0.4'} - - obug@2.1.1: - resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==} - - on-finished@2.4.1: - resolution: {integrity: sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==} - engines: {node: '>= 0.8'} - - once@1.4.0: - resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} - - optionator@0.9.4: - resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} - engines: {node: '>= 0.8.0'} - - outdent@0.5.0: - resolution: {integrity: sha512-/jHxFIzoMXdqPzTaCpFzAAWhpkSjZPF4Vsn6jAfNpmbH/ymsmd7Qc6VE9BGn0L6YMj6uwpQLxCECpus4ukKS9Q==} - - own-keys@1.0.1: - resolution: {integrity: sha512-qFOyK5PjiWZd+QQIh+1jhdb9LpxTF0qs7Pm8o5QHYZ0M3vKqSqzsZaEB6oWlxZ+q2sJBMI/Ktgd2N5ZwQoRHfg==} - engines: {node: '>= 0.4'} - - p-filter@2.1.0: - resolution: {integrity: sha512-ZBxxZ5sL2HghephhpGAQdoskxplTwr7ICaehZwLIlfL6acuVgZPm8yBNuRAFBGEqtD/hmUeq9eqLg2ys9Xr/yw==} - engines: {node: '>=8'} - - p-limit@2.3.0: - resolution: {integrity: sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==} - engines: {node: '>=6'} - - p-limit@3.1.0: - resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==} - engines: {node: '>=10'} - - p-locate@4.1.0: - resolution: {integrity: sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==} - engines: {node: '>=8'} - - p-locate@5.0.0: - resolution: {integrity: sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==} - engines: {node: '>=10'} - - p-map@2.1.0: - resolution: {integrity: sha512-y3b8Kpd8OAN444hxfBbFfj1FY/RjtTd8tzYwhUqNYXx0fXx2iX4maP4Qr6qhIKbQXI02wTLAda4fYUbDagTUFw==} - engines: {node: '>=6'} - - p-try@2.2.0: - resolution: {integrity: sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==} - engines: {node: '>=6'} - - package-manager-detector@0.2.11: - resolution: {integrity: sha512-BEnLolu+yuz22S56CU1SUKq3XC3PkwD5wv4ikR4MfGvnRVcmzXR9DwSlW2fEamyTPyXHomBJRzgapeuBvRNzJQ==} - - parent-module@1.0.1: - resolution: {integrity: sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==} - engines: {node: '>=6'} - - parseurl@1.3.3: - resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} - engines: {node: '>= 0.8'} - - path-exists@4.0.0: - resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} - engines: {node: '>=8'} - - path-key@3.1.1: - resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} - engines: {node: '>=8'} - - path-parse@1.0.7: - resolution: {integrity: sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==} - - path-to-regexp@8.3.0: - resolution: {integrity: sha512-7jdwVIRtsP8MYpdXSwOS0YdD0Du+qOoF/AEPIt88PcCFrZCzx41oxku1jD88hZBwbNUIEfpqvuhjFaMAqMTWnA==} - - path-type@4.0.0: - resolution: {integrity: sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==} - engines: {node: '>=8'} - - pathe@2.0.3: - resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} - - picocolors@1.1.1: - resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} - - picomatch@2.3.1: - resolution: {integrity: sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==} - engines: {node: '>=8.6'} - - picomatch@4.0.3: - resolution: {integrity: sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==} - engines: {node: '>=12'} - - pify@4.0.1: - resolution: {integrity: sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==} - engines: {node: '>=6'} - - pkce-challenge@5.0.0: - resolution: {integrity: sha512-ueGLflrrnvwB3xuo/uGob5pd5FN7l0MsLf0Z87o/UQmRtwjvfylfc9MurIxRAWywCYTgrvpXBcqjV4OfCYGCIQ==} - engines: {node: '>=16.20.0'} - - possible-typed-array-names@1.1.0: - resolution: {integrity: sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==} - engines: {node: '>= 0.4'} - - postcss@8.5.6: - resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==} - engines: {node: ^10 || ^12 || >=14} - - prelude-ls@1.2.1: - resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} - engines: {node: '>= 0.8.0'} - - prettier@2.8.8: - resolution: {integrity: sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==} - engines: {node: '>=10.13.0'} - hasBin: true - - prettier@3.6.2: - resolution: {integrity: sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==} - engines: {node: '>=14'} - hasBin: true - - proxy-addr@2.0.7: - resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==} - engines: {node: '>= 0.10'} - - punycode@2.3.1: - resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} - engines: {node: '>=6'} - - qs@6.14.0: - resolution: {integrity: sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==} - engines: {node: '>=0.6'} - - quansync@0.2.11: - resolution: {integrity: sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==} - - quansync@1.0.0: - resolution: {integrity: sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA==} - - queue-microtask@1.2.3: - resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} - - range-parser@1.2.1: - resolution: {integrity: sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==} - engines: {node: '>= 0.6'} - - raw-body@3.0.1: - resolution: {integrity: sha512-9G8cA+tuMS75+6G/TzW8OtLzmBDMo8p1JRxN5AZ+LAp8uxGA8V8GZm4GQ4/N5QNQEnLmg6SS7wyuSmbKepiKqA==} - engines: {node: '>= 0.10'} - - read-yaml-file@1.1.0: - resolution: {integrity: sha512-VIMnQi/Z4HT2Fxuwg5KrY174U1VdUIASQVWXXyqtNRtxSr9IYkn1rsI6Tb6HsrHCmB7gVpNwX6JxPTHcH6IoTA==} - engines: {node: '>=6'} - - reflect.getprototypeof@1.0.10: - resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==} - engines: {node: '>= 0.4'} - - regexp.prototype.flags@1.5.4: - resolution: {integrity: sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==} - engines: {node: '>= 0.4'} - - require-from-string@2.0.2: - resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} - engines: {node: '>=0.10.0'} - - resolve-from@4.0.0: - resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} - engines: {node: '>=4'} - - resolve-from@5.0.0: - resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==} - engines: {node: '>=8'} - - resolve-pkg-maps@1.0.0: - resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} - - resolve@1.22.11: - resolution: {integrity: sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==} - engines: {node: '>= 0.4'} - hasBin: true - - reusify@1.1.0: - resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==} - engines: {iojs: '>=1.0.0', node: '>=0.10.0'} - - rolldown-plugin-dts@0.18.3: - resolution: {integrity: sha512-rd1LZ0Awwfyn89UndUF/HoFF4oH9a5j+2ZeuKSJYM80vmeN/p0gslYMnHTQHBEXPhUlvAlqGA3tVgXB/1qFNDg==} - engines: {node: '>=20.19.0'} - peerDependencies: - '@ts-macro/tsc': ^0.3.6 - '@typescript/native-preview': '>=7.0.0-dev.20250601.1' - rolldown: ^1.0.0-beta.51 - typescript: ^5.0.0 - vue-tsc: ~3.1.0 - peerDependenciesMeta: - '@ts-macro/tsc': - optional: true - '@typescript/native-preview': - optional: true - typescript: - optional: true - vue-tsc: - optional: true - - rolldown@1.0.0-beta.53: - resolution: {integrity: sha512-Qd9c2p0XKZdgT5AYd+KgAMggJ8ZmCs3JnS9PTMWkyUfteKlfmKtxJbWTHkVakxwXs1Ub7jrRYVeFeF7N0sQxyw==} - engines: {node: ^20.19.0 || >=22.12.0} - hasBin: true - - rollup@4.53.2: - resolution: {integrity: sha512-MHngMYwGJVi6Fmnk6ISmnk7JAHRNF0UkuucA0CUW3N3a4KnONPEZz+vUanQP/ZC/iY1Qkf3bwPWzyY84wEks1g==} - engines: {node: '>=18.0.0', npm: '>=8.0.0'} - hasBin: true - - router@2.2.0: - resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==} - engines: {node: '>= 18'} - - run-parallel@1.2.0: - resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==} - - safe-array-concat@1.1.3: - resolution: {integrity: sha512-AURm5f0jYEOydBj7VQlVvDrjeFgthDdEF5H1dP+6mNpoXOMo1quQqJ4wvJDyRZ9+pO3kGWoOdmV08cSv2aJV6Q==} - engines: {node: '>=0.4'} - - safe-buffer@5.2.1: - resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} - - safe-push-apply@1.0.0: - resolution: {integrity: sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==} - engines: {node: '>= 0.4'} - - safe-regex-test@1.1.0: - resolution: {integrity: sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==} - engines: {node: '>= 0.4'} - - safer-buffer@2.1.2: - resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==} - - semver@6.3.1: - resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==} - hasBin: true - - semver@7.7.3: - resolution: {integrity: sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==} - engines: {node: '>=10'} - hasBin: true - - send@1.2.0: - resolution: {integrity: sha512-uaW0WwXKpL9blXE2o0bRhoL2EGXIrZxQ2ZQ4mgcfoBxdFmQold+qWsD2jLrfZ0trjKL6vOw0j//eAwcALFjKSw==} - engines: {node: '>= 18'} - - serve-static@2.2.0: - resolution: {integrity: sha512-61g9pCh0Vnh7IutZjtLGGpTA355+OPn2TyDv/6ivP2h/AdAVX9azsoxmg2/M6nZeQZNYBEwIcsne1mJd9oQItQ==} - engines: {node: '>= 18'} - - set-function-length@1.2.2: - resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==} - engines: {node: '>= 0.4'} - - set-function-name@2.0.2: - resolution: {integrity: sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==} - engines: {node: '>= 0.4'} - - set-proto@1.0.0: - resolution: {integrity: sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==} - engines: {node: '>= 0.4'} - - setprototypeof@1.2.0: - resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==} - - shebang-command@2.0.0: - resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} - engines: {node: '>=8'} - - shebang-regex@3.0.0: - resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} - engines: {node: '>=8'} - - side-channel-list@1.0.0: - resolution: {integrity: sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==} - engines: {node: '>= 0.4'} - - side-channel-map@1.0.1: - resolution: {integrity: sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==} - engines: {node: '>= 0.4'} - - side-channel-weakmap@1.0.2: - resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==} - engines: {node: '>= 0.4'} - - side-channel@1.1.0: - resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==} - engines: {node: '>= 0.4'} - - siginfo@2.0.0: - resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} - - signal-exit@4.1.0: - resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} - engines: {node: '>=14'} - - slash@3.0.0: - resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==} - engines: {node: '>=8'} - - source-map-js@1.2.1: - resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} - engines: {node: '>=0.10.0'} - - spawndamnit@3.0.1: - resolution: {integrity: sha512-MmnduQUuHCoFckZoWnXsTg7JaiLBJrKFj9UI2MbRPGaJeVpsLcVBu6P/IGZovziM/YBsellCmsprgNA+w0CzVg==} - - sprintf-js@1.0.3: - resolution: {integrity: sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==} - - stable-hash-x@0.2.0: - resolution: {integrity: sha512-o3yWv49B/o4QZk5ZcsALc6t0+eCelPc44zZsLtCQnZPDwFpDYSWcDnrv2TtMmMbQ7uKo3J0HTURCqckw23czNQ==} - engines: {node: '>=12.0.0'} - - stackback@0.0.2: - resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} - - statuses@2.0.1: - resolution: {integrity: sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==} - engines: {node: '>= 0.8'} - - statuses@2.0.2: - resolution: {integrity: sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==} - engines: {node: '>= 0.8'} - - std-env@3.10.0: - resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==} - - stop-iteration-iterator@1.1.0: - resolution: {integrity: sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==} - engines: {node: '>= 0.4'} - - string.prototype.trim@1.2.10: - resolution: {integrity: sha512-Rs66F0P/1kedk5lyYyH9uBzuiI/kNRmwJAR9quK6VOtIpZ2G+hMZd+HQbbv25MgCA6gEffoMZYxlTod4WcdrKA==} - engines: {node: '>= 0.4'} - - string.prototype.trimend@1.0.9: - resolution: {integrity: sha512-G7Ok5C6E/j4SGfyLCloXTrngQIQU3PWtXGst3yM7Bea9FRURf1S42ZHlZZtsNque2FN2PoUhfZXYLNWwEr4dLQ==} - engines: {node: '>= 0.4'} - - string.prototype.trimstart@1.0.8: - resolution: {integrity: sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==} - engines: {node: '>= 0.4'} - - strip-ansi@6.0.1: - resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==} - engines: {node: '>=8'} - - strip-bom@3.0.0: - resolution: {integrity: sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==} - engines: {node: '>=4'} - - strip-json-comments@3.1.1: - resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} - engines: {node: '>=8'} - - superagent@10.2.3: - resolution: {integrity: sha512-y/hkYGeXAj7wUMjxRbB21g/l6aAEituGXM9Rwl4o20+SX3e8YOSV6BxFXl+dL3Uk0mjSL3kCbNkwURm8/gEDig==} - engines: {node: '>=14.18.0'} - - supertest@7.1.4: - resolution: {integrity: sha512-tjLPs7dVyqgItVFirHYqe2T+MfWc2VOBQ8QFKKbWTA3PU7liZR8zoSpAi/C1k1ilm9RsXIKYf197oap9wXGVYg==} - engines: {node: '>=14.18.0'} - - supports-color@7.2.0: - resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} - engines: {node: '>=8'} - - supports-preserve-symlinks-flag@1.0.0: - resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} - engines: {node: '>= 0.4'} - - tapable@2.3.0: - resolution: {integrity: sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg==} - engines: {node: '>=6'} - - term-size@2.2.1: - resolution: {integrity: sha512-wK0Ri4fOGjv/XPy8SBHZChl8CM7uMc5VML7SqiQ0zG7+J5Vr+RMQDoHa2CNT6KHUnTGIXH34UDMkPzAUyapBZg==} - engines: {node: '>=8'} - - tinybench@2.9.0: - resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} - - tinyexec@0.3.2: - resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} - - tinyexec@1.0.2: - resolution: {integrity: sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==} - engines: {node: '>=18'} - - tinyglobby@0.2.15: - resolution: {integrity: sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==} - engines: {node: '>=12.0.0'} - - tinyrainbow@3.0.3: - resolution: {integrity: sha512-PSkbLUoxOFRzJYjjxHJt9xro7D+iilgMX/C9lawzVuYiIdcihh9DXmVibBe8lmcFrRi/VzlPjBxbN7rH24q8/Q==} - engines: {node: '>=14.0.0'} - - to-regex-range@5.0.1: - resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} - engines: {node: '>=8.0'} - - toidentifier@1.0.1: - resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==} - engines: {node: '>=0.6'} - - tr46@0.0.3: - resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==} - - tree-kill@1.2.2: - resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==} - hasBin: true - - ts-api-utils@2.1.0: - resolution: {integrity: sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==} - engines: {node: '>=18.12'} - peerDependencies: - typescript: '>=4.8.4' - - ts-declaration-location@1.0.7: - resolution: {integrity: sha512-EDyGAwH1gO0Ausm9gV6T2nUvBgXT5kGoCMJPllOaooZ+4VvJiKBdZE7wK18N1deEowhcUptS+5GXZK8U/fvpwA==} - peerDependencies: - typescript: '>=4.0.0' - - tsconfck@3.1.6: - resolution: {integrity: sha512-ks6Vjr/jEw0P1gmOVwutM3B7fWxoWBL2KRDb1JfqGVawBmO5UsvmWOQFGHBPl5yxYz4eERr19E6L7NMv+Fej4w==} - engines: {node: ^18 || >=20} - hasBin: true - peerDependencies: - typescript: ^5.0.0 - peerDependenciesMeta: - typescript: - optional: true - - tsconfig-paths@3.15.0: - resolution: {integrity: sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==} - - tsdown@0.18.0: - resolution: {integrity: sha512-Yotdh3NzizysnqR96xfpHFYtEntk1cZvSRHz8A+Pn3ZHNdTQa4fBQxh6HHzWZwfjdQv47xb7GCv6vEWMtxBirw==} - engines: {node: '>=20.19.0'} - hasBin: true - peerDependencies: - '@arethetypeswrong/core': ^0.18.1 - '@vitejs/devtools': ^0.0.0-alpha.19 - publint: ^0.3.0 - typescript: ^5.0.0 - unplugin-lightningcss: ^0.4.0 - unplugin-unused: ^0.5.0 - peerDependenciesMeta: - '@arethetypeswrong/core': - optional: true - '@vitejs/devtools': - optional: true - publint: - optional: true - typescript: - optional: true - unplugin-lightningcss: - optional: true - unplugin-unused: - optional: true - - tslib@2.8.1: - resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} - - tsx@4.20.6: - resolution: {integrity: sha512-ytQKuwgmrrkDTFP4LjR0ToE2nqgy886GpvRSpU0JAnrdBYppuY5rLkRUYPU1yCryb24SsKBTL/hlDQAEFVwtZg==} - engines: {node: '>=18.0.0'} - hasBin: true - - type-check@0.4.0: - resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} - engines: {node: '>= 0.8.0'} - - type-is@2.0.1: - resolution: {integrity: sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==} - engines: {node: '>= 0.6'} - - typed-array-buffer@1.0.3: - resolution: {integrity: sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==} - engines: {node: '>= 0.4'} - - typed-array-byte-length@1.0.3: - resolution: {integrity: sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==} - engines: {node: '>= 0.4'} - - typed-array-byte-offset@1.0.4: - resolution: {integrity: sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ==} - engines: {node: '>= 0.4'} - - typed-array-length@1.0.7: - resolution: {integrity: sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==} - engines: {node: '>= 0.4'} - - typescript-eslint@8.49.0: - resolution: {integrity: sha512-zRSVH1WXD0uXczCXw+nsdjGPUdx4dfrs5VQoHnUWmv1U3oNlAKv4FUNdLDhVUg+gYn+a5hUESqch//Rv5wVhrg==} - engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - peerDependencies: - eslint: ^8.57.0 || ^9.0.0 - typescript: '>=4.8.4 <6.0.0' - - typescript@5.9.3: - resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} - engines: {node: '>=14.17'} - hasBin: true - - unbox-primitive@1.1.0: - resolution: {integrity: sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==} - engines: {node: '>= 0.4'} - - unconfig-core@7.4.2: - resolution: {integrity: sha512-VgPCvLWugINbXvMQDf8Jh0mlbvNjNC6eSUziHsBCMpxR05OPrNrvDnyatdMjRgcHaaNsCqz+wjNXxNw1kRLHUg==} - - undici-types@7.16.0: - resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==} - - universalify@0.1.2: - resolution: {integrity: sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==} - engines: {node: '>= 4.0.0'} - - unpipe@1.0.0: - resolution: {integrity: sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==} - engines: {node: '>= 0.8'} - - unrs-resolver@1.11.1: - resolution: {integrity: sha512-bSjt9pjaEBnNiGgc9rUiHGKv5l4/TGzDmYw3RhnkJGtLhbnnA/5qJj7x3dNDCRx/PJxu774LlH8lCOlB4hEfKg==} - - unrun@0.2.19: - resolution: {integrity: sha512-DbwbJ9BvPEb3BeZnIpP9S5tGLO/JIgPQ3JrpMRFIfZMZfMG19f26OlLbC2ml8RRdrI2ZA7z2t+at5tsIHbh6Qw==} - engines: {node: '>=20.19.0'} - hasBin: true - peerDependencies: - synckit: ^0.11.11 - peerDependenciesMeta: - synckit: - optional: true - - uri-js@4.4.1: - resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} - - vary@1.1.2: - resolution: {integrity: sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==} - engines: {node: '>= 0.8'} - - vite-tsconfig-paths@5.1.4: - resolution: {integrity: sha512-cYj0LRuLV2c2sMqhqhGpaO3LretdtMn/BVX4cPLanIZuwwrkVl+lK84E/miEXkCHWXuq65rhNN4rXsBcOB3S4w==} - peerDependencies: - vite: '*' - peerDependenciesMeta: - vite: - optional: true - - vite@7.2.2: - resolution: {integrity: sha512-BxAKBWmIbrDgrokdGZH1IgkIk/5mMHDreLDmCJ0qpyJaAteP8NvMhkwr/ZCQNqNH97bw/dANTE9PDzqwJghfMQ==} - engines: {node: ^20.19.0 || >=22.12.0} - hasBin: true - peerDependencies: - '@types/node': ^20.19.0 || >=22.12.0 - jiti: '>=1.21.0' - less: ^4.0.0 - lightningcss: ^1.21.0 - sass: ^1.70.0 - sass-embedded: ^1.70.0 - stylus: '>=0.54.8' - sugarss: ^5.0.0 - terser: ^5.16.0 - tsx: ^4.8.1 - yaml: ^2.4.2 - peerDependenciesMeta: - '@types/node': - optional: true - jiti: - optional: true - less: - optional: true - lightningcss: - optional: true - sass: - optional: true - sass-embedded: - optional: true - stylus: - optional: true - sugarss: - optional: true - terser: - optional: true - tsx: - optional: true - yaml: - optional: true - - vitest@4.0.9: - resolution: {integrity: sha512-E0Ja2AX4th+CG33yAFRC+d1wFx2pzU5r6HtG6LiPSE04flaE0qB6YyjSw9ZcpJAtVPfsvZGtJlKWZpuW7EHRxg==} - engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} - hasBin: true - peerDependencies: - '@edge-runtime/vm': '*' - '@types/debug': ^4.1.12 - '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 - '@vitest/browser-playwright': 4.0.9 - '@vitest/browser-preview': 4.0.9 - '@vitest/browser-webdriverio': 4.0.9 - '@vitest/ui': 4.0.9 - happy-dom: '*' - jsdom: '*' - peerDependenciesMeta: - '@edge-runtime/vm': - optional: true - '@types/debug': - optional: true - '@types/node': - optional: true - '@vitest/browser-playwright': - optional: true - '@vitest/browser-preview': - optional: true - '@vitest/browser-webdriverio': - optional: true - '@vitest/ui': - optional: true - happy-dom: - optional: true - jsdom: - optional: true - - webidl-conversions@3.0.1: - resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} - - whatwg-url@5.0.0: - resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==} - - which-boxed-primitive@1.1.1: - resolution: {integrity: sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==} - engines: {node: '>= 0.4'} - - which-builtin-type@1.2.1: - resolution: {integrity: sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==} - engines: {node: '>= 0.4'} - - which-collection@1.0.2: - resolution: {integrity: sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==} - engines: {node: '>= 0.4'} - - which-typed-array@1.1.19: - resolution: {integrity: sha512-rEvr90Bck4WZt9HHFC4DJMsjvu7x+r6bImz0/BrbWb7A2djJ8hnZMrWnHo9F8ssv0OMErasDhftrfROTyqSDrw==} - engines: {node: '>= 0.4'} - - which@2.0.2: - resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} - engines: {node: '>= 8'} - hasBin: true - - why-is-node-running@2.3.0: - resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} - engines: {node: '>=8'} - hasBin: true - - word-wrap@1.2.5: - resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} - engines: {node: '>=0.10.0'} - - wrappy@1.0.2: - resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} - - ws@8.18.3: - resolution: {integrity: sha512-PEIGCY5tSlUt50cqyMXfCzX+oOPqN0vuGqWzbcJ2xvnkzkq46oOpz7dQaTDBdfICb4N14+GARUDw2XV2N4tvzg==} - engines: {node: '>=10.0.0'} - peerDependencies: - bufferutil: ^4.0.1 - utf-8-validate: '>=5.0.2' - peerDependenciesMeta: - bufferutil: - optional: true - utf-8-validate: - optional: true - - yocto-queue@0.1.0: - resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} - engines: {node: '>=10'} - - zod-to-json-schema@3.25.0: - resolution: {integrity: sha512-HvWtU2UG41LALjajJrML6uQejQhNJx+JBO9IflpSja4R03iNWfKXrj6W2h7ljuLyc1nKS+9yDyL/9tD1U/yBnQ==} - peerDependencies: - zod: ^3.25 || ^4 - - zod@3.25.76: - resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==} - -snapshots: - - '@babel/generator@7.28.5': - dependencies: - '@babel/parser': 7.28.5 - '@babel/types': 7.28.5 - '@jridgewell/gen-mapping': 0.3.13 - '@jridgewell/trace-mapping': 0.3.31 - jsesc: 3.1.0 - - '@babel/helper-string-parser@7.27.1': {} - - '@babel/helper-validator-identifier@7.28.5': {} - - '@babel/parser@7.28.5': - dependencies: - '@babel/types': 7.28.5 - - '@babel/runtime@7.28.4': {} - - '@babel/types@7.28.5': - dependencies: - '@babel/helper-string-parser': 7.27.1 - '@babel/helper-validator-identifier': 7.28.5 - - '@cfworker/json-schema@4.1.1': {} - - '@changesets/apply-release-plan@7.0.14': - dependencies: - '@changesets/config': 3.1.2 - '@changesets/get-version-range-type': 0.4.0 - '@changesets/git': 3.0.4 - '@changesets/should-skip-package': 0.1.2 - '@changesets/types': 6.1.0 - '@manypkg/get-packages': 1.1.3 - detect-indent: 6.1.0 - fs-extra: 7.0.1 - lodash.startcase: 4.4.0 - outdent: 0.5.0 - prettier: 2.8.8 - resolve-from: 5.0.0 - semver: 7.7.3 - - '@changesets/assemble-release-plan@6.0.9': - dependencies: - '@changesets/errors': 0.2.0 - '@changesets/get-dependents-graph': 2.1.3 - '@changesets/should-skip-package': 0.1.2 - '@changesets/types': 6.1.0 - '@manypkg/get-packages': 1.1.3 - semver: 7.7.3 - - '@changesets/changelog-git@0.2.1': - dependencies: - '@changesets/types': 6.1.0 - - '@changesets/changelog-github@0.5.2': - dependencies: - '@changesets/get-github-info': 0.7.0 - '@changesets/types': 6.1.0 - dotenv: 8.6.0 - transitivePeerDependencies: - - encoding - - '@changesets/cli@2.29.8(@types/node@24.10.3)': - dependencies: - '@changesets/apply-release-plan': 7.0.14 - '@changesets/assemble-release-plan': 6.0.9 - '@changesets/changelog-git': 0.2.1 - '@changesets/config': 3.1.2 - '@changesets/errors': 0.2.0 - '@changesets/get-dependents-graph': 2.1.3 - '@changesets/get-release-plan': 4.0.14 - '@changesets/git': 3.0.4 - '@changesets/logger': 0.1.1 - '@changesets/pre': 2.0.2 - '@changesets/read': 0.6.6 - '@changesets/should-skip-package': 0.1.2 - '@changesets/types': 6.1.0 - '@changesets/write': 0.4.0 - '@inquirer/external-editor': 1.0.3(@types/node@24.10.3) - '@manypkg/get-packages': 1.1.3 - ansi-colors: 4.1.3 - ci-info: 3.9.0 - enquirer: 2.4.1 - fs-extra: 7.0.1 - mri: 1.2.0 - p-limit: 2.3.0 - package-manager-detector: 0.2.11 - picocolors: 1.1.1 - resolve-from: 5.0.0 - semver: 7.7.3 - spawndamnit: 3.0.1 - term-size: 2.2.1 - transitivePeerDependencies: - - '@types/node' - - '@changesets/config@3.1.2': - dependencies: - '@changesets/errors': 0.2.0 - '@changesets/get-dependents-graph': 2.1.3 - '@changesets/logger': 0.1.1 - '@changesets/types': 6.1.0 - '@manypkg/get-packages': 1.1.3 - fs-extra: 7.0.1 - micromatch: 4.0.8 - - '@changesets/errors@0.2.0': - dependencies: - extendable-error: 0.1.7 - - '@changesets/get-dependents-graph@2.1.3': - dependencies: - '@changesets/types': 6.1.0 - '@manypkg/get-packages': 1.1.3 - picocolors: 1.1.1 - semver: 7.7.3 - - '@changesets/get-github-info@0.7.0': - dependencies: - dataloader: 1.4.0 - node-fetch: 2.7.0 - transitivePeerDependencies: - - encoding - - '@changesets/get-release-plan@4.0.14': - dependencies: - '@changesets/assemble-release-plan': 6.0.9 - '@changesets/config': 3.1.2 - '@changesets/pre': 2.0.2 - '@changesets/read': 0.6.6 - '@changesets/types': 6.1.0 - '@manypkg/get-packages': 1.1.3 - - '@changesets/get-version-range-type@0.4.0': {} - - '@changesets/git@3.0.4': - dependencies: - '@changesets/errors': 0.2.0 - '@manypkg/get-packages': 1.1.3 - is-subdir: 1.2.0 - micromatch: 4.0.8 - spawndamnit: 3.0.1 - - '@changesets/logger@0.1.1': - dependencies: - picocolors: 1.1.1 - - '@changesets/parse@0.4.2': - dependencies: - '@changesets/types': 6.1.0 - js-yaml: 4.1.1 - - '@changesets/pre@2.0.2': - dependencies: - '@changesets/errors': 0.2.0 - '@changesets/types': 6.1.0 - '@manypkg/get-packages': 1.1.3 - fs-extra: 7.0.1 - - '@changesets/read@0.6.6': - dependencies: - '@changesets/git': 3.0.4 - '@changesets/logger': 0.1.1 - '@changesets/parse': 0.4.2 - '@changesets/types': 6.1.0 - fs-extra: 7.0.1 - p-filter: 2.1.0 - picocolors: 1.1.1 - - '@changesets/should-skip-package@0.1.2': - dependencies: - '@changesets/types': 6.1.0 - '@manypkg/get-packages': 1.1.3 - - '@changesets/types@4.1.0': {} - - '@changesets/types@6.1.0': {} - - '@changesets/write@0.4.0': - dependencies: - '@changesets/types': 6.1.0 - fs-extra: 7.0.1 - human-id: 4.1.3 - prettier: 2.8.8 - - '@emnapi/core@1.7.1': - dependencies: - '@emnapi/wasi-threads': 1.1.0 - tslib: 2.8.1 - optional: true - - '@emnapi/runtime@1.7.1': - dependencies: - tslib: 2.8.1 - optional: true - - '@emnapi/wasi-threads@1.1.0': - dependencies: - tslib: 2.8.1 - optional: true - - '@esbuild/aix-ppc64@0.25.12': - optional: true - - '@esbuild/android-arm64@0.25.12': - optional: true - - '@esbuild/android-arm@0.25.12': - optional: true - - '@esbuild/android-x64@0.25.12': - optional: true - - '@esbuild/darwin-arm64@0.25.12': - optional: true - - '@esbuild/darwin-x64@0.25.12': - optional: true - - '@esbuild/freebsd-arm64@0.25.12': - optional: true - - '@esbuild/freebsd-x64@0.25.12': - optional: true - - '@esbuild/linux-arm64@0.25.12': - optional: true - - '@esbuild/linux-arm@0.25.12': - optional: true - - '@esbuild/linux-ia32@0.25.12': - optional: true - - '@esbuild/linux-loong64@0.25.12': - optional: true - - '@esbuild/linux-mips64el@0.25.12': - optional: true - - '@esbuild/linux-ppc64@0.25.12': - optional: true - - '@esbuild/linux-riscv64@0.25.12': - optional: true - - '@esbuild/linux-s390x@0.25.12': - optional: true - - '@esbuild/linux-x64@0.25.12': - optional: true - - '@esbuild/netbsd-arm64@0.25.12': - optional: true - - '@esbuild/netbsd-x64@0.25.12': - optional: true - - '@esbuild/openbsd-arm64@0.25.12': - optional: true - - '@esbuild/openbsd-x64@0.25.12': - optional: true - - '@esbuild/openharmony-arm64@0.25.12': - optional: true - - '@esbuild/sunos-x64@0.25.12': - optional: true - - '@esbuild/win32-arm64@0.25.12': - optional: true - - '@esbuild/win32-ia32@0.25.12': - optional: true - - '@esbuild/win32-x64@0.25.12': - optional: true - - '@eslint-community/eslint-utils@4.9.0(eslint@9.39.1)': - dependencies: - eslint: 9.39.1 - eslint-visitor-keys: 3.4.3 - - '@eslint-community/regexpp@4.12.2': {} - - '@eslint/config-array@0.21.1': - dependencies: - '@eslint/object-schema': 2.1.7 - debug: 4.4.3 - minimatch: 3.1.2 - transitivePeerDependencies: - - supports-color - - '@eslint/config-helpers@0.4.2': - dependencies: - '@eslint/core': 0.17.0 - - '@eslint/core@0.17.0': - dependencies: - '@types/json-schema': 7.0.15 - - '@eslint/eslintrc@3.3.1': - dependencies: - ajv: 6.12.6 - debug: 4.4.3 - espree: 10.4.0 - globals: 14.0.0 - ignore: 5.3.2 - import-fresh: 3.3.1 - js-yaml: 4.1.0 - minimatch: 3.1.2 - strip-json-comments: 3.1.1 - transitivePeerDependencies: - - supports-color - - '@eslint/js@9.39.1': {} - - '@eslint/object-schema@2.1.7': {} - - '@eslint/plugin-kit@0.4.1': - dependencies: - '@eslint/core': 0.17.0 - levn: 0.4.1 - - '@hono/node-server@1.19.7(hono@4.11.1)': - dependencies: - hono: 4.11.1 - - '@humanfs/core@0.19.1': {} - - '@humanfs/node@0.16.7': - dependencies: - '@humanfs/core': 0.19.1 - '@humanwhocodes/retry': 0.4.3 - - '@humanwhocodes/module-importer@1.0.1': {} - - '@humanwhocodes/retry@0.4.3': {} - - '@inquirer/external-editor@1.0.3(@types/node@24.10.3)': - dependencies: - chardet: 2.1.1 - iconv-lite: 0.7.0 - optionalDependencies: - '@types/node': 24.10.3 - - '@jridgewell/gen-mapping@0.3.13': - dependencies: - '@jridgewell/sourcemap-codec': 1.5.5 - '@jridgewell/trace-mapping': 0.3.31 - - '@jridgewell/resolve-uri@3.1.2': {} - - '@jridgewell/sourcemap-codec@1.5.5': {} - - '@jridgewell/trace-mapping@0.3.31': - dependencies: - '@jridgewell/resolve-uri': 3.1.2 - '@jridgewell/sourcemap-codec': 1.5.5 - - '@manypkg/find-root@1.1.0': - dependencies: - '@babel/runtime': 7.28.4 - '@types/node': 12.20.55 - find-up: 4.1.0 - fs-extra: 8.1.0 - - '@manypkg/get-packages@1.1.3': - dependencies: - '@babel/runtime': 7.28.4 - '@changesets/types': 4.1.0 - '@manypkg/find-root': 1.1.0 - fs-extra: 8.1.0 - globby: 11.1.0 - read-yaml-file: 1.1.0 - - '@napi-rs/wasm-runtime@0.2.12': - dependencies: - '@emnapi/core': 1.7.1 - '@emnapi/runtime': 1.7.1 - '@tybys/wasm-util': 0.10.1 - optional: true - - '@napi-rs/wasm-runtime@1.1.0': - dependencies: - '@emnapi/core': 1.7.1 - '@emnapi/runtime': 1.7.1 - '@tybys/wasm-util': 0.10.1 - optional: true - - '@noble/hashes@1.8.0': {} - - '@nodelib/fs.scandir@2.1.5': - dependencies: - '@nodelib/fs.stat': 2.0.5 - run-parallel: 1.2.0 - - '@nodelib/fs.stat@2.0.5': {} - - '@nodelib/fs.walk@1.2.8': - dependencies: - '@nodelib/fs.scandir': 2.1.5 - fastq: 1.19.1 - - '@oxc-project/types@0.101.0': {} - - '@paralleldrive/cuid2@2.3.1': - dependencies: - '@noble/hashes': 1.8.0 - - '@quansync/fs@1.0.0': - dependencies: - quansync: 1.0.0 - - '@rolldown/binding-android-arm64@1.0.0-beta.53': - optional: true - - '@rolldown/binding-darwin-arm64@1.0.0-beta.53': - optional: true - - '@rolldown/binding-darwin-x64@1.0.0-beta.53': - optional: true - - '@rolldown/binding-freebsd-x64@1.0.0-beta.53': - optional: true - - '@rolldown/binding-linux-arm-gnueabihf@1.0.0-beta.53': - optional: true - - '@rolldown/binding-linux-arm64-gnu@1.0.0-beta.53': - optional: true - - '@rolldown/binding-linux-arm64-musl@1.0.0-beta.53': - optional: true - - '@rolldown/binding-linux-x64-gnu@1.0.0-beta.53': - optional: true - - '@rolldown/binding-linux-x64-musl@1.0.0-beta.53': - optional: true - - '@rolldown/binding-openharmony-arm64@1.0.0-beta.53': - optional: true - - '@rolldown/binding-wasm32-wasi@1.0.0-beta.53': - dependencies: - '@napi-rs/wasm-runtime': 1.1.0 - optional: true - - '@rolldown/binding-win32-arm64-msvc@1.0.0-beta.53': - optional: true - - '@rolldown/binding-win32-x64-msvc@1.0.0-beta.53': - optional: true - - '@rolldown/pluginutils@1.0.0-beta.53': {} - - '@rollup/rollup-android-arm-eabi@4.53.2': - optional: true - - '@rollup/rollup-android-arm64@4.53.2': - optional: true - - '@rollup/rollup-darwin-arm64@4.53.2': - optional: true - - '@rollup/rollup-darwin-x64@4.53.2': - optional: true - - '@rollup/rollup-freebsd-arm64@4.53.2': - optional: true - - '@rollup/rollup-freebsd-x64@4.53.2': - optional: true - - '@rollup/rollup-linux-arm-gnueabihf@4.53.2': - optional: true - - '@rollup/rollup-linux-arm-musleabihf@4.53.2': - optional: true - - '@rollup/rollup-linux-arm64-gnu@4.53.2': - optional: true - - '@rollup/rollup-linux-arm64-musl@4.53.2': - optional: true - - '@rollup/rollup-linux-loong64-gnu@4.53.2': - optional: true - - '@rollup/rollup-linux-ppc64-gnu@4.53.2': - optional: true - - '@rollup/rollup-linux-riscv64-gnu@4.53.2': - optional: true - - '@rollup/rollup-linux-riscv64-musl@4.53.2': - optional: true - - '@rollup/rollup-linux-s390x-gnu@4.53.2': - optional: true - - '@rollup/rollup-linux-x64-gnu@4.53.2': - optional: true - - '@rollup/rollup-linux-x64-musl@4.53.2': - optional: true - - '@rollup/rollup-openharmony-arm64@4.53.2': - optional: true - - '@rollup/rollup-win32-arm64-msvc@4.53.2': - optional: true - - '@rollup/rollup-win32-ia32-msvc@4.53.2': - optional: true - - '@rollup/rollup-win32-x64-gnu@4.53.2': - optional: true - - '@rollup/rollup-win32-x64-msvc@4.53.2': - optional: true - - '@rtsao/scc@1.1.0': {} - - '@standard-schema/spec@1.0.0': {} - - '@tybys/wasm-util@0.10.1': - dependencies: - tslib: 2.8.1 - optional: true - - '@types/body-parser@1.19.6': - dependencies: - '@types/connect': 3.4.38 - '@types/node': 24.10.3 - - '@types/chai@5.2.3': - dependencies: - '@types/deep-eql': 4.0.2 - assertion-error: 2.0.1 - - '@types/connect@3.4.38': - dependencies: - '@types/node': 24.10.3 - - '@types/content-type@1.1.9': {} - - '@types/cookiejar@2.1.5': {} - - '@types/cors@2.8.19': - dependencies: - '@types/node': 24.10.3 - - '@types/cross-spawn@6.0.6': - dependencies: - '@types/node': 24.10.3 - - '@types/deep-eql@4.0.2': {} - - '@types/estree@1.0.8': {} - - '@types/eventsource@1.1.15': {} - - '@types/express-serve-static-core@5.1.0': - dependencies: - '@types/node': 24.10.3 - '@types/qs': 6.14.0 - '@types/range-parser': 1.2.7 - '@types/send': 1.2.1 - - '@types/express@5.0.5': - dependencies: - '@types/body-parser': 1.19.6 - '@types/express-serve-static-core': 5.1.0 - '@types/serve-static': 1.15.10 - - '@types/http-errors@2.0.5': {} - - '@types/json-schema@7.0.15': {} - - '@types/json5@0.0.29': {} - - '@types/methods@1.1.4': {} - - '@types/mime@1.3.5': {} - - '@types/node@12.20.55': {} - - '@types/node@24.10.3': - dependencies: - undici-types: 7.16.0 - - '@types/qs@6.14.0': {} - - '@types/range-parser@1.2.7': {} - - '@types/send@0.17.6': - dependencies: - '@types/mime': 1.3.5 - '@types/node': 24.10.3 - - '@types/send@1.2.1': - dependencies: - '@types/node': 24.10.3 - - '@types/serve-static@1.15.10': - dependencies: - '@types/http-errors': 2.0.5 - '@types/node': 24.10.3 - '@types/send': 0.17.6 - - '@types/superagent@8.1.9': - dependencies: - '@types/cookiejar': 2.1.5 - '@types/methods': 1.1.4 - '@types/node': 24.10.3 - form-data: 4.0.4 - - '@types/supertest@6.0.3': - dependencies: - '@types/methods': 1.1.4 - '@types/superagent': 8.1.9 - - '@types/ws@8.18.1': - dependencies: - '@types/node': 24.10.3 - - '@typescript-eslint/eslint-plugin@8.49.0(@typescript-eslint/parser@8.49.0(eslint@9.39.1)(typescript@5.9.3))(eslint@9.39.1)(typescript@5.9.3)': - dependencies: - '@eslint-community/regexpp': 4.12.2 - '@typescript-eslint/parser': 8.49.0(eslint@9.39.1)(typescript@5.9.3) - '@typescript-eslint/scope-manager': 8.49.0 - '@typescript-eslint/type-utils': 8.49.0(eslint@9.39.1)(typescript@5.9.3) - '@typescript-eslint/utils': 8.49.0(eslint@9.39.1)(typescript@5.9.3) - '@typescript-eslint/visitor-keys': 8.49.0 - eslint: 9.39.1 - ignore: 7.0.5 - natural-compare: 1.4.0 - ts-api-utils: 2.1.0(typescript@5.9.3) - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/parser@8.49.0(eslint@9.39.1)(typescript@5.9.3)': - dependencies: - '@typescript-eslint/scope-manager': 8.49.0 - '@typescript-eslint/types': 8.49.0 - '@typescript-eslint/typescript-estree': 8.49.0(typescript@5.9.3) - '@typescript-eslint/visitor-keys': 8.49.0 - debug: 4.4.3 - eslint: 9.39.1 - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/project-service@8.49.0(typescript@5.9.3)': - dependencies: - '@typescript-eslint/tsconfig-utils': 8.49.0(typescript@5.9.3) - '@typescript-eslint/types': 8.49.0 - debug: 4.4.3 - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/scope-manager@8.49.0': - dependencies: - '@typescript-eslint/types': 8.49.0 - '@typescript-eslint/visitor-keys': 8.49.0 - - '@typescript-eslint/tsconfig-utils@8.49.0(typescript@5.9.3)': - dependencies: - typescript: 5.9.3 - - '@typescript-eslint/type-utils@8.49.0(eslint@9.39.1)(typescript@5.9.3)': - dependencies: - '@typescript-eslint/types': 8.49.0 - '@typescript-eslint/typescript-estree': 8.49.0(typescript@5.9.3) - '@typescript-eslint/utils': 8.49.0(eslint@9.39.1)(typescript@5.9.3) - debug: 4.4.3 - eslint: 9.39.1 - ts-api-utils: 2.1.0(typescript@5.9.3) - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/types@8.49.0': {} - - '@typescript-eslint/typescript-estree@8.49.0(typescript@5.9.3)': - dependencies: - '@typescript-eslint/project-service': 8.49.0(typescript@5.9.3) - '@typescript-eslint/tsconfig-utils': 8.49.0(typescript@5.9.3) - '@typescript-eslint/types': 8.49.0 - '@typescript-eslint/visitor-keys': 8.49.0 - debug: 4.4.3 - minimatch: 9.0.5 - semver: 7.7.3 - tinyglobby: 0.2.15 - ts-api-utils: 2.1.0(typescript@5.9.3) - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/utils@8.49.0(eslint@9.39.1)(typescript@5.9.3)': - dependencies: - '@eslint-community/eslint-utils': 4.9.0(eslint@9.39.1) - '@typescript-eslint/scope-manager': 8.49.0 - '@typescript-eslint/types': 8.49.0 - '@typescript-eslint/typescript-estree': 8.49.0(typescript@5.9.3) - eslint: 9.39.1 - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - '@typescript-eslint/visitor-keys@8.49.0': - dependencies: - '@typescript-eslint/types': 8.49.0 - eslint-visitor-keys: 4.2.1 - - '@typescript/native-preview-darwin-arm64@7.0.0-dev.20251218.3': - optional: true - - '@typescript/native-preview-darwin-x64@7.0.0-dev.20251218.3': - optional: true - - '@typescript/native-preview-linux-arm64@7.0.0-dev.20251218.3': - optional: true - - '@typescript/native-preview-linux-arm@7.0.0-dev.20251218.3': - optional: true - - '@typescript/native-preview-linux-x64@7.0.0-dev.20251218.3': - optional: true - - '@typescript/native-preview-win32-arm64@7.0.0-dev.20251218.3': - optional: true - - '@typescript/native-preview-win32-x64@7.0.0-dev.20251218.3': - optional: true - - '@typescript/native-preview@7.0.0-dev.20251218.3': - optionalDependencies: - '@typescript/native-preview-darwin-arm64': 7.0.0-dev.20251218.3 - '@typescript/native-preview-darwin-x64': 7.0.0-dev.20251218.3 - '@typescript/native-preview-linux-arm': 7.0.0-dev.20251218.3 - '@typescript/native-preview-linux-arm64': 7.0.0-dev.20251218.3 - '@typescript/native-preview-linux-x64': 7.0.0-dev.20251218.3 - '@typescript/native-preview-win32-arm64': 7.0.0-dev.20251218.3 - '@typescript/native-preview-win32-x64': 7.0.0-dev.20251218.3 - - '@unrs/resolver-binding-android-arm-eabi@1.11.1': - optional: true - - '@unrs/resolver-binding-android-arm64@1.11.1': - optional: true - - '@unrs/resolver-binding-darwin-arm64@1.11.1': - optional: true - - '@unrs/resolver-binding-darwin-x64@1.11.1': - optional: true - - '@unrs/resolver-binding-freebsd-x64@1.11.1': - optional: true - - '@unrs/resolver-binding-linux-arm-gnueabihf@1.11.1': - optional: true - - '@unrs/resolver-binding-linux-arm-musleabihf@1.11.1': - optional: true - - '@unrs/resolver-binding-linux-arm64-gnu@1.11.1': - optional: true - - '@unrs/resolver-binding-linux-arm64-musl@1.11.1': - optional: true - - '@unrs/resolver-binding-linux-ppc64-gnu@1.11.1': - optional: true - - '@unrs/resolver-binding-linux-riscv64-gnu@1.11.1': - optional: true - - '@unrs/resolver-binding-linux-riscv64-musl@1.11.1': - optional: true - - '@unrs/resolver-binding-linux-s390x-gnu@1.11.1': - optional: true - - '@unrs/resolver-binding-linux-x64-gnu@1.11.1': - optional: true - - '@unrs/resolver-binding-linux-x64-musl@1.11.1': - optional: true - - '@unrs/resolver-binding-wasm32-wasi@1.11.1': - dependencies: - '@napi-rs/wasm-runtime': 0.2.12 - optional: true - - '@unrs/resolver-binding-win32-arm64-msvc@1.11.1': - optional: true - - '@unrs/resolver-binding-win32-ia32-msvc@1.11.1': - optional: true - - '@unrs/resolver-binding-win32-x64-msvc@1.11.1': - optional: true - - '@vitest/expect@4.0.9': - dependencies: - '@standard-schema/spec': 1.0.0 - '@types/chai': 5.2.3 - '@vitest/spy': 4.0.9 - '@vitest/utils': 4.0.9 - chai: 6.2.1 - tinyrainbow: 3.0.3 - - '@vitest/mocker@4.0.9(vite@7.2.2(@types/node@24.10.3)(tsx@4.20.6))': - dependencies: - '@vitest/spy': 4.0.9 - estree-walker: 3.0.3 - magic-string: 0.30.21 - optionalDependencies: - vite: 7.2.2(@types/node@24.10.3)(tsx@4.20.6) - - '@vitest/pretty-format@4.0.9': - dependencies: - tinyrainbow: 3.0.3 - - '@vitest/runner@4.0.9': - dependencies: - '@vitest/utils': 4.0.9 - pathe: 2.0.3 - - '@vitest/snapshot@4.0.9': - dependencies: - '@vitest/pretty-format': 4.0.9 - magic-string: 0.30.21 - pathe: 2.0.3 - - '@vitest/spy@4.0.9': {} - - '@vitest/utils@4.0.9': - dependencies: - '@vitest/pretty-format': 4.0.9 - tinyrainbow: 3.0.3 - - accepts@2.0.0: - dependencies: - mime-types: 3.0.1 - negotiator: 1.0.0 - - acorn-jsx@5.3.2(acorn@8.15.0): - dependencies: - acorn: 8.15.0 - - acorn@8.15.0: {} - - ajv-formats@3.0.1(ajv@8.17.1): - optionalDependencies: - ajv: 8.17.1 - - ajv@6.12.6: - dependencies: - fast-deep-equal: 3.1.3 - fast-json-stable-stringify: 2.1.0 - json-schema-traverse: 0.4.1 - uri-js: 4.4.1 - - ajv@8.17.1: - dependencies: - fast-deep-equal: 3.1.3 - fast-uri: 3.1.0 - json-schema-traverse: 1.0.0 - require-from-string: 2.0.2 - - ansi-colors@4.1.3: {} - - ansi-regex@5.0.1: {} - - ansi-styles@4.3.0: - dependencies: - color-convert: 2.0.1 - - ansis@4.2.0: {} - - argparse@1.0.10: - dependencies: - sprintf-js: 1.0.3 - - argparse@2.0.1: {} - - array-buffer-byte-length@1.0.2: - dependencies: - call-bound: 1.0.4 - is-array-buffer: 3.0.5 - - array-includes@3.1.9: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.4 - define-properties: 1.2.1 - es-abstract: 1.24.0 - es-object-atoms: 1.1.1 - get-intrinsic: 1.3.0 - is-string: 1.1.1 - math-intrinsics: 1.1.0 - - array-union@2.1.0: {} - - array.prototype.findlastindex@1.2.6: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.4 - define-properties: 1.2.1 - es-abstract: 1.24.0 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - es-shim-unscopables: 1.1.0 - - array.prototype.flat@1.3.3: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-abstract: 1.24.0 - es-shim-unscopables: 1.1.0 - - array.prototype.flatmap@1.3.3: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-abstract: 1.24.0 - es-shim-unscopables: 1.1.0 - - arraybuffer.prototype.slice@1.0.4: - dependencies: - array-buffer-byte-length: 1.0.2 - call-bind: 1.0.8 - define-properties: 1.2.1 - es-abstract: 1.24.0 - es-errors: 1.3.0 - get-intrinsic: 1.3.0 - is-array-buffer: 3.0.5 - - asap@2.0.6: {} - - assertion-error@2.0.1: {} - - ast-kit@2.2.0: - dependencies: - '@babel/parser': 7.28.5 - pathe: 2.0.3 - - async-function@1.0.0: {} - - asynckit@0.4.0: {} - - available-typed-arrays@1.0.7: - dependencies: - possible-typed-array-names: 1.1.0 - - balanced-match@1.0.2: {} - - better-path-resolve@1.0.0: - dependencies: - is-windows: 1.0.2 - - birpc@3.0.0: {} - - body-parser@2.2.0: - dependencies: - bytes: 3.1.2 - content-type: 1.0.5 - debug: 4.4.3 - http-errors: 2.0.0 - iconv-lite: 0.6.3 - on-finished: 2.4.1 - qs: 6.14.0 - raw-body: 3.0.1 - type-is: 2.0.1 - transitivePeerDependencies: - - supports-color - - brace-expansion@1.1.12: - dependencies: - balanced-match: 1.0.2 - concat-map: 0.0.1 - - brace-expansion@2.0.2: - dependencies: - balanced-match: 1.0.2 - - braces@3.0.3: - dependencies: - fill-range: 7.1.1 - - bytes@3.1.2: {} - - cac@6.7.14: {} - - call-bind-apply-helpers@1.0.2: - dependencies: - es-errors: 1.3.0 - function-bind: 1.1.2 - - call-bind@1.0.8: - dependencies: - call-bind-apply-helpers: 1.0.2 - es-define-property: 1.0.1 - get-intrinsic: 1.3.0 - set-function-length: 1.2.2 - - call-bound@1.0.4: - dependencies: - call-bind-apply-helpers: 1.0.2 - get-intrinsic: 1.3.0 - - callsites@3.1.0: {} - - chai@6.2.1: {} - - chalk@4.1.2: - dependencies: - ansi-styles: 4.3.0 - supports-color: 7.2.0 - - chardet@2.1.1: {} - - ci-info@3.9.0: {} - - color-convert@2.0.1: - dependencies: - color-name: 1.1.4 - - color-name@1.1.4: {} - - combined-stream@1.0.8: - dependencies: - delayed-stream: 1.0.0 - - component-emitter@1.3.1: {} - - concat-map@0.0.1: {} - - content-disposition@1.0.0: - dependencies: - safe-buffer: 5.2.1 - - content-type@1.0.5: {} - - cookie-signature@1.2.2: {} - - cookie@0.7.2: {} - - cookiejar@2.1.4: {} - - cors@2.8.5: - dependencies: - object-assign: 4.1.1 - vary: 1.1.2 - - cross-spawn@7.0.6: - dependencies: - path-key: 3.1.1 - shebang-command: 2.0.0 - which: 2.0.2 - - data-view-buffer@1.0.2: - dependencies: - call-bound: 1.0.4 - es-errors: 1.3.0 - is-data-view: 1.0.2 - - data-view-byte-length@1.0.2: - dependencies: - call-bound: 1.0.4 - es-errors: 1.3.0 - is-data-view: 1.0.2 - - data-view-byte-offset@1.0.1: - dependencies: - call-bound: 1.0.4 - es-errors: 1.3.0 - is-data-view: 1.0.2 - - dataloader@1.4.0: {} - - debug@3.2.7: - dependencies: - ms: 2.1.3 - - debug@4.4.3: - dependencies: - ms: 2.1.3 - - deep-is@0.1.4: {} - - define-data-property@1.1.4: - dependencies: - es-define-property: 1.0.1 - es-errors: 1.3.0 - gopd: 1.2.0 - - define-properties@1.2.1: - dependencies: - define-data-property: 1.1.4 - has-property-descriptors: 1.0.2 - object-keys: 1.1.1 - - defu@6.1.4: {} - - delayed-stream@1.0.0: {} - - depd@2.0.0: {} - - detect-indent@6.1.0: {} - - dezalgo@1.0.4: - dependencies: - asap: 2.0.6 - wrappy: 1.0.2 - - dir-glob@3.0.1: - dependencies: - path-type: 4.0.0 - - doctrine@2.1.0: - dependencies: - esutils: 2.0.3 - - dotenv@8.6.0: {} - - dts-resolver@2.1.3: {} - - dunder-proto@1.0.1: - dependencies: - call-bind-apply-helpers: 1.0.2 - es-errors: 1.3.0 - gopd: 1.2.0 - - ee-first@1.1.1: {} - - empathic@2.0.0: {} - - encodeurl@2.0.0: {} - - enhanced-resolve@5.18.3: - dependencies: - graceful-fs: 4.2.11 - tapable: 2.3.0 - - enquirer@2.4.1: - dependencies: - ansi-colors: 4.1.3 - strip-ansi: 6.0.1 - - es-abstract@1.24.0: - dependencies: - array-buffer-byte-length: 1.0.2 - arraybuffer.prototype.slice: 1.0.4 - available-typed-arrays: 1.0.7 - call-bind: 1.0.8 - call-bound: 1.0.4 - data-view-buffer: 1.0.2 - data-view-byte-length: 1.0.2 - data-view-byte-offset: 1.0.1 - es-define-property: 1.0.1 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - es-set-tostringtag: 2.1.0 - es-to-primitive: 1.3.0 - function.prototype.name: 1.1.8 - get-intrinsic: 1.3.0 - get-proto: 1.0.1 - get-symbol-description: 1.1.0 - globalthis: 1.0.4 - gopd: 1.2.0 - has-property-descriptors: 1.0.2 - has-proto: 1.2.0 - has-symbols: 1.1.0 - hasown: 2.0.2 - internal-slot: 1.1.0 - is-array-buffer: 3.0.5 - is-callable: 1.2.7 - is-data-view: 1.0.2 - is-negative-zero: 2.0.3 - is-regex: 1.2.1 - is-set: 2.0.3 - is-shared-array-buffer: 1.0.4 - is-string: 1.1.1 - is-typed-array: 1.1.15 - is-weakref: 1.1.1 - math-intrinsics: 1.1.0 - object-inspect: 1.13.4 - object-keys: 1.1.1 - object.assign: 4.1.7 - own-keys: 1.0.1 - regexp.prototype.flags: 1.5.4 - safe-array-concat: 1.1.3 - safe-push-apply: 1.0.0 - safe-regex-test: 1.1.0 - set-proto: 1.0.0 - stop-iteration-iterator: 1.1.0 - string.prototype.trim: 1.2.10 - string.prototype.trimend: 1.0.9 - string.prototype.trimstart: 1.0.8 - typed-array-buffer: 1.0.3 - typed-array-byte-length: 1.0.3 - typed-array-byte-offset: 1.0.4 - typed-array-length: 1.0.7 - unbox-primitive: 1.1.0 - which-typed-array: 1.1.19 - - es-define-property@1.0.1: {} - - es-errors@1.3.0: {} - - es-module-lexer@1.7.0: {} - - es-object-atoms@1.1.1: - dependencies: - es-errors: 1.3.0 - - es-set-tostringtag@2.1.0: - dependencies: - es-errors: 1.3.0 - get-intrinsic: 1.3.0 - has-tostringtag: 1.0.2 - hasown: 2.0.2 - - es-shim-unscopables@1.1.0: - dependencies: - hasown: 2.0.2 - - es-to-primitive@1.3.0: - dependencies: - is-callable: 1.2.7 - is-date-object: 1.1.0 - is-symbol: 1.1.1 - - esbuild@0.25.12: - optionalDependencies: - '@esbuild/aix-ppc64': 0.25.12 - '@esbuild/android-arm': 0.25.12 - '@esbuild/android-arm64': 0.25.12 - '@esbuild/android-x64': 0.25.12 - '@esbuild/darwin-arm64': 0.25.12 - '@esbuild/darwin-x64': 0.25.12 - '@esbuild/freebsd-arm64': 0.25.12 - '@esbuild/freebsd-x64': 0.25.12 - '@esbuild/linux-arm': 0.25.12 - '@esbuild/linux-arm64': 0.25.12 - '@esbuild/linux-ia32': 0.25.12 - '@esbuild/linux-loong64': 0.25.12 - '@esbuild/linux-mips64el': 0.25.12 - '@esbuild/linux-ppc64': 0.25.12 - '@esbuild/linux-riscv64': 0.25.12 - '@esbuild/linux-s390x': 0.25.12 - '@esbuild/linux-x64': 0.25.12 - '@esbuild/netbsd-arm64': 0.25.12 - '@esbuild/netbsd-x64': 0.25.12 - '@esbuild/openbsd-arm64': 0.25.12 - '@esbuild/openbsd-x64': 0.25.12 - '@esbuild/openharmony-arm64': 0.25.12 - '@esbuild/sunos-x64': 0.25.12 - '@esbuild/win32-arm64': 0.25.12 - '@esbuild/win32-ia32': 0.25.12 - '@esbuild/win32-x64': 0.25.12 - - escape-html@1.0.3: {} - - escape-string-regexp@4.0.0: {} - - eslint-compat-utils@0.5.1(eslint@9.39.1): - dependencies: - eslint: 9.39.1 - semver: 7.7.3 - - eslint-config-prettier@10.1.8(eslint@9.39.1): - dependencies: - eslint: 9.39.1 - - eslint-import-context@0.1.9(unrs-resolver@1.11.1): - dependencies: - get-tsconfig: 4.13.0 - stable-hash-x: 0.2.0 - optionalDependencies: - unrs-resolver: 1.11.1 - - eslint-import-resolver-node@0.3.9: - dependencies: - debug: 3.2.7 - is-core-module: 2.16.1 - resolve: 1.22.11 - transitivePeerDependencies: - - supports-color - - eslint-import-resolver-typescript@4.4.4(eslint-plugin-import@2.32.0)(eslint@9.39.1): - dependencies: - debug: 4.4.3 - eslint: 9.39.1 - eslint-import-context: 0.1.9(unrs-resolver@1.11.1) - get-tsconfig: 4.13.0 - is-bun-module: 2.0.0 - stable-hash-x: 0.2.0 - tinyglobby: 0.2.15 - unrs-resolver: 1.11.1 - optionalDependencies: - eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.49.0(eslint@9.39.1)(typescript@5.9.3))(eslint-import-resolver-typescript@4.4.4)(eslint@9.39.1) - transitivePeerDependencies: - - supports-color - - eslint-module-utils@2.12.1(@typescript-eslint/parser@8.49.0(eslint@9.39.1)(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@4.4.4)(eslint@9.39.1): - dependencies: - debug: 3.2.7 - optionalDependencies: - '@typescript-eslint/parser': 8.49.0(eslint@9.39.1)(typescript@5.9.3) - eslint: 9.39.1 - eslint-import-resolver-node: 0.3.9 - eslint-import-resolver-typescript: 4.4.4(eslint-plugin-import@2.32.0)(eslint@9.39.1) - transitivePeerDependencies: - - supports-color - - eslint-plugin-es-x@7.8.0(eslint@9.39.1): - dependencies: - '@eslint-community/eslint-utils': 4.9.0(eslint@9.39.1) - '@eslint-community/regexpp': 4.12.2 - eslint: 9.39.1 - eslint-compat-utils: 0.5.1(eslint@9.39.1) - - eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.49.0(eslint@9.39.1)(typescript@5.9.3))(eslint-import-resolver-typescript@4.4.4)(eslint@9.39.1): - dependencies: - '@rtsao/scc': 1.1.0 - array-includes: 3.1.9 - array.prototype.findlastindex: 1.2.6 - array.prototype.flat: 1.3.3 - array.prototype.flatmap: 1.3.3 - debug: 3.2.7 - doctrine: 2.1.0 - eslint: 9.39.1 - eslint-import-resolver-node: 0.3.9 - eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.49.0(eslint@9.39.1)(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@4.4.4)(eslint@9.39.1) - hasown: 2.0.2 - is-core-module: 2.16.1 - is-glob: 4.0.3 - minimatch: 3.1.2 - object.fromentries: 2.0.8 - object.groupby: 1.0.3 - object.values: 1.2.1 - semver: 6.3.1 - string.prototype.trimend: 1.0.9 - tsconfig-paths: 3.15.0 - optionalDependencies: - '@typescript-eslint/parser': 8.49.0(eslint@9.39.1)(typescript@5.9.3) - transitivePeerDependencies: - - eslint-import-resolver-typescript - - eslint-import-resolver-webpack - - supports-color - - eslint-plugin-n@17.23.1(eslint@9.39.1)(typescript@5.9.3): - dependencies: - '@eslint-community/eslint-utils': 4.9.0(eslint@9.39.1) - enhanced-resolve: 5.18.3 - eslint: 9.39.1 - eslint-plugin-es-x: 7.8.0(eslint@9.39.1) - get-tsconfig: 4.13.0 - globals: 15.15.0 - globrex: 0.1.2 - ignore: 5.3.2 - semver: 7.7.3 - ts-declaration-location: 1.0.7(typescript@5.9.3) - transitivePeerDependencies: - - typescript - - eslint-plugin-simple-import-sort@12.1.1(eslint@9.39.1): - dependencies: - eslint: 9.39.1 - - eslint-scope@8.4.0: - dependencies: - esrecurse: 4.3.0 - estraverse: 5.3.0 - - eslint-visitor-keys@3.4.3: {} - - eslint-visitor-keys@4.2.1: {} - - eslint@9.39.1: - dependencies: - '@eslint-community/eslint-utils': 4.9.0(eslint@9.39.1) - '@eslint-community/regexpp': 4.12.2 - '@eslint/config-array': 0.21.1 - '@eslint/config-helpers': 0.4.2 - '@eslint/core': 0.17.0 - '@eslint/eslintrc': 3.3.1 - '@eslint/js': 9.39.1 - '@eslint/plugin-kit': 0.4.1 - '@humanfs/node': 0.16.7 - '@humanwhocodes/module-importer': 1.0.1 - '@humanwhocodes/retry': 0.4.3 - '@types/estree': 1.0.8 - ajv: 6.12.6 - chalk: 4.1.2 - cross-spawn: 7.0.6 - debug: 4.4.3 - escape-string-regexp: 4.0.0 - eslint-scope: 8.4.0 - eslint-visitor-keys: 4.2.1 - espree: 10.4.0 - esquery: 1.6.0 - esutils: 2.0.3 - fast-deep-equal: 3.1.3 - file-entry-cache: 8.0.0 - find-up: 5.0.0 - glob-parent: 6.0.2 - ignore: 5.3.2 - imurmurhash: 0.1.4 - is-glob: 4.0.3 - json-stable-stringify-without-jsonify: 1.0.1 - lodash.merge: 4.6.2 - minimatch: 3.1.2 - natural-compare: 1.4.0 - optionator: 0.9.4 - transitivePeerDependencies: - - supports-color - - espree@10.4.0: - dependencies: - acorn: 8.15.0 - acorn-jsx: 5.3.2(acorn@8.15.0) - eslint-visitor-keys: 4.2.1 - - esprima@4.0.1: {} - - esquery@1.6.0: - dependencies: - estraverse: 5.3.0 - - esrecurse@4.3.0: - dependencies: - estraverse: 5.3.0 - - estraverse@5.3.0: {} - - estree-walker@3.0.3: - dependencies: - '@types/estree': 1.0.8 - - esutils@2.0.3: {} - - etag@1.8.1: {} - - eventsource-parser@3.0.6: {} - - eventsource@3.0.7: - dependencies: - eventsource-parser: 3.0.6 - - expect-type@1.2.2: {} - - express-rate-limit@7.5.1(express@5.1.0): - dependencies: - express: 5.1.0 - - express@5.1.0: - dependencies: - accepts: 2.0.0 - body-parser: 2.2.0 - content-disposition: 1.0.0 - content-type: 1.0.5 - cookie: 0.7.2 - cookie-signature: 1.2.2 - debug: 4.4.3 - encodeurl: 2.0.0 - escape-html: 1.0.3 - etag: 1.8.1 - finalhandler: 2.1.0 - fresh: 2.0.0 - http-errors: 2.0.0 - merge-descriptors: 2.0.0 - mime-types: 3.0.1 - on-finished: 2.4.1 - once: 1.4.0 - parseurl: 1.3.3 - proxy-addr: 2.0.7 - qs: 6.14.0 - range-parser: 1.2.1 - router: 2.2.0 - send: 1.2.0 - serve-static: 2.2.0 - statuses: 2.0.2 - type-is: 2.0.1 - vary: 1.1.2 - transitivePeerDependencies: - - supports-color - - extendable-error@0.1.7: {} - - fast-deep-equal@3.1.3: {} - - fast-glob@3.3.3: - dependencies: - '@nodelib/fs.stat': 2.0.5 - '@nodelib/fs.walk': 1.2.8 - glob-parent: 5.1.2 - merge2: 1.4.1 - micromatch: 4.0.8 - - fast-json-stable-stringify@2.1.0: {} - - fast-levenshtein@2.0.6: {} - - fast-safe-stringify@2.1.1: {} - - fast-uri@3.1.0: {} - - fastq@1.19.1: - dependencies: - reusify: 1.1.0 - - fdir@6.5.0(picomatch@4.0.3): - optionalDependencies: - picomatch: 4.0.3 - - file-entry-cache@8.0.0: - dependencies: - flat-cache: 4.0.1 - - fill-range@7.1.1: - dependencies: - to-regex-range: 5.0.1 - - finalhandler@2.1.0: - dependencies: - debug: 4.4.3 - encodeurl: 2.0.0 - escape-html: 1.0.3 - on-finished: 2.4.1 - parseurl: 1.3.3 - statuses: 2.0.2 - transitivePeerDependencies: - - supports-color - - find-up@4.1.0: - dependencies: - locate-path: 5.0.0 - path-exists: 4.0.0 - - find-up@5.0.0: - dependencies: - locate-path: 6.0.0 - path-exists: 4.0.0 - - flat-cache@4.0.1: - dependencies: - flatted: 3.3.3 - keyv: 4.5.4 - - flatted@3.3.3: {} - - for-each@0.3.5: - dependencies: - is-callable: 1.2.7 - - form-data@4.0.4: - dependencies: - asynckit: 0.4.0 - combined-stream: 1.0.8 - es-set-tostringtag: 2.1.0 - hasown: 2.0.2 - mime-types: 2.1.35 - - formidable@3.5.4: - dependencies: - '@paralleldrive/cuid2': 2.3.1 - dezalgo: 1.0.4 - once: 1.4.0 - - forwarded@0.2.0: {} - - fresh@2.0.0: {} - - fs-extra@7.0.1: - dependencies: - graceful-fs: 4.2.11 - jsonfile: 4.0.0 - universalify: 0.1.2 - - fs-extra@8.1.0: - dependencies: - graceful-fs: 4.2.11 - jsonfile: 4.0.0 - universalify: 0.1.2 - - fsevents@2.3.3: - optional: true - - function-bind@1.1.2: {} - - function.prototype.name@1.1.8: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.4 - define-properties: 1.2.1 - functions-have-names: 1.2.3 - hasown: 2.0.2 - is-callable: 1.2.7 - - functions-have-names@1.2.3: {} - - generator-function@2.0.1: {} - - get-intrinsic@1.3.0: - dependencies: - call-bind-apply-helpers: 1.0.2 - es-define-property: 1.0.1 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - function-bind: 1.1.2 - get-proto: 1.0.1 - gopd: 1.2.0 - has-symbols: 1.1.0 - hasown: 2.0.2 - math-intrinsics: 1.1.0 - - get-proto@1.0.1: - dependencies: - dunder-proto: 1.0.1 - es-object-atoms: 1.1.1 - - get-symbol-description@1.1.0: - dependencies: - call-bound: 1.0.4 - es-errors: 1.3.0 - get-intrinsic: 1.3.0 - - get-tsconfig@4.13.0: - dependencies: - resolve-pkg-maps: 1.0.0 - - glob-parent@5.1.2: - dependencies: - is-glob: 4.0.3 - - glob-parent@6.0.2: - dependencies: - is-glob: 4.0.3 - - globals@14.0.0: {} - - globals@15.15.0: {} - - globalthis@1.0.4: - dependencies: - define-properties: 1.2.1 - gopd: 1.2.0 - - globby@11.1.0: - dependencies: - array-union: 2.1.0 - dir-glob: 3.0.1 - fast-glob: 3.3.3 - ignore: 5.3.2 - merge2: 1.4.1 - slash: 3.0.0 - - globrex@0.1.2: {} - - gopd@1.2.0: {} - - graceful-fs@4.2.11: {} - - has-bigints@1.1.0: {} - - has-flag@4.0.0: {} - - has-property-descriptors@1.0.2: - dependencies: - es-define-property: 1.0.1 - - has-proto@1.2.0: - dependencies: - dunder-proto: 1.0.1 - - has-symbols@1.1.0: {} - - has-tostringtag@1.0.2: - dependencies: - has-symbols: 1.1.0 - - hasown@2.0.2: - dependencies: - function-bind: 1.1.2 - - hono@4.11.1: {} - - hookable@5.5.3: {} - - http-errors@2.0.0: - dependencies: - depd: 2.0.0 - inherits: 2.0.4 - setprototypeof: 1.2.0 - statuses: 2.0.1 - toidentifier: 1.0.1 - - human-id@4.1.3: {} - - iconv-lite@0.6.3: - dependencies: - safer-buffer: 2.1.2 - - iconv-lite@0.7.0: - dependencies: - safer-buffer: 2.1.2 - - ignore@5.3.2: {} - - ignore@7.0.5: {} - - import-fresh@3.3.1: - dependencies: - parent-module: 1.0.1 - resolve-from: 4.0.0 - - import-without-cache@0.2.3: {} - - imurmurhash@0.1.4: {} - - inherits@2.0.4: {} - - internal-slot@1.1.0: - dependencies: - es-errors: 1.3.0 - hasown: 2.0.2 - side-channel: 1.1.0 - - ipaddr.js@1.9.1: {} - - is-array-buffer@3.0.5: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.4 - get-intrinsic: 1.3.0 - - is-async-function@2.1.1: - dependencies: - async-function: 1.0.0 - call-bound: 1.0.4 - get-proto: 1.0.1 - has-tostringtag: 1.0.2 - safe-regex-test: 1.1.0 - - is-bigint@1.1.0: - dependencies: - has-bigints: 1.1.0 - - is-boolean-object@1.2.2: - dependencies: - call-bound: 1.0.4 - has-tostringtag: 1.0.2 - - is-bun-module@2.0.0: - dependencies: - semver: 7.7.3 - - is-callable@1.2.7: {} - - is-core-module@2.16.1: - dependencies: - hasown: 2.0.2 - - is-data-view@1.0.2: - dependencies: - call-bound: 1.0.4 - get-intrinsic: 1.3.0 - is-typed-array: 1.1.15 - - is-date-object@1.1.0: - dependencies: - call-bound: 1.0.4 - has-tostringtag: 1.0.2 - - is-extglob@2.1.1: {} - - is-finalizationregistry@1.1.1: - dependencies: - call-bound: 1.0.4 - - is-generator-function@1.1.2: - dependencies: - call-bound: 1.0.4 - generator-function: 2.0.1 - get-proto: 1.0.1 - has-tostringtag: 1.0.2 - safe-regex-test: 1.1.0 - - is-glob@4.0.3: - dependencies: - is-extglob: 2.1.1 - - is-map@2.0.3: {} - - is-negative-zero@2.0.3: {} - - is-number-object@1.1.1: - dependencies: - call-bound: 1.0.4 - has-tostringtag: 1.0.2 - - is-number@7.0.0: {} - - is-promise@4.0.0: {} - - is-regex@1.2.1: - dependencies: - call-bound: 1.0.4 - gopd: 1.2.0 - has-tostringtag: 1.0.2 - hasown: 2.0.2 - - is-set@2.0.3: {} - - is-shared-array-buffer@1.0.4: - dependencies: - call-bound: 1.0.4 - - is-string@1.1.1: - dependencies: - call-bound: 1.0.4 - has-tostringtag: 1.0.2 - - is-subdir@1.2.0: - dependencies: - better-path-resolve: 1.0.0 - - is-symbol@1.1.1: - dependencies: - call-bound: 1.0.4 - has-symbols: 1.1.0 - safe-regex-test: 1.1.0 - - is-typed-array@1.1.15: - dependencies: - which-typed-array: 1.1.19 - - is-weakmap@2.0.2: {} - - is-weakref@1.1.1: - dependencies: - call-bound: 1.0.4 - - is-weakset@2.0.4: - dependencies: - call-bound: 1.0.4 - get-intrinsic: 1.3.0 - - is-windows@1.0.2: {} - - isarray@2.0.5: {} - - isexe@2.0.0: {} - - jose@6.1.3: {} - - js-yaml@3.14.2: - dependencies: - argparse: 1.0.10 - esprima: 4.0.1 - - js-yaml@4.1.0: - dependencies: - argparse: 2.0.1 - - js-yaml@4.1.1: - dependencies: - argparse: 2.0.1 - - jsesc@3.1.0: {} - - json-buffer@3.0.1: {} - - json-schema-traverse@0.4.1: {} - - json-schema-traverse@1.0.0: {} - - json-schema-typed@8.0.2: {} - - json-stable-stringify-without-jsonify@1.0.1: {} - - json5@1.0.2: - dependencies: - minimist: 1.2.8 - - jsonfile@4.0.0: - optionalDependencies: - graceful-fs: 4.2.11 - - keyv@4.5.4: - dependencies: - json-buffer: 3.0.1 - - levn@0.4.1: - dependencies: - prelude-ls: 1.2.1 - type-check: 0.4.0 - - locate-path@5.0.0: - dependencies: - p-locate: 4.1.0 - - locate-path@6.0.0: - dependencies: - p-locate: 5.0.0 - - lodash.merge@4.6.2: {} - - lodash.startcase@4.4.0: {} - - magic-string@0.30.21: - dependencies: - '@jridgewell/sourcemap-codec': 1.5.5 - - math-intrinsics@1.1.0: {} - - media-typer@1.1.0: {} - - merge-descriptors@2.0.0: {} - - merge2@1.4.1: {} - - methods@1.1.2: {} - - micromatch@4.0.8: - dependencies: - braces: 3.0.3 - picomatch: 2.3.1 - - mime-db@1.52.0: {} - - mime-db@1.54.0: {} - - mime-types@2.1.35: - dependencies: - mime-db: 1.52.0 - - mime-types@3.0.1: - dependencies: - mime-db: 1.54.0 - - mime@2.6.0: {} - - minimatch@3.1.2: - dependencies: - brace-expansion: 1.1.12 - - minimatch@9.0.5: - dependencies: - brace-expansion: 2.0.2 - - minimist@1.2.8: {} - - mri@1.2.0: {} - - ms@2.1.3: {} - - nanoid@3.3.11: {} - - napi-postinstall@0.3.4: {} - - natural-compare@1.4.0: {} - - negotiator@1.0.0: {} - - node-fetch@2.7.0: - dependencies: - whatwg-url: 5.0.0 - - object-assign@4.1.1: {} - - object-inspect@1.13.4: {} - - object-keys@1.1.1: {} - - object.assign@4.1.7: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.4 - define-properties: 1.2.1 - es-object-atoms: 1.1.1 - has-symbols: 1.1.0 - object-keys: 1.1.1 - - object.fromentries@2.0.8: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-abstract: 1.24.0 - es-object-atoms: 1.1.1 - - object.groupby@1.0.3: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-abstract: 1.24.0 - - object.values@1.2.1: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.4 - define-properties: 1.2.1 - es-object-atoms: 1.1.1 - - obug@2.1.1: {} - - on-finished@2.4.1: - dependencies: - ee-first: 1.1.1 - - once@1.4.0: - dependencies: - wrappy: 1.0.2 - - optionator@0.9.4: - dependencies: - deep-is: 0.1.4 - fast-levenshtein: 2.0.6 - levn: 0.4.1 - prelude-ls: 1.2.1 - type-check: 0.4.0 - word-wrap: 1.2.5 - - outdent@0.5.0: {} - - own-keys@1.0.1: - dependencies: - get-intrinsic: 1.3.0 - object-keys: 1.1.1 - safe-push-apply: 1.0.0 - - p-filter@2.1.0: - dependencies: - p-map: 2.1.0 - - p-limit@2.3.0: - dependencies: - p-try: 2.2.0 - - p-limit@3.1.0: - dependencies: - yocto-queue: 0.1.0 - - p-locate@4.1.0: - dependencies: - p-limit: 2.3.0 - - p-locate@5.0.0: - dependencies: - p-limit: 3.1.0 - - p-map@2.1.0: {} - - p-try@2.2.0: {} - - package-manager-detector@0.2.11: - dependencies: - quansync: 0.2.11 - - parent-module@1.0.1: - dependencies: - callsites: 3.1.0 - - parseurl@1.3.3: {} - - path-exists@4.0.0: {} - - path-key@3.1.1: {} - - path-parse@1.0.7: {} - - path-to-regexp@8.3.0: {} - - path-type@4.0.0: {} - - pathe@2.0.3: {} - - picocolors@1.1.1: {} - - picomatch@2.3.1: {} - - picomatch@4.0.3: {} - - pify@4.0.1: {} - - pkce-challenge@5.0.0: {} - - possible-typed-array-names@1.1.0: {} - - postcss@8.5.6: - dependencies: - nanoid: 3.3.11 - picocolors: 1.1.1 - source-map-js: 1.2.1 - - prelude-ls@1.2.1: {} - - prettier@2.8.8: {} - - prettier@3.6.2: {} - - proxy-addr@2.0.7: - dependencies: - forwarded: 0.2.0 - ipaddr.js: 1.9.1 - - punycode@2.3.1: {} - - qs@6.14.0: - dependencies: - side-channel: 1.1.0 - - quansync@0.2.11: {} - - quansync@1.0.0: {} - - queue-microtask@1.2.3: {} - - range-parser@1.2.1: {} - - raw-body@3.0.1: - dependencies: - bytes: 3.1.2 - http-errors: 2.0.0 - iconv-lite: 0.7.0 - unpipe: 1.0.0 - - read-yaml-file@1.1.0: - dependencies: - graceful-fs: 4.2.11 - js-yaml: 3.14.2 - pify: 4.0.1 - strip-bom: 3.0.0 - - reflect.getprototypeof@1.0.10: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-abstract: 1.24.0 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - get-intrinsic: 1.3.0 - get-proto: 1.0.1 - which-builtin-type: 1.2.1 - - regexp.prototype.flags@1.5.4: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-errors: 1.3.0 - get-proto: 1.0.1 - gopd: 1.2.0 - set-function-name: 2.0.2 - - require-from-string@2.0.2: {} - - resolve-from@4.0.0: {} - - resolve-from@5.0.0: {} - - resolve-pkg-maps@1.0.0: {} - - resolve@1.22.11: - dependencies: - is-core-module: 2.16.1 - path-parse: 1.0.7 - supports-preserve-symlinks-flag: 1.0.0 - - reusify@1.1.0: {} - - rolldown-plugin-dts@0.18.3(@typescript/native-preview@7.0.0-dev.20251218.3)(rolldown@1.0.0-beta.53)(typescript@5.9.3): - dependencies: - '@babel/generator': 7.28.5 - '@babel/parser': 7.28.5 - '@babel/types': 7.28.5 - ast-kit: 2.2.0 - birpc: 3.0.0 - dts-resolver: 2.1.3 - get-tsconfig: 4.13.0 - magic-string: 0.30.21 - obug: 2.1.1 - rolldown: 1.0.0-beta.53 - optionalDependencies: - '@typescript/native-preview': 7.0.0-dev.20251218.3 - typescript: 5.9.3 - transitivePeerDependencies: - - oxc-resolver - - rolldown@1.0.0-beta.53: - dependencies: - '@oxc-project/types': 0.101.0 - '@rolldown/pluginutils': 1.0.0-beta.53 - optionalDependencies: - '@rolldown/binding-android-arm64': 1.0.0-beta.53 - '@rolldown/binding-darwin-arm64': 1.0.0-beta.53 - '@rolldown/binding-darwin-x64': 1.0.0-beta.53 - '@rolldown/binding-freebsd-x64': 1.0.0-beta.53 - '@rolldown/binding-linux-arm-gnueabihf': 1.0.0-beta.53 - '@rolldown/binding-linux-arm64-gnu': 1.0.0-beta.53 - '@rolldown/binding-linux-arm64-musl': 1.0.0-beta.53 - '@rolldown/binding-linux-x64-gnu': 1.0.0-beta.53 - '@rolldown/binding-linux-x64-musl': 1.0.0-beta.53 - '@rolldown/binding-openharmony-arm64': 1.0.0-beta.53 - '@rolldown/binding-wasm32-wasi': 1.0.0-beta.53 - '@rolldown/binding-win32-arm64-msvc': 1.0.0-beta.53 - '@rolldown/binding-win32-x64-msvc': 1.0.0-beta.53 - - rollup@4.53.2: - dependencies: - '@types/estree': 1.0.8 - optionalDependencies: - '@rollup/rollup-android-arm-eabi': 4.53.2 - '@rollup/rollup-android-arm64': 4.53.2 - '@rollup/rollup-darwin-arm64': 4.53.2 - '@rollup/rollup-darwin-x64': 4.53.2 - '@rollup/rollup-freebsd-arm64': 4.53.2 - '@rollup/rollup-freebsd-x64': 4.53.2 - '@rollup/rollup-linux-arm-gnueabihf': 4.53.2 - '@rollup/rollup-linux-arm-musleabihf': 4.53.2 - '@rollup/rollup-linux-arm64-gnu': 4.53.2 - '@rollup/rollup-linux-arm64-musl': 4.53.2 - '@rollup/rollup-linux-loong64-gnu': 4.53.2 - '@rollup/rollup-linux-ppc64-gnu': 4.53.2 - '@rollup/rollup-linux-riscv64-gnu': 4.53.2 - '@rollup/rollup-linux-riscv64-musl': 4.53.2 - '@rollup/rollup-linux-s390x-gnu': 4.53.2 - '@rollup/rollup-linux-x64-gnu': 4.53.2 - '@rollup/rollup-linux-x64-musl': 4.53.2 - '@rollup/rollup-openharmony-arm64': 4.53.2 - '@rollup/rollup-win32-arm64-msvc': 4.53.2 - '@rollup/rollup-win32-ia32-msvc': 4.53.2 - '@rollup/rollup-win32-x64-gnu': 4.53.2 - '@rollup/rollup-win32-x64-msvc': 4.53.2 - fsevents: 2.3.3 - - router@2.2.0: - dependencies: - debug: 4.4.3 - depd: 2.0.0 - is-promise: 4.0.0 - parseurl: 1.3.3 - path-to-regexp: 8.3.0 - transitivePeerDependencies: - - supports-color - - run-parallel@1.2.0: - dependencies: - queue-microtask: 1.2.3 - - safe-array-concat@1.1.3: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.4 - get-intrinsic: 1.3.0 - has-symbols: 1.1.0 - isarray: 2.0.5 - - safe-buffer@5.2.1: {} - - safe-push-apply@1.0.0: - dependencies: - es-errors: 1.3.0 - isarray: 2.0.5 - - safe-regex-test@1.1.0: - dependencies: - call-bound: 1.0.4 - es-errors: 1.3.0 - is-regex: 1.2.1 - - safer-buffer@2.1.2: {} - - semver@6.3.1: {} - - semver@7.7.3: {} - - send@1.2.0: - dependencies: - debug: 4.4.3 - encodeurl: 2.0.0 - escape-html: 1.0.3 - etag: 1.8.1 - fresh: 2.0.0 - http-errors: 2.0.0 - mime-types: 3.0.1 - ms: 2.1.3 - on-finished: 2.4.1 - range-parser: 1.2.1 - statuses: 2.0.2 - transitivePeerDependencies: - - supports-color - - serve-static@2.2.0: - dependencies: - encodeurl: 2.0.0 - escape-html: 1.0.3 - parseurl: 1.3.3 - send: 1.2.0 - transitivePeerDependencies: - - supports-color - - set-function-length@1.2.2: - dependencies: - define-data-property: 1.1.4 - es-errors: 1.3.0 - function-bind: 1.1.2 - get-intrinsic: 1.3.0 - gopd: 1.2.0 - has-property-descriptors: 1.0.2 - - set-function-name@2.0.2: - dependencies: - define-data-property: 1.1.4 - es-errors: 1.3.0 - functions-have-names: 1.2.3 - has-property-descriptors: 1.0.2 - - set-proto@1.0.0: - dependencies: - dunder-proto: 1.0.1 - es-errors: 1.3.0 - es-object-atoms: 1.1.1 - - setprototypeof@1.2.0: {} - - shebang-command@2.0.0: - dependencies: - shebang-regex: 3.0.0 - - shebang-regex@3.0.0: {} - - side-channel-list@1.0.0: - dependencies: - es-errors: 1.3.0 - object-inspect: 1.13.4 - - side-channel-map@1.0.1: - dependencies: - call-bound: 1.0.4 - es-errors: 1.3.0 - get-intrinsic: 1.3.0 - object-inspect: 1.13.4 - - side-channel-weakmap@1.0.2: - dependencies: - call-bound: 1.0.4 - es-errors: 1.3.0 - get-intrinsic: 1.3.0 - object-inspect: 1.13.4 - side-channel-map: 1.0.1 - - side-channel@1.1.0: - dependencies: - es-errors: 1.3.0 - object-inspect: 1.13.4 - side-channel-list: 1.0.0 - side-channel-map: 1.0.1 - side-channel-weakmap: 1.0.2 - - siginfo@2.0.0: {} - - signal-exit@4.1.0: {} - - slash@3.0.0: {} - - source-map-js@1.2.1: {} - - spawndamnit@3.0.1: - dependencies: - cross-spawn: 7.0.6 - signal-exit: 4.1.0 - - sprintf-js@1.0.3: {} - - stable-hash-x@0.2.0: {} - - stackback@0.0.2: {} - - statuses@2.0.1: {} - - statuses@2.0.2: {} - - std-env@3.10.0: {} - - stop-iteration-iterator@1.1.0: - dependencies: - es-errors: 1.3.0 - internal-slot: 1.1.0 - - string.prototype.trim@1.2.10: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.4 - define-data-property: 1.1.4 - define-properties: 1.2.1 - es-abstract: 1.24.0 - es-object-atoms: 1.1.1 - has-property-descriptors: 1.0.2 - - string.prototype.trimend@1.0.9: - dependencies: - call-bind: 1.0.8 - call-bound: 1.0.4 - define-properties: 1.2.1 - es-object-atoms: 1.1.1 - - string.prototype.trimstart@1.0.8: - dependencies: - call-bind: 1.0.8 - define-properties: 1.2.1 - es-object-atoms: 1.1.1 - - strip-ansi@6.0.1: - dependencies: - ansi-regex: 5.0.1 - - strip-bom@3.0.0: {} - - strip-json-comments@3.1.1: {} - - superagent@10.2.3: - dependencies: - component-emitter: 1.3.1 - cookiejar: 2.1.4 - debug: 4.4.3 - fast-safe-stringify: 2.1.1 - form-data: 4.0.4 - formidable: 3.5.4 - methods: 1.1.2 - mime: 2.6.0 - qs: 6.14.0 - transitivePeerDependencies: - - supports-color - - supertest@7.1.4: - dependencies: - methods: 1.1.2 - superagent: 10.2.3 - transitivePeerDependencies: - - supports-color - - supports-color@7.2.0: - dependencies: - has-flag: 4.0.0 - - supports-preserve-symlinks-flag@1.0.0: {} - - tapable@2.3.0: {} - - term-size@2.2.1: {} - - tinybench@2.9.0: {} - - tinyexec@0.3.2: {} - - tinyexec@1.0.2: {} - - tinyglobby@0.2.15: - dependencies: - fdir: 6.5.0(picomatch@4.0.3) - picomatch: 4.0.3 - - tinyrainbow@3.0.3: {} - - to-regex-range@5.0.1: - dependencies: - is-number: 7.0.0 - - toidentifier@1.0.1: {} - - tr46@0.0.3: {} - - tree-kill@1.2.2: {} - - ts-api-utils@2.1.0(typescript@5.9.3): - dependencies: - typescript: 5.9.3 - - ts-declaration-location@1.0.7(typescript@5.9.3): - dependencies: - picomatch: 4.0.3 - typescript: 5.9.3 - - tsconfck@3.1.6(typescript@5.9.3): - optionalDependencies: - typescript: 5.9.3 - - tsconfig-paths@3.15.0: - dependencies: - '@types/json5': 0.0.29 - json5: 1.0.2 - minimist: 1.2.8 - strip-bom: 3.0.0 - - tsdown@0.18.0(@typescript/native-preview@7.0.0-dev.20251218.3)(typescript@5.9.3): - dependencies: - ansis: 4.2.0 - cac: 6.7.14 - defu: 6.1.4 - empathic: 2.0.0 - hookable: 5.5.3 - import-without-cache: 0.2.3 - obug: 2.1.1 - rolldown: 1.0.0-beta.53 - rolldown-plugin-dts: 0.18.3(@typescript/native-preview@7.0.0-dev.20251218.3)(rolldown@1.0.0-beta.53)(typescript@5.9.3) - semver: 7.7.3 - tinyexec: 1.0.2 - tinyglobby: 0.2.15 - tree-kill: 1.2.2 - unconfig-core: 7.4.2 - unrun: 0.2.19 - optionalDependencies: - typescript: 5.9.3 - transitivePeerDependencies: - - '@ts-macro/tsc' - - '@typescript/native-preview' - - oxc-resolver - - synckit - - vue-tsc - - tslib@2.8.1: - optional: true - - tsx@4.20.6: - dependencies: - esbuild: 0.25.12 - get-tsconfig: 4.13.0 - optionalDependencies: - fsevents: 2.3.3 - - type-check@0.4.0: - dependencies: - prelude-ls: 1.2.1 - - type-is@2.0.1: - dependencies: - content-type: 1.0.5 - media-typer: 1.1.0 - mime-types: 3.0.1 - - typed-array-buffer@1.0.3: - dependencies: - call-bound: 1.0.4 - es-errors: 1.3.0 - is-typed-array: 1.1.15 - - typed-array-byte-length@1.0.3: - dependencies: - call-bind: 1.0.8 - for-each: 0.3.5 - gopd: 1.2.0 - has-proto: 1.2.0 - is-typed-array: 1.1.15 - - typed-array-byte-offset@1.0.4: - dependencies: - available-typed-arrays: 1.0.7 - call-bind: 1.0.8 - for-each: 0.3.5 - gopd: 1.2.0 - has-proto: 1.2.0 - is-typed-array: 1.1.15 - reflect.getprototypeof: 1.0.10 - - typed-array-length@1.0.7: - dependencies: - call-bind: 1.0.8 - for-each: 0.3.5 - gopd: 1.2.0 - is-typed-array: 1.1.15 - possible-typed-array-names: 1.1.0 - reflect.getprototypeof: 1.0.10 - - typescript-eslint@8.49.0(eslint@9.39.1)(typescript@5.9.3): - dependencies: - '@typescript-eslint/eslint-plugin': 8.49.0(@typescript-eslint/parser@8.49.0(eslint@9.39.1)(typescript@5.9.3))(eslint@9.39.1)(typescript@5.9.3) - '@typescript-eslint/parser': 8.49.0(eslint@9.39.1)(typescript@5.9.3) - '@typescript-eslint/typescript-estree': 8.49.0(typescript@5.9.3) - '@typescript-eslint/utils': 8.49.0(eslint@9.39.1)(typescript@5.9.3) - eslint: 9.39.1 - typescript: 5.9.3 - transitivePeerDependencies: - - supports-color - - typescript@5.9.3: {} - - unbox-primitive@1.1.0: - dependencies: - call-bound: 1.0.4 - has-bigints: 1.1.0 - has-symbols: 1.1.0 - which-boxed-primitive: 1.1.1 - - unconfig-core@7.4.2: - dependencies: - '@quansync/fs': 1.0.0 - quansync: 1.0.0 - - undici-types@7.16.0: {} - - universalify@0.1.2: {} - - unpipe@1.0.0: {} - - unrs-resolver@1.11.1: - dependencies: - napi-postinstall: 0.3.4 - optionalDependencies: - '@unrs/resolver-binding-android-arm-eabi': 1.11.1 - '@unrs/resolver-binding-android-arm64': 1.11.1 - '@unrs/resolver-binding-darwin-arm64': 1.11.1 - '@unrs/resolver-binding-darwin-x64': 1.11.1 - '@unrs/resolver-binding-freebsd-x64': 1.11.1 - '@unrs/resolver-binding-linux-arm-gnueabihf': 1.11.1 - '@unrs/resolver-binding-linux-arm-musleabihf': 1.11.1 - '@unrs/resolver-binding-linux-arm64-gnu': 1.11.1 - '@unrs/resolver-binding-linux-arm64-musl': 1.11.1 - '@unrs/resolver-binding-linux-ppc64-gnu': 1.11.1 - '@unrs/resolver-binding-linux-riscv64-gnu': 1.11.1 - '@unrs/resolver-binding-linux-riscv64-musl': 1.11.1 - '@unrs/resolver-binding-linux-s390x-gnu': 1.11.1 - '@unrs/resolver-binding-linux-x64-gnu': 1.11.1 - '@unrs/resolver-binding-linux-x64-musl': 1.11.1 - '@unrs/resolver-binding-wasm32-wasi': 1.11.1 - '@unrs/resolver-binding-win32-arm64-msvc': 1.11.1 - '@unrs/resolver-binding-win32-ia32-msvc': 1.11.1 - '@unrs/resolver-binding-win32-x64-msvc': 1.11.1 - - unrun@0.2.19: - dependencies: - rolldown: 1.0.0-beta.53 - - uri-js@4.4.1: - dependencies: - punycode: 2.3.1 - - vary@1.1.2: {} - - vite-tsconfig-paths@5.1.4(typescript@5.9.3)(vite@7.2.2(@types/node@24.10.3)(tsx@4.20.6)): - dependencies: - debug: 4.4.3 - globrex: 0.1.2 - tsconfck: 3.1.6(typescript@5.9.3) - optionalDependencies: - vite: 7.2.2(@types/node@24.10.3)(tsx@4.20.6) - transitivePeerDependencies: - - supports-color - - typescript - - vite@7.2.2(@types/node@24.10.3)(tsx@4.20.6): - dependencies: - esbuild: 0.25.12 - fdir: 6.5.0(picomatch@4.0.3) - picomatch: 4.0.3 - postcss: 8.5.6 - rollup: 4.53.2 - tinyglobby: 0.2.15 - optionalDependencies: - '@types/node': 24.10.3 - fsevents: 2.3.3 - tsx: 4.20.6 - - vitest@4.0.9(@types/node@24.10.3)(tsx@4.20.6): - dependencies: - '@vitest/expect': 4.0.9 - '@vitest/mocker': 4.0.9(vite@7.2.2(@types/node@24.10.3)(tsx@4.20.6)) - '@vitest/pretty-format': 4.0.9 - '@vitest/runner': 4.0.9 - '@vitest/snapshot': 4.0.9 - '@vitest/spy': 4.0.9 - '@vitest/utils': 4.0.9 - debug: 4.4.3 - es-module-lexer: 1.7.0 - expect-type: 1.2.2 - magic-string: 0.30.21 - pathe: 2.0.3 - picomatch: 4.0.3 - std-env: 3.10.0 - tinybench: 2.9.0 - tinyexec: 0.3.2 - tinyglobby: 0.2.15 - tinyrainbow: 3.0.3 - vite: 7.2.2(@types/node@24.10.3)(tsx@4.20.6) - why-is-node-running: 2.3.0 - optionalDependencies: - '@types/node': 24.10.3 - transitivePeerDependencies: - - jiti - - less - - lightningcss - - msw - - sass - - sass-embedded - - stylus - - sugarss - - supports-color - - terser - - tsx - - yaml - - webidl-conversions@3.0.1: {} - - whatwg-url@5.0.0: - dependencies: - tr46: 0.0.3 - webidl-conversions: 3.0.1 - - which-boxed-primitive@1.1.1: - dependencies: - is-bigint: 1.1.0 - is-boolean-object: 1.2.2 - is-number-object: 1.1.1 - is-string: 1.1.1 - is-symbol: 1.1.1 - - which-builtin-type@1.2.1: - dependencies: - call-bound: 1.0.4 - function.prototype.name: 1.1.8 - has-tostringtag: 1.0.2 - is-async-function: 2.1.1 - is-date-object: 1.1.0 - is-finalizationregistry: 1.1.1 - is-generator-function: 1.1.2 - is-regex: 1.2.1 - is-weakref: 1.1.1 - isarray: 2.0.5 - which-boxed-primitive: 1.1.1 - which-collection: 1.0.2 - which-typed-array: 1.1.19 - - which-collection@1.0.2: - dependencies: - is-map: 2.0.3 - is-set: 2.0.3 - is-weakmap: 2.0.2 - is-weakset: 2.0.4 - - which-typed-array@1.1.19: - dependencies: - available-typed-arrays: 1.0.7 - call-bind: 1.0.8 - call-bound: 1.0.4 - for-each: 0.3.5 - get-proto: 1.0.1 - gopd: 1.2.0 - has-tostringtag: 1.0.2 - - which@2.0.2: - dependencies: - isexe: 2.0.0 - - why-is-node-running@2.3.0: - dependencies: - siginfo: 2.0.0 - stackback: 0.0.2 - - word-wrap@1.2.5: {} - - wrappy@1.0.2: {} - - ws@8.18.3: {} - - yocto-queue@0.1.0: {} - - zod-to-json-schema@3.25.0(zod@3.25.76): - dependencies: - zod: 3.25.76 - - zod@3.25.76: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml deleted file mode 100644 index 12bae83261..0000000000 --- a/pnpm-workspace.yaml +++ /dev/null @@ -1,55 +0,0 @@ -packages: - - packages/**/* - - common/**/* - - examples/**/* - - test/**/* - -catalogs: - runtimeShared: - ajv: ^8.17.1 - ajv-formats: ^3.0.1 - json-schema-typed: ^8.0.2 - pkce-challenge: ^5.0.0 - zod: ^3.25 || ^4.0 - zod-to-json-schema: ^3.25.0 - '@cfworker/json-schema': ^4.1.1 - runtimeServerOnly: - '@hono/node-server': ^1.19.7 - hono: ^4.11.1 - content-type: ^1.0.5 - cors: ^2.8.5 - express: ^5.0.1 - express-rate-limit: ^7.5.0 - raw-body: ^3.0.0 - runtimeClientOnly: - jose: ^6.1.1 - cross-spawn: ^7.0.5 - eventsource: ^3.0.2 - eventsource-parser: ^3.0.0 - devTools: - typescript: ^5.9.3 - vitest: ^4.0.8 - eslint: ^9.8.0 - '@eslint/js': ^9.39.1 - eslint-config-prettier: ^10.1.8 - eslint-plugin-n: ^17.23.1 - prettier: 3.6.2 - tsx: ^4.16.5 - 'typescript-eslint': ^8.48.1 - supertest: ^7.0.0 - ws: ^8.18.0 - vite-tsconfig-paths: ^5.1.4 - '@types/content-type': ^1.1.8 - '@types/cors': ^2.8.17 - '@types/cross-spawn': ^6.0.6 - '@types/eventsource': ^1.1.15 - '@types/express': ^5.0.0 - '@types/express-serve-static-core': ^5.1.0 - '@types/supertest': ^6.0.2 - '@types/ws': ^8.5.12 - '@typescript/native-preview': ^7.0.0-dev.20251217.1 - tsdown: ^0.18.0 - -enableGlobalVirtualStore: false - -linkWorkspacePackages: deep diff --git a/scripts/fetch-spec-types.ts b/scripts/fetch-spec-types.ts index e88902d67a..a64e0848e9 100644 --- a/scripts/fetch-spec-types.ts +++ b/scripts/fetch-spec-types.ts @@ -64,7 +64,7 @@ async function main() { * Last updated from commit: {SHA} * * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. - * To update this file, run: pnpm run fetch:spec-types + * To update this file, run: npm run fetch:spec-types */`; const header = headerTemplate.replace('{SHA}', latestSHA); @@ -73,10 +73,10 @@ async function main() { const fullContent = header + specContent; // Write to file - const outputPath = join(PROJECT_ROOT, 'packages', 'core', 'src', 'types', 'spec.types.ts'); + const outputPath = join(PROJECT_ROOT, 'src', 'spec.types.ts'); writeFileSync(outputPath, fullContent, 'utf-8'); - console.log('Successfully updated packages/core/src/types/spec.types.ts'); + console.log('Successfully updated src/spec.types.ts'); } catch (error) { console.error('Error:', error instanceof Error ? error.message : String(error)); process.exit(1); diff --git a/test/integration/test/__fixtures__/serverThatHangs.ts b/src/__fixtures__/serverThatHangs.ts similarity index 90% rename from test/integration/test/__fixtures__/serverThatHangs.ts rename to src/__fixtures__/serverThatHangs.ts index 861c206873..82c244aa2d 100644 --- a/test/integration/test/__fixtures__/serverThatHangs.ts +++ b/src/__fixtures__/serverThatHangs.ts @@ -1,7 +1,7 @@ -import process from 'node:process'; import { setInterval } from 'node:timers'; - -import { McpServer, StdioServerTransport } from '@modelcontextprotocol/server'; +import process from 'node:process'; +import { McpServer } from '../server/mcp.js'; +import { StdioServerTransport } from '../server/stdio.js'; const transport = new StdioServerTransport(); diff --git a/test/integration/test/__fixtures__/testServer.ts b/src/__fixtures__/testServer.ts similarity index 74% rename from test/integration/test/__fixtures__/testServer.ts rename to src/__fixtures__/testServer.ts index 41ef07e46d..6401d0f837 100644 --- a/test/integration/test/__fixtures__/testServer.ts +++ b/src/__fixtures__/testServer.ts @@ -1,4 +1,5 @@ -import { McpServer, StdioServerTransport } from '@modelcontextprotocol/server'; +import { McpServer } from '../server/mcp.js'; +import { StdioServerTransport } from '../server/stdio.js'; const transport = new StdioServerTransport(); diff --git a/packages/server/test/server/__fixtures__/zodTestMatrix.ts b/src/__fixtures__/zodTestMatrix.ts similarity index 100% rename from packages/server/test/server/__fixtures__/zodTestMatrix.ts rename to src/__fixtures__/zodTestMatrix.ts diff --git a/src/__mocks__/pkce-challenge.ts b/src/__mocks__/pkce-challenge.ts new file mode 100644 index 0000000000..3dfec41f90 --- /dev/null +++ b/src/__mocks__/pkce-challenge.ts @@ -0,0 +1,6 @@ +export default function pkceChallenge() { + return { + code_verifier: 'test_verifier', + code_challenge: 'test_challenge' + }; +} diff --git a/packages/client/src/client/auth-extensions.ts b/src/client/auth-extensions.ts similarity index 98% rename from packages/client/src/client/auth-extensions.ts rename to src/client/auth-extensions.ts index 8dc444db67..f3908d2c22 100644 --- a/packages/client/src/client/auth-extensions.ts +++ b/src/client/auth-extensions.ts @@ -5,10 +5,9 @@ * for common machine-to-machine authentication scenarios. */ -import type { OAuthClientInformation, OAuthClientMetadata, OAuthTokens } from '@modelcontextprotocol/core'; -import type { CryptoKey, JWK } from 'jose'; - -import type { AddClientAuthentication, OAuthClientProvider } from './auth.js'; +import type { JWK } from 'jose'; +import { OAuthClientInformation, OAuthClientMetadata, OAuthTokens } from '../shared/auth.js'; +import { AddClientAuthentication, OAuthClientProvider } from './auth.js'; /** * Helper to produce a private_key_jwt client authentication function. diff --git a/packages/client/src/client/auth.ts b/src/client/auth.ts similarity index 98% rename from packages/client/src/client/auth.ts rename to src/client/auth.ts index 93048e4b36..4c82b51144 100644 --- a/packages/client/src/client/auth.ts +++ b/src/client/auth.ts @@ -1,33 +1,34 @@ -import type { - AuthorizationServerMetadata, - FetchLike, +import pkceChallenge from 'pkce-challenge'; +import { LATEST_PROTOCOL_VERSION } from '../types.js'; +import { + OAuthClientMetadata, OAuthClientInformation, - OAuthClientInformationFull, OAuthClientInformationMixed, - OAuthClientMetadata, + OAuthTokens, OAuthMetadata, + OAuthClientInformationFull, OAuthProtectedResourceMetadata, - OAuthTokens -} from '@modelcontextprotocol/core'; + OAuthErrorResponseSchema, + AuthorizationServerMetadata, + OpenIdProviderDiscoveryMetadataSchema +} from '../shared/auth.js'; +import { + OAuthClientInformationFullSchema, + OAuthMetadataSchema, + OAuthProtectedResourceMetadataSchema, + OAuthTokensSchema +} from '../shared/auth.js'; +import { checkResourceAllowed, resourceUrlFromServerUrl } from '../shared/auth-utils.js'; import { - checkResourceAllowed, InvalidClientError, InvalidClientMetadataError, InvalidGrantError, - LATEST_PROTOCOL_VERSION, OAUTH_ERRORS, - OAuthClientInformationFullSchema, OAuthError, - OAuthErrorResponseSchema, - OAuthMetadataSchema, - OAuthProtectedResourceMetadataSchema, - OAuthTokensSchema, - OpenIdProviderDiscoveryMetadataSchema, - resourceUrlFromServerUrl, ServerError, UnauthorizedClientError -} from '@modelcontextprotocol/core'; -import pkceChallenge from 'pkce-challenge'; +} from '../server/auth/errors.js'; +import { FetchLike } from '../shared/transport.js'; /** * Function type for adding client authentication to token requests. @@ -573,7 +574,7 @@ export function extractWWWAuthenticateParams(res: Response): { resourceMetadataU } const [type, scheme] = authenticateHeader.split(' '); - if (type?.toLowerCase() !== 'bearer' || !scheme) { + if (type.toLowerCase() !== 'bearer' || !scheme) { return {}; } @@ -616,10 +617,7 @@ function extractFieldFromWwwAuth(response: Response, fieldName: string): string if (match) { // Pattern matches: field_name="value" or field_name=value (unquoted) - const result = match[1] || match[2]; - if (result) { - return result; - } + return match[1] || match[2]; } return null; @@ -636,13 +634,13 @@ export function extractResourceMetadataUrl(res: Response): URL | undefined { } const [type, scheme] = authenticateHeader.split(' '); - if (type?.toLowerCase() !== 'bearer' || !scheme) { + if (type.toLowerCase() !== 'bearer' || !scheme) { return undefined; } const regex = /resource_metadata="([^"]*)"/; const match = regex.exec(authenticateHeader); - if (!match || !match[1]) { + if (!match) { return undefined; } diff --git a/packages/client/src/client/client.ts b/src/client/index.ts similarity index 95% rename from packages/client/src/client/client.ts rename to src/client/index.ts index 8d96ba0bca..eda412f672 100644 --- a/packages/client/src/client/client.ts +++ b/src/client/index.ts @@ -1,75 +1,69 @@ -import type { - AnyObjectSchema, - CallToolRequest, - ClientCapabilities, - ClientNotification, - ClientRequest, - ClientResult, - CompatibilityCallToolResultSchema, - CompleteRequest, - GetPromptRequest, - Implementation, - JsonSchemaType, - JsonSchemaValidator, - jsonSchemaValidator, - ListChangedHandlers, - ListChangedOptions, - ListPromptsRequest, - ListResourcesRequest, - ListResourceTemplatesRequest, - ListToolsRequest, - LoggingLevel, - Notification, - ProtocolOptions, - ReadResourceRequest, - Request, - RequestHandlerExtra, - RequestOptions, - Result, - SchemaOutput, - ServerCapabilities, - SubscribeRequest, - Tool, - Transport, - UnsubscribeRequest, - ZodV3Internal, - ZodV4Internal -} from '@modelcontextprotocol/core'; +import { mergeCapabilities, Protocol, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; +import type { Transport } from '../shared/transport.js'; + import { - AjvJsonSchemaValidator, - assertClientRequestTaskCapability, - assertToolsCallTaskCapability, + type CallToolRequest, CallToolResultSchema, + type ClientCapabilities, + type ClientNotification, + type ClientRequest, + type ClientResult, + type CompatibilityCallToolResultSchema, + type CompleteRequest, CompleteResultSchema, - CreateMessageRequestSchema, - CreateMessageResultSchema, - CreateTaskResultSchema, - ElicitRequestSchema, - ElicitResultSchema, EmptyResultSchema, ErrorCode, - getObjectShape, + type GetPromptRequest, GetPromptResultSchema, + type Implementation, InitializeResultSchema, - isZ4Schema, LATEST_PROTOCOL_VERSION, - ListChangedOptionsBaseSchema, + type ListPromptsRequest, ListPromptsResultSchema, + type ListResourcesRequest, ListResourcesResultSchema, + type ListResourceTemplatesRequest, ListResourceTemplatesResultSchema, + type ListToolsRequest, ListToolsResultSchema, + type LoggingLevel, McpError, - mergeCapabilities, - PromptListChangedNotificationSchema, - Protocol, + type Notification, + type ReadResourceRequest, ReadResourceResultSchema, + type Request, + type Result, + type ServerCapabilities, + SUPPORTED_PROTOCOL_VERSIONS, + type SubscribeRequest, + type Tool, + type UnsubscribeRequest, + ElicitResultSchema, + ElicitRequestSchema, + CreateTaskResultSchema, + CreateMessageRequestSchema, + CreateMessageResultSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, ResourceListChangedNotificationSchema, + ListChangedOptions, + ListChangedOptionsBaseSchema, + type ListChangedHandlers +} from '../types.js'; +import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; +import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from '../validation/types.js'; +import { + AnyObjectSchema, + SchemaOutput, + getObjectShape, + isZ4Schema, safeParse, - SUPPORTED_PROTOCOL_VERSIONS, - ToolListChangedNotificationSchema -} from '@modelcontextprotocol/core'; - + type ZodV3Internal, + type ZodV4Internal +} from '../server/zod-compat.js'; +import type { RequestHandlerExtra } from '../shared/protocol.js'; import { ExperimentalClientTasks } from '../experimental/tasks/client.js'; +import { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js'; /** * Elicitation default application helper. Applies defaults to the data based on the schema. @@ -85,7 +79,7 @@ function applyElicitationDefaults(schema: JsonSchemaType | undefined, data: unkn const obj = data as Record; const props = schema.properties as Record; for (const key of Object.keys(props)) { - const propSchema = props[key]!; + const propSchema = props[key]; // If missing or explicitly undefined, apply default if present if (obj[key] === undefined && Object.prototype.hasOwnProperty.call(propSchema, 'default')) { obj[key] = propSchema.default; @@ -374,14 +368,14 @@ export class Client< } const { params } = validatedRequest.data; - params.mode = params.mode ?? 'form'; + const mode = params.mode ?? 'form'; const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation); - if (params.mode === 'form' && !supportsFormMode) { + if (mode === 'form' && !supportsFormMode) { throw new McpError(ErrorCode.InvalidParams, 'Client does not support form-mode elicitation requests'); } - if (params.mode === 'url' && !supportsUrlMode) { + if (mode === 'url' && !supportsUrlMode) { throw new McpError(ErrorCode.InvalidParams, 'Client does not support URL-mode elicitation requests'); } @@ -410,9 +404,9 @@ export class Client< } const validatedResult = validationResult.data; - const requestedSchema = params.mode === 'form' ? (params.requestedSchema as JsonSchemaType) : undefined; + const requestedSchema = mode === 'form' ? (params.requestedSchema as JsonSchemaType) : undefined; - if (params.mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) { + if (mode === 'form' && validatedResult.action === 'accept' && validatedResult.content && requestedSchema) { if (this._capabilities.elicitation?.form?.applyDefaults) { try { applyElicitationDefaults(requestedSchema, validatedResult.content); diff --git a/packages/client/src/client/middleware.ts b/src/client/middleware.ts similarity index 98% rename from packages/client/src/client/middleware.ts rename to src/client/middleware.ts index 331a920e25..c8f7fdd3d4 100644 --- a/packages/client/src/client/middleware.ts +++ b/src/client/middleware.ts @@ -1,7 +1,5 @@ -import type { FetchLike } from '@modelcontextprotocol/core'; - -import type { OAuthClientProvider } from './auth.js'; -import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js'; +import { auth, extractWWWAuthenticateParams, OAuthClientProvider, UnauthorizedError } from './auth.js'; +import { FetchLike } from '../shared/transport.js'; /** * Middleware function that wraps and enhances fetch functionality. diff --git a/packages/client/src/client/sse.ts b/src/client/sse.ts similarity index 95% rename from packages/client/src/client/sse.ts rename to src/client/sse.ts index bff74986ea..f0e91ff258 100644 --- a/packages/client/src/client/sse.ts +++ b/src/client/sse.ts @@ -1,9 +1,7 @@ -import type { FetchLike, JSONRPCMessage, Transport } from '@modelcontextprotocol/core'; -import { createFetchWithInit, JSONRPCMessageSchema, normalizeHeaders } from '@modelcontextprotocol/core'; -import { type ErrorEvent, EventSource, type EventSourceInit } from 'eventsource'; - -import type { AuthResult, OAuthClientProvider } from './auth.js'; -import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js'; +import { EventSource, type ErrorEvent, type EventSourceInit } from 'eventsource'; +import { Transport, FetchLike, createFetchWithInit, normalizeHeaders } from '../shared/transport.js'; +import { JSONRPCMessage, JSONRPCMessageSchema } from '../types.js'; +import { auth, AuthResult, extractWWWAuthenticateParams, OAuthClientProvider, UnauthorizedError } from './auth.js'; export class SseError extends Error { constructor( @@ -116,7 +114,7 @@ export class SSEClientTransport implements Transport { } private async _commonHeaders(): Promise { - const headers: RequestInit['headers'] & Record = {}; + const headers: HeadersInit & Record = {}; if (this._authProvider) { const tokens = await this._authProvider.tokens(); if (tokens) { diff --git a/packages/client/src/client/stdio.ts b/src/client/stdio.ts similarity index 96% rename from packages/client/src/client/stdio.ts rename to src/client/stdio.ts index 56d773a7bd..e488dcd241 100644 --- a/packages/client/src/client/stdio.ts +++ b/src/client/stdio.ts @@ -1,11 +1,10 @@ -import type { ChildProcess, IOType } from 'node:child_process'; -import process from 'node:process'; -import type { Stream } from 'node:stream'; -import { PassThrough } from 'node:stream'; - -import type { JSONRPCMessage, Transport } from '@modelcontextprotocol/core'; -import { ReadBuffer, serializeMessage } from '@modelcontextprotocol/core'; +import { ChildProcess, IOType } from 'node:child_process'; import spawn from 'cross-spawn'; +import process from 'node:process'; +import { Stream, PassThrough } from 'node:stream'; +import { ReadBuffer, serializeMessage } from '../shared/stdio.js'; +import { Transport } from '../shared/transport.js'; +import { JSONRPCMessage } from '../types.js'; export type StdioServerParameters = { /** diff --git a/packages/client/src/client/streamableHttp.ts b/src/client/streamableHttp.ts similarity index 97% rename from packages/client/src/client/streamableHttp.ts rename to src/client/streamableHttp.ts index 91709a9a6a..6473ca48f5 100644 --- a/packages/client/src/client/streamableHttp.ts +++ b/src/client/streamableHttp.ts @@ -1,19 +1,8 @@ -import type { ReadableWritablePair } from 'node:stream/web'; - -import type { FetchLike, JSONRPCMessage, Transport } from '@modelcontextprotocol/core'; -import { - createFetchWithInit, - isInitializedNotification, - isJSONRPCRequest, - isJSONRPCResultResponse, - JSONRPCMessageSchema, - normalizeHeaders -} from '@modelcontextprotocol/core'; +import { Transport, FetchLike, createFetchWithInit, normalizeHeaders } from '../shared/transport.js'; +import { isInitializedNotification, isJSONRPCRequest, isJSONRPCResponse, JSONRPCMessage, JSONRPCMessageSchema } from '../types.js'; +import { auth, AuthResult, extractWWWAuthenticateParams, OAuthClientProvider, UnauthorizedError } from './auth.js'; import { EventSourceParserStream } from 'eventsource-parser/stream'; -import type { AuthResult, OAuthClientProvider } from './auth.js'; -import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js'; - // Default reconnection options for StreamableHTTP connections const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS: StreamableHTTPReconnectionOptions = { initialReconnectionDelay: 1000, @@ -191,7 +180,7 @@ export class StreamableHTTPClientTransport implements Transport { } private async _commonHeaders(): Promise { - const headers: RequestInit['headers'] & Record = {}; + const headers: HeadersInit & Record = {}; if (this._authProvider) { const tokens = await this._authProvider.tokens(); if (tokens) { @@ -361,7 +350,7 @@ export class StreamableHTTPClientTransport implements Transport { if (!event.event || event.event === 'message') { try { const message = JSONRPCMessageSchema.parse(JSON.parse(event.data)); - if (isJSONRPCResultResponse(message)) { + if (isJSONRPCResponse(message)) { // Mark that we received a response - no need to reconnect for this request receivedResponse = true; if (replayMessageId !== undefined) { diff --git a/packages/client/src/client/websocket.ts b/src/client/websocket.ts similarity index 93% rename from packages/client/src/client/websocket.ts rename to src/client/websocket.ts index cb0c34687c..aed766cafc 100644 --- a/packages/client/src/client/websocket.ts +++ b/src/client/websocket.ts @@ -1,5 +1,5 @@ -import type { JSONRPCMessage, Transport } from '@modelcontextprotocol/core'; -import { JSONRPCMessageSchema } from '@modelcontextprotocol/core'; +import { Transport } from '../shared/transport.js'; +import { JSONRPCMessage, JSONRPCMessageSchema } from '../types.js'; const SUBPROTOCOL = 'mcp'; diff --git a/src/examples/README.md b/src/examples/README.md new file mode 100644 index 0000000000..0d98456a6b --- /dev/null +++ b/src/examples/README.md @@ -0,0 +1,352 @@ +# MCP TypeScript SDK Examples + +This directory contains example implementations of MCP clients and servers using the TypeScript SDK. For a high-level index of scenarios and where they live, see the **Examples** table in the root `README.md`. + +## Table of Contents + +- [Client Implementations](#client-implementations) + - [Streamable HTTP Client](#streamable-http-client) + - [Backwards Compatible Client](#backwards-compatible-client) + - [URL Elicitation Example Client](#url-elicitation-example-client) +- [Server Implementations](#server-implementations) + - [Single Node Deployment](#single-node-deployment) + - [Streamable HTTP Transport](#streamable-http-transport) + - [Deprecated SSE Transport](#deprecated-sse-transport) + - [Backwards Compatible Server](#streamable-http-backwards-compatible-server-with-sse) + - [Form Elicitation Example](#form-elicitation-example) + - [URL Elicitation Example](#url-elicitation-example) + - [Multi-Node Deployment](#multi-node-deployment) +- [Backwards Compatibility](#testing-streamable-http-backwards-compatibility-with-sse) + +## Client Implementations + +### Streamable HTTP Client + +A full-featured interactive client that connects to a Streamable HTTP server, demonstrating how to: + +- Establish and manage a connection to an MCP server +- List and call tools with arguments +- Handle notifications through the SSE stream +- List and get prompts with arguments +- List available resources +- Handle session termination and reconnection +- Support for resumability with Last-Event-ID tracking + +```bash +npx tsx src/examples/client/simpleStreamableHttp.ts +``` + +Example client with OAuth: + +```bash +npx tsx src/examples/client/simpleOAuthClient.ts +``` + +Client credentials (machine-to-machine) example: + +```bash +npx tsx src/examples/client/simpleClientCredentials.ts +``` + +### Backwards Compatible Client + +A client that implements backwards compatibility according to the [MCP specification](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#backwards-compatibility), allowing it to work with both new and legacy servers. This client demonstrates: + +- The client first POSTs an initialize request to the server URL: + - If successful, it uses the Streamable HTTP transport + - If it fails with a 4xx status, it attempts a GET request to establish an SSE stream + +```bash +npx tsx src/examples/client/streamableHttpWithSseFallbackClient.ts +``` + +### URL Elicitation Example Client + +A client that demonstrates how to use URL elicitation to securely collect _sensitive_ user input or perform secure third-party flows. + +```bash +# First, run the server: +npx tsx src/examples/server/elicitationUrlExample.ts + +# Then, run the client: +npx tsx src/examples/client/elicitationUrlExample.ts + +``` + +## Server Implementations + +### Single Node Deployment + +These examples demonstrate how to set up an MCP server on a single node with different transport options. + +#### Streamable HTTP Transport + +##### Simple Streamable HTTP Server + +A server that implements the Streamable HTTP transport (protocol version 2025-03-26). + +- Basic server setup with Express and the Streamable HTTP transport +- Session management with an in-memory event store for resumability +- Tool implementation with the `greet` and `multi-greet` tools +- Prompt implementation with the `greeting-template` prompt +- Static resource exposure +- Support for notifications via SSE stream established by GET requests +- Session termination via DELETE requests + +```bash +npx tsx src/examples/server/simpleStreamableHttp.ts + +# To add a demo of authentication to this example, use: +npx tsx src/examples/server/simpleStreamableHttp.ts --oauth + +# To mitigate impersonation risks, enable strict Resource Identifier verification: +npx tsx src/examples/server/simpleStreamableHttp.ts --oauth --oauth-strict +``` + +##### JSON Response Mode Server + +A server that uses Streamable HTTP transport with JSON response mode enabled (no SSE). + +- Streamable HTTP with JSON response mode, which returns responses directly in the response body +- Limited support for notifications (since SSE is disabled) +- Proper response handling according to the MCP specification for servers that don't support SSE +- Returning appropriate HTTP status codes for unsupported methods + +```bash +npx tsx src/examples/server/jsonResponseStreamableHttp.ts +``` + +##### Streamable HTTP with server notifications + +A server that demonstrates server notifications using Streamable HTTP. + +- Resource list change notifications with dynamically added resources +- Automatic resource creation on a timed interval + +```bash +npx tsx src/examples/server/standaloneSseWithGetStreamableHttp.ts +``` + +##### Form Elicitation Example + +A server that demonstrates using form elicitation to collect _non-sensitive_ user input. + +```bash +npx tsx src/examples/server/elicitationFormExample.ts +``` + +##### URL Elicitation Example + +A comprehensive example demonstrating URL mode elicitation in a server protected by MCP authorization. This example shows: + +- SSE-driven URL elicitation of an API Key on session initialization: obtain sensitive user input at session init +- Tools that require direct user interaction via URL elicitation (for payment confirmation and for third-party OAuth tokens) +- Completion notifications for URL elicitation + +To run this example: + +```bash +# Start the server +npx tsx src/examples/server/elicitationUrlExample.ts + +# In a separate terminal, start the client +npx tsx src/examples/client/elicitationUrlExample.ts +``` + +#### Deprecated SSE Transport + +A server that implements the deprecated HTTP+SSE transport (protocol version 2024-11-05). This example only used for testing backwards compatibility for clients. + +- Two separate endpoints: `/mcp` for the SSE stream (GET) and `/messages` for client messages (POST) +- Tool implementation with a `start-notification-stream` tool that demonstrates sending periodic notifications + +```bash +npx tsx src/examples/server/simpleSseServer.ts +``` + +#### Streamable Http Backwards Compatible Server with SSE + +A server that supports both Streamable HTTP and SSE transports, adhering to the [MCP specification for backwards compatibility](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#backwards-compatibility). + +- Single MCP server instance with multiple transport options +- Support for Streamable HTTP requests at `/mcp` endpoint (GET/POST/DELETE) +- Support for deprecated SSE transport with `/sse` (GET) and `/messages` (POST) +- Session type tracking to avoid mixing transport types +- Notifications and tool execution across both transport types + +```bash +npx tsx src/examples/server/sseAndStreamableHttpCompatibleServer.ts +``` + +### Multi-Node Deployment + +When deploying MCP servers in a horizontally scaled environment (multiple server instances), there are a few different options that can be useful for different use cases: + +- **Stateless mode** - No need to maintain state between calls to MCP servers. Useful for simple API wrapper servers. +- **Persistent storage mode** - No local state needed, but session data is stored in a database. Example: an MCP server for online ordering where the shopping cart is stored in a database. +- **Local state with message routing** - Local state is needed, and all requests for a session must be routed to the correct node. This can be done with a message queue and pub/sub system. + +#### Stateless Mode + +The Streamable HTTP transport can be configured to operate without tracking sessions. This is perfect for simple API proxies or when each request is completely independent. + +##### Implementation + +To enable stateless mode, configure the `StreamableHTTPServerTransport` with: + +```typescript +sessionIdGenerator: undefined; +``` + +This disables session management entirely, and the server won't generate or expect session IDs. + +- No session ID headers are sent or expected +- Any server node can process any request +- No state is preserved between requests +- Perfect for RESTful or stateless API scenarios +- Simplest deployment model with minimal infrastructure requirements + +``` +┌─────────────────────────────────────────────┐ +│ Client │ +└─────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────┐ +│ Load Balancer │ +└─────────────────────────────────────────────┘ + │ │ + ▼ ▼ +┌─────────────────┐ ┌─────────────────────┐ +│ MCP Server #1 │ │ MCP Server #2 │ +│ (Node.js) │ │ (Node.js) │ +└─────────────────┘ └─────────────────────┘ +``` + +#### Persistent Storage Mode + +For cases where you need session continuity but don't need to maintain in-memory state on specific nodes, you can use a database to persist session data while still allowing any node to handle requests. + +##### Implementation + +Configure the transport with session management, but retrieve and store all state in an external persistent storage: + +```typescript +sessionIdGenerator: () => randomUUID(), +eventStore: databaseEventStore +``` + +All session state is stored in the database, and any node can serve any client by retrieving the state when needed. + +- Maintains sessions with unique IDs +- Stores all session data in an external database +- Provides resumability through the database-backed EventStore +- Any node can handle any request for the same session +- No node-specific memory state means no need for message routing +- Good for applications where state can be fully externalized +- Somewhat higher latency due to database access for each request + +``` +┌─────────────────────────────────────────────┐ +│ Client │ +└─────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────┐ +│ Load Balancer │ +└─────────────────────────────────────────────┘ + │ │ + ▼ ▼ +┌─────────────────┐ ┌─────────────────────┐ +│ MCP Server #1 │ │ MCP Server #2 │ +│ (Node.js) │ │ (Node.js) │ +└─────────────────┘ └─────────────────────┘ + │ │ + │ │ + ▼ ▼ +┌─────────────────────────────────────────────┐ +│ Database (PostgreSQL) │ +│ │ +│ • Session state │ +│ • Event storage for resumability │ +└─────────────────────────────────────────────┘ +``` + +#### Streamable HTTP with Distributed Message Routing + +For scenarios where local in-memory state must be maintained on specific nodes (such as Computer Use or complex session state), the Streamable HTTP transport can be combined with a pub/sub system to route messages to the correct node handling each session. + +1. **Bidirectional Message Queue Integration**: + - All nodes both publish to and subscribe from the message queue + - Each node registers the sessions it's actively handling + - Messages are routed based on session ownership + +2. **Request Handling Flow**: + - When a client connects to Node A with an existing `mcp-session-id` + - If Node A doesn't own this session, it: + - Establishes and maintains the SSE connection with the client + - Publishes the request to the message queue with the session ID + - Node B (which owns the session) receives the request from the queue + - Node B processes the request with its local session state + - Node B publishes responses/notifications back to the queue + - Node A subscribes to the response channel and forwards to the client + +3. **Channel Identification**: + - Each message channel combines both `mcp-session-id` and `stream-id` + - This ensures responses are correctly routed back to the originating connection + +``` +┌─────────────────────────────────────────────┐ +│ Client │ +└─────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────┐ +│ Load Balancer │ +└─────────────────────────────────────────────┘ + │ │ + ▼ ▼ +┌─────────────────┐ ┌─────────────────────┐ +│ MCP Server #1 │◄───►│ MCP Server #2 │ +│ (Has Session A) │ │ (Has Session B) │ +└─────────────────┘ └─────────────────────┘ + ▲│ ▲│ + │▼ │▼ +┌─────────────────────────────────────────────┐ +│ Message Queue / Pub-Sub │ +│ │ +│ • Session ownership registry │ +│ • Bidirectional message routing │ +│ • Request/response forwarding │ +└─────────────────────────────────────────────┘ +``` + +- Maintains session affinity for stateful operations without client redirection +- Enables horizontal scaling while preserving complex in-memory state +- Provides fault tolerance through the message queue as intermediary + +## Backwards Compatibility + +### Testing Streamable HTTP Backwards Compatibility with SSE + +To test the backwards compatibility features: + +1. Start one of the server implementations: + + ```bash + # Legacy SSE server (protocol version 2024-11-05) + npx tsx src/examples/server/simpleSseServer.ts + + # Streamable HTTP server (protocol version 2025-03-26) + npx tsx src/examples/server/simpleStreamableHttp.ts + + # Backwards compatible server (supports both protocols) + npx tsx src/examples/server/sseAndStreamableHttpCompatibleServer.ts + ``` + +2. Then run the backwards compatible client: + ```bash + npx tsx src/examples/client/streamableHttpWithSseFallbackClient.ts + ``` + +This demonstrates how the MCP ecosystem ensures interoperability between clients and servers regardless of which protocol version they were built for. diff --git a/examples/client/src/elicitationUrlExample.ts b/src/examples/client/elicitationUrlExample.ts similarity index 98% rename from examples/client/src/elicitationUrlExample.ts rename to src/examples/client/elicitationUrlExample.ts index 9b59c5b11a..b57927e3fc 100644 --- a/examples/client/src/elicitationUrlExample.ts +++ b/src/examples/client/elicitationUrlExample.ts @@ -1,38 +1,34 @@ -// Run with: pnpm tsx src/elicitationUrlExample.ts +// Run with: npx tsx src/examples/client/elicitationUrlExample.ts // // This example demonstrates how to use URL elicitation to securely // collect user input in a remote (HTTP) server. // URL elicitation allows servers to prompt the end-user to open a URL in their browser // to collect sensitive information. -import { exec } from 'node:child_process'; -import { createServer } from 'node:http'; +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; import { createInterface } from 'node:readline'; - -import type { - CallToolRequest, - ElicitRequest, - ElicitRequestURLParams, - ElicitResult, - ListToolsRequest, - OAuthClientMetadata, - ResourceLink -} from '@modelcontextprotocol/client'; import { + ListToolsRequest, + ListToolsResultSchema, + CallToolRequest, CallToolResultSchema, - Client, - ElicitationCompleteNotificationSchema, ElicitRequestSchema, - ErrorCode, - getDisplayName, - ListToolsResultSchema, + ElicitRequest, + ElicitResult, + ResourceLink, + ElicitRequestURLParams, McpError, - StreamableHTTPClientTransport, - UnauthorizedError, - UrlElicitationRequiredError -} from '@modelcontextprotocol/client'; - + ErrorCode, + UrlElicitationRequiredError, + ElicitationCompleteNotificationSchema +} from '../../types.js'; +import { getDisplayName } from '../../shared/metadataUtils.js'; +import { OAuthClientMetadata } from '../../shared/auth.js'; +import { exec } from 'node:child_process'; import { InMemoryOAuthClientProvider } from './simpleOAuthClientProvider.js'; +import { UnauthorizedError } from '../../client/auth.js'; +import { createServer } from 'node:http'; // Set up OAuth (required for this example) const OAUTH_CALLBACK_PORT = 8090; // Use different port than auth server (3001) @@ -175,7 +171,7 @@ async function commandLoop(): Promise { if (args.length < 2) { console.log('Usage: call-tool [args]'); } else { - const toolName = args[1]!; + const toolName = args[1]; let toolArgs = {}; if (args.length > 2) { try { diff --git a/examples/client/src/multipleClientsParallel.ts b/src/examples/client/multipleClientsParallel.ts similarity index 95% rename from examples/client/src/multipleClientsParallel.ts rename to src/examples/client/multipleClientsParallel.ts index 95c72212ba..492235cdd7 100644 --- a/examples/client/src/multipleClientsParallel.ts +++ b/src/examples/client/multipleClientsParallel.ts @@ -1,10 +1,6 @@ -import type { CallToolRequest, CallToolResult } from '@modelcontextprotocol/client'; -import { - CallToolResultSchema, - Client, - LoggingMessageNotificationSchema, - StreamableHTTPClientTransport -} from '@modelcontextprotocol/client'; +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { CallToolRequest, CallToolResultSchema, LoggingMessageNotificationSchema, CallToolResult } from '../../types.js'; /** * Multiple Clients MCP Example diff --git a/examples/client/src/parallelToolCallsClient.ts b/src/examples/client/parallelToolCallsClient.ts similarity index 97% rename from examples/client/src/parallelToolCallsClient.ts rename to src/examples/client/parallelToolCallsClient.ts index b692eba684..2ad249de71 100644 --- a/examples/client/src/parallelToolCallsClient.ts +++ b/src/examples/client/parallelToolCallsClient.ts @@ -1,11 +1,12 @@ -import type { CallToolResult, ListToolsRequest } from '@modelcontextprotocol/client'; +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; import { - CallToolResultSchema, - Client, + ListToolsRequest, ListToolsResultSchema, + CallToolResultSchema, LoggingMessageNotificationSchema, - StreamableHTTPClientTransport -} from '@modelcontextprotocol/client'; + CallToolResult +} from '../../types.js'; /** * Parallel Tool Calls MCP Client diff --git a/examples/client/src/simpleClientCredentials.ts b/src/examples/client/simpleClientCredentials.ts similarity index 89% rename from examples/client/src/simpleClientCredentials.ts rename to src/examples/client/simpleClientCredentials.ts index 141a72ab25..7defcc41f9 100644 --- a/examples/client/src/simpleClientCredentials.ts +++ b/src/examples/client/simpleClientCredentials.ts @@ -18,8 +18,10 @@ * MCP_SERVER_URL - Server URL (default: http://localhost:3000/mcp) */ -import type { OAuthClientProvider } from '@modelcontextprotocol/client'; -import { Client, ClientCredentialsProvider, PrivateKeyJwtProvider, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'; +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { ClientCredentialsProvider, PrivateKeyJwtProvider } from '../../client/auth-extensions.js'; +import { OAuthClientProvider } from '../../client/auth.js'; const DEFAULT_SERVER_URL = process.env.MCP_SERVER_URL || 'http://localhost:3000/mcp'; diff --git a/examples/client/src/simpleOAuthClient.ts b/src/examples/client/simpleOAuthClient.ts similarity index 97% rename from examples/client/src/simpleOAuthClient.ts rename to src/examples/client/simpleOAuthClient.ts index 514d81d94a..8071e61acc 100644 --- a/examples/client/src/simpleOAuthClient.ts +++ b/src/examples/client/simpleOAuthClient.ts @@ -1,19 +1,14 @@ #!/usr/bin/env node -import { exec } from 'node:child_process'; import { createServer } from 'node:http'; import { createInterface } from 'node:readline'; import { URL } from 'node:url'; - -import type { CallToolRequest, ListToolsRequest, OAuthClientMetadata } from '@modelcontextprotocol/client'; -import { - CallToolResultSchema, - Client, - ListToolsResultSchema, - StreamableHTTPClientTransport, - UnauthorizedError -} from '@modelcontextprotocol/client'; - +import { exec } from 'node:child_process'; +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { OAuthClientMetadata } from '../../shared/auth.js'; +import { CallToolRequest, ListToolsRequest, CallToolResultSchema, ListToolsResultSchema } from '../../types.js'; +import { UnauthorizedError } from '../../client/auth.js'; import { InMemoryOAuthClientProvider } from './simpleOAuthClientProvider.js'; // Configuration diff --git a/examples/client/src/simpleOAuthClientProvider.ts b/src/examples/client/simpleOAuthClientProvider.ts similarity index 91% rename from examples/client/src/simpleOAuthClientProvider.ts rename to src/examples/client/simpleOAuthClientProvider.ts index 96655c9f68..3f1932c3e5 100644 --- a/examples/client/src/simpleOAuthClientProvider.ts +++ b/src/examples/client/simpleOAuthClientProvider.ts @@ -1,4 +1,5 @@ -import type { OAuthClientInformationMixed, OAuthClientMetadata, OAuthClientProvider, OAuthTokens } from '@modelcontextprotocol/client'; +import { OAuthClientProvider } from '../../client/auth.js'; +import { OAuthClientInformationMixed, OAuthClientMetadata, OAuthTokens } from '../../shared/auth.js'; /** * In-memory OAuth client provider for demonstration purposes diff --git a/examples/client/src/simpleStreamableHttp.ts b/src/examples/client/simpleStreamableHttp.ts similarity index 98% rename from examples/client/src/simpleStreamableHttp.ts rename to src/examples/client/simpleStreamableHttp.ts index eaaa2cf50c..21ab4f5568 100644 --- a/examples/client/src/simpleStreamableHttp.ts +++ b/src/examples/client/simpleStreamableHttp.ts @@ -1,31 +1,28 @@ +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; import { createInterface } from 'node:readline'; - -import type { - CallToolRequest, - GetPromptRequest, - ListPromptsRequest, - ListResourcesRequest, - ListToolsRequest, - ReadResourceRequest, - ResourceLink -} from '@modelcontextprotocol/client'; import { + ListToolsRequest, + ListToolsResultSchema, + CallToolRequest, CallToolResultSchema, - Client, - ElicitRequestSchema, - ErrorCode, - getDisplayName, - GetPromptResultSchema, + ListPromptsRequest, ListPromptsResultSchema, + GetPromptRequest, + GetPromptResultSchema, + ListResourcesRequest, ListResourcesResultSchema, - ListToolsResultSchema, LoggingMessageNotificationSchema, - McpError, + ResourceListChangedNotificationSchema, + ElicitRequestSchema, + ResourceLink, + ReadResourceRequest, ReadResourceResultSchema, RELATED_TASK_META_KEY, - ResourceListChangedNotificationSchema, - StreamableHTTPClientTransport -} from '@modelcontextprotocol/client'; + ErrorCode, + McpError +} from '../../types.js'; +import { getDisplayName } from '../../shared/metadataUtils.js'; import { Ajv } from 'ajv'; // Create readline interface for user input @@ -109,7 +106,7 @@ function commandLoop(): void { if (args.length < 2) { console.log('Usage: call-tool [args]'); } else { - const toolName = args[1]!; + const toolName = args[1]; let toolArgs = {}; if (args.length > 2) { try { @@ -152,7 +149,7 @@ function commandLoop(): void { if (args.length < 2) { console.log('Usage: call-tool-task [args]'); } else { - const toolName = args[1]!; + const toolName = args[1]; let toolArgs = {}; if (args.length > 2) { try { @@ -173,7 +170,7 @@ function commandLoop(): void { if (args.length < 2) { console.log('Usage: get-prompt [args]'); } else { - const promptName = args[1]!; + const promptName = args[1]; let promptArgs = {}; if (args.length > 2) { try { @@ -194,7 +191,7 @@ function commandLoop(): void { if (args.length < 2) { console.log('Usage: read-resource '); } else { - await readResource(args[1]!); + await readResource(args[1]); } break; diff --git a/examples/client/src/simpleTaskInteractiveClient.ts b/src/examples/client/simpleTaskInteractiveClient.ts similarity index 95% rename from examples/client/src/simpleTaskInteractiveClient.ts rename to src/examples/client/simpleTaskInteractiveClient.ts index 882b2ccbf1..06ed0ead10 100644 --- a/examples/client/src/simpleTaskInteractiveClient.ts +++ b/src/examples/client/simpleTaskInteractiveClient.ts @@ -7,18 +7,19 @@ * - Using task-based tool execution with streaming */ +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; import { createInterface } from 'node:readline'; - -import type { CreateMessageRequest, CreateMessageResult, TextContent } from '@modelcontextprotocol/client'; import { CallToolResultSchema, - Client, - CreateMessageRequestSchema, + TextContent, ElicitRequestSchema, + CreateMessageRequestSchema, + CreateMessageRequest, + CreateMessageResult, ErrorCode, - McpError, - StreamableHTTPClientTransport -} from '@modelcontextprotocol/client'; + McpError +} from '../../types.js'; // Create readline interface for user input const readline = createInterface({ @@ -58,7 +59,7 @@ async function samplingCallback(params: CreateMessageRequest['params']): Promise // Get the prompt from the first message let prompt = 'unknown'; if (params.messages && params.messages.length > 0) { - const firstMessage = params.messages[0]!; + const firstMessage = params.messages[0]; const content = firstMessage.content; if (typeof content === 'object' && !Array.isArray(content) && content.type === 'text' && 'text' in content) { prompt = content.text; @@ -191,7 +192,7 @@ let url = 'http://localhost:8000/mcp'; for (let i = 0; i < args.length; i++) { if (args[i] === '--url' && args[i + 1]) { - url = args[i + 1]!; + url = args[i + 1]; i++; } } diff --git a/examples/client/src/ssePollingClient.ts b/src/examples/client/ssePollingClient.ts similarity index 92% rename from examples/client/src/ssePollingClient.ts rename to src/examples/client/ssePollingClient.ts index 60f322a3c2..ac7bba37d9 100644 --- a/examples/client/src/ssePollingClient.ts +++ b/src/examples/client/ssePollingClient.ts @@ -9,15 +9,12 @@ * - Event replay via Last-Event-ID header * - Resumption token tracking via onresumptiontoken callback * - * Run with: pnpm tsx src/ssePollingClient.ts + * Run with: npx tsx src/examples/client/ssePollingClient.ts * Requires: ssePollingExample.ts server running on port 3001 */ -import { - CallToolResultSchema, - Client, - LoggingMessageNotificationSchema, - StreamableHTTPClientTransport -} from '@modelcontextprotocol/client'; +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { CallToolResultSchema, LoggingMessageNotificationSchema } from '../../types.js'; const SERVER_URL = 'http://localhost:3001/mcp'; diff --git a/examples/client/src/streamableHttpWithSseFallbackClient.ts b/src/examples/client/streamableHttpWithSseFallbackClient.ts similarity index 95% rename from examples/client/src/streamableHttpWithSseFallbackClient.ts rename to src/examples/client/streamableHttpWithSseFallbackClient.ts index 6bc75b091e..657f48953e 100644 --- a/examples/client/src/streamableHttpWithSseFallbackClient.ts +++ b/src/examples/client/streamableHttpWithSseFallbackClient.ts @@ -1,12 +1,13 @@ -import type { CallToolRequest, ListToolsRequest } from '@modelcontextprotocol/client'; +import { Client } from '../../client/index.js'; +import { StreamableHTTPClientTransport } from '../../client/streamableHttp.js'; +import { SSEClientTransport } from '../../client/sse.js'; import { - CallToolResultSchema, - Client, + ListToolsRequest, ListToolsResultSchema, - LoggingMessageNotificationSchema, - SSEClientTransport, - StreamableHTTPClientTransport -} from '@modelcontextprotocol/client'; + CallToolRequest, + CallToolResultSchema, + LoggingMessageNotificationSchema +} from '../../types.js'; /** * Simplified Backwards Compatible MCP Client diff --git a/examples/server/src/README-simpleTaskInteractive.md b/src/examples/server/README-simpleTaskInteractive.md similarity index 79% rename from examples/server/src/README-simpleTaskInteractive.md rename to src/examples/server/README-simpleTaskInteractive.md index 5e9793d1a0..6e8cd345b9 100644 --- a/examples/server/src/README-simpleTaskInteractive.md +++ b/src/examples/server/README-simpleTaskInteractive.md @@ -44,21 +44,11 @@ The `TaskResultHandler` dequeues messages when the client calls `tasks/result` a ### Start the Server ```bash -# From anywhere in the SDK -pnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleTaskInteractive.ts +# From the SDK root directory +npx tsx src/examples/server/simpleTaskInteractive.ts # Or with a custom port -PORT=9000 pnpm --filter @modelcontextprotocol/examples-server exec tsx src/simpleTaskInteractive.ts -``` - -Or, from within the `examples/server` package: - -```bash -cd examples/server -pnpm tsx src/simpleTaskInteractive.ts - -# Or with a custom port -PORT=9000 pnpm tsx src/simpleTaskInteractive.ts +PORT=9000 npx tsx src/examples/server/simpleTaskInteractive.ts ``` The server will start on http://localhost:8000/mcp (or your custom port). @@ -66,21 +56,11 @@ The server will start on http://localhost:8000/mcp (or your custom port). ### Run the Client ```bash -# From anywhere in the SDK -pnpm --filter @modelcontextprotocol/examples-client exec tsx src/simpleTaskInteractiveClient.ts - -# Or connect to a different server -pnpm --filter @modelcontextprotocol/examples-client exec tsx src/simpleTaskInteractiveClient.ts --url http://localhost:9000/mcp -``` - -Or, from within the `examples/client` package: - -```bash -cd examples/client -pnpm tsx src/simpleTaskInteractiveClient.ts +# From the SDK root directory +npx tsx src/examples/client/simpleTaskInteractiveClient.ts # Or connect to a different server -pnpm tsx src/simpleTaskInteractiveClient.ts --url http://localhost:9000/mcp +npx tsx src/examples/client/simpleTaskInteractiveClient.ts --url http://localhost:9000/mcp ``` ## Expected Output @@ -176,6 +156,6 @@ This tells the server that the client can handle both form-based elicitation and ## Related Files -- `packages/core/src/experimental/tasks/interfaces.ts` - Core task interfaces (TaskStore, TaskMessageQueue) -- `packages/core/src/experimental/tasks/stores/in-memory.ts` - In-memory task store implementation -- `packages/core/src/types/types.ts` - Task-related types (Task, CreateTaskResult, GetTaskRequestSchema, etc.) +- `src/shared/task.ts` - Core task interfaces (TaskStore, TaskMessageQueue) +- `src/examples/shared/inMemoryTaskStore.ts` - In-memory implementations +- `src/types.ts` - Task-related types (Task, CreateTaskResult, GetTaskRequestSchema, etc.) diff --git a/examples/shared/src/demoInMemoryOAuthProvider.ts b/src/examples/server/demoInMemoryOAuthProvider.ts similarity index 93% rename from examples/shared/src/demoInMemoryOAuthProvider.ts rename to src/examples/server/demoInMemoryOAuthProvider.ts index bcf11dd0c6..1abc040ce0 100644 --- a/examples/shared/src/demoInMemoryOAuthProvider.ts +++ b/src/examples/server/demoInMemoryOAuthProvider.ts @@ -1,17 +1,12 @@ import { randomUUID } from 'node:crypto'; - -import type { - AuthInfo, - AuthorizationParams, - OAuthClientInformationFull, - OAuthMetadata, - OAuthRegisteredClientsStore, - OAuthServerProvider, - OAuthTokens -} from '@modelcontextprotocol/server'; -import { createOAuthMetadata, InvalidRequestError, mcpAuthRouter, resourceUrlFromServerUrl } from '@modelcontextprotocol/server'; -import type { Request, Response } from 'express'; -import express from 'express'; +import { AuthorizationParams, OAuthServerProvider } from '../../server/auth/provider.js'; +import { OAuthRegisteredClientsStore } from '../../server/auth/clients.js'; +import { OAuthClientInformationFull, OAuthMetadata, OAuthTokens } from '../../shared/auth.js'; +import express, { Request, Response } from 'express'; +import { AuthInfo } from '../../server/auth/types.js'; +import { createOAuthMetadata, mcpAuthRouter } from '../../server/auth/router.js'; +import { resourceUrlFromServerUrl } from '../../shared/auth-utils.js'; +import { InvalidRequestError } from '../../server/auth/errors.js'; export class DemoInMemoryClientsStore implements OAuthRegisteredClientsStore { private clients = new Map(); diff --git a/examples/server/src/elicitationFormExample.ts b/src/examples/server/elicitationFormExample.ts similarity index 97% rename from examples/server/src/elicitationFormExample.ts rename to src/examples/server/elicitationFormExample.ts index f8863c17bb..6c08009499 100644 --- a/examples/server/src/elicitationFormExample.ts +++ b/src/examples/server/elicitationFormExample.ts @@ -1,4 +1,4 @@ -// Run with: pnpm tsx src/elicitationFormExample.ts +// Run with: npx tsx src/examples/server/elicitationFormExample.ts // // This example demonstrates how to use form elicitation to collect structured user input // with JSON Schema validation via a local HTTP server with SSE streaming. @@ -8,9 +8,11 @@ // to collect *sensitive* user input via a browser. import { randomUUID } from 'node:crypto'; - -import { createMcpExpressApp, isInitializeRequest, McpServer, StreamableHTTPServerTransport } from '@modelcontextprotocol/server'; import { type Request, type Response } from 'express'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { isInitializeRequest } from '../../types.js'; +import { createMcpExpressApp } from '../../server/express.js'; // Create MCP server - it will automatically use AjvJsonSchemaValidator with sensible defaults // The validator supports format validation (email, date, etc.) if ajv-formats is installed @@ -452,7 +454,7 @@ async function main() { for (const sessionId in transports) { try { console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId]!.close(); + await transports[sessionId].close(); delete transports[sessionId]; } catch (error) { console.error(`Error closing transport for session ${sessionId}:`, error); diff --git a/examples/server/src/elicitationUrlExample.ts b/src/examples/server/elicitationUrlExample.ts similarity index 96% rename from examples/server/src/elicitationUrlExample.ts rename to src/examples/server/elicitationUrlExample.ts index 99f85d0795..5ddecc4e14 100644 --- a/examples/server/src/elicitationUrlExample.ts +++ b/src/examples/server/elicitationUrlExample.ts @@ -1,4 +1,4 @@ -// Run with: pnpm tsx src/elicitationUrlExample.ts +// Run with: npx tsx src/examples/server/elicitationUrlExample.ts // // This example demonstrates how to use URL elicitation to securely collect // *sensitive* user input in a remote (HTTP) server. @@ -7,27 +7,21 @@ // Note: See also elicitationFormExample.ts for an example of using form (not URL) elicitation // to collect *non-sensitive* user input with a structured schema. +import express, { Request, Response } from 'express'; import { randomUUID } from 'node:crypto'; - -import { setupAuthServer } from '@modelcontextprotocol/examples-shared'; -import type { CallToolResult, ElicitRequestURLParams, ElicitResult, OAuthMetadata } from '@modelcontextprotocol/server'; -import { - checkResourceAllowed, - createMcpExpressApp, - getOAuthProtectedResourceMetadataUrl, - isInitializeRequest, - mcpAuthMetadataRouter, - McpServer, - requireBearerAuth, - StreamableHTTPServerTransport, - UrlElicitationRequiredError -} from '@modelcontextprotocol/server'; -import cors from 'cors'; -import type { Request, Response } from 'express'; -import express from 'express'; import { z } from 'zod'; +import { McpServer } from '../../server/mcp.js'; +import { createMcpExpressApp } from '../../server/express.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { getOAuthProtectedResourceMetadataUrl, mcpAuthMetadataRouter } from '../../server/auth/router.js'; +import { requireBearerAuth } from '../../server/auth/middleware/bearerAuth.js'; +import { CallToolResult, UrlElicitationRequiredError, ElicitRequestURLParams, ElicitResult, isInitializeRequest } from '../../types.js'; +import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; +import { setupAuthServer } from './demoInMemoryOAuthProvider.js'; +import { OAuthMetadata } from '../../shared/auth.js'; +import { checkResourceAllowed } from '../../shared/auth-utils.js'; -import { InMemoryEventStore } from './inMemoryEventStore.js'; +import cors from 'cors'; // Create an MCP server with implementation details const getServer = () => { @@ -263,7 +257,7 @@ const tokenVerifier = { throw new Error(`Invalid or expired token: ${text}`); } - const data = (await response.json()) as { aud: string; client_id: string; scope: string; exp: number }; + const data = await response.json(); if (!data.aud) { throw new Error(`Resource Indicator (RFC8707) missing`); @@ -765,7 +759,7 @@ process.on('SIGINT', async () => { for (const sessionId in transports) { try { console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId]!.close(); + await transports[sessionId].close(); delete transports[sessionId]; delete sessionsNeedingElicitation[sessionId]; } catch (error) { diff --git a/examples/server/src/jsonResponseStreamableHttp.ts b/src/examples/server/jsonResponseStreamableHttp.ts similarity index 89% rename from examples/server/src/jsonResponseStreamableHttp.ts rename to src/examples/server/jsonResponseStreamableHttp.ts index 2199ebfbea..224955c460 100644 --- a/examples/server/src/jsonResponseStreamableHttp.ts +++ b/src/examples/server/jsonResponseStreamableHttp.ts @@ -1,9 +1,10 @@ +import { Request, Response } from 'express'; import { randomUUID } from 'node:crypto'; - -import type { CallToolResult } from '@modelcontextprotocol/server'; -import { createMcpExpressApp, isInitializeRequest, McpServer, StreamableHTTPServerTransport } from '@modelcontextprotocol/server'; -import type { Request, Response } from 'express'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; import * as z from 'zod/v4'; +import { CallToolResult, isInitializeRequest } from '../../types.js'; +import { createMcpExpressApp } from '../../server/express.js'; // Create an MCP server with implementation details const getServer = () => { @@ -20,13 +21,11 @@ const getServer = () => { ); // Register a simple tool that returns a greeting - server.registerTool( + server.tool( 'greet', + 'A simple greeting tool', { - description: 'A simple greeting tool', - inputSchema: { - name: z.string().describe('Name to greet') - } + name: z.string().describe('Name to greet') }, async ({ name }): Promise => { return { @@ -41,13 +40,11 @@ const getServer = () => { ); // Register a tool that sends multiple greetings with notifications - server.registerTool( + server.tool( 'multi-greet', + 'A tool that sends different greetings with delays between them', { - description: 'A tool that sends different greetings with delays between them', - inputSchema: { - name: z.string().describe('Name to greet') - } + name: z.string().describe('Name to greet') }, async ({ name }, extra): Promise => { const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); diff --git a/examples/server/src/mcpServerOutputSchema.ts b/src/examples/server/mcpServerOutputSchema.ts similarity index 95% rename from examples/server/src/mcpServerOutputSchema.ts rename to src/examples/server/mcpServerOutputSchema.ts index 52fa766678..7ef9f6227a 100644 --- a/examples/server/src/mcpServerOutputSchema.ts +++ b/src/examples/server/mcpServerOutputSchema.ts @@ -4,7 +4,8 @@ * This demonstrates how to easily create tools with structured output */ -import { McpServer, StdioServerTransport } from '@modelcontextprotocol/server'; +import { McpServer } from '../../server/mcp.js'; +import { StdioServerTransport } from '../../server/stdio.js'; import * as z from 'zod/v4'; const server = new McpServer({ diff --git a/examples/server/src/simpleSseServer.ts b/src/examples/server/simpleSseServer.ts similarity index 89% rename from examples/server/src/simpleSseServer.ts rename to src/examples/server/simpleSseServer.ts index 90561c62f5..1cd10cd2da 100644 --- a/examples/server/src/simpleSseServer.ts +++ b/src/examples/server/simpleSseServer.ts @@ -1,7 +1,9 @@ -import type { CallToolResult } from '@modelcontextprotocol/server'; -import { createMcpExpressApp, McpServer, SSEServerTransport } from '@modelcontextprotocol/server'; -import type { Request, Response } from 'express'; +import { Request, Response } from 'express'; +import { McpServer } from '../../server/mcp.js'; +import { SSEServerTransport } from '../../server/sse.js'; import * as z from 'zod/v4'; +import { CallToolResult } from '../../types.js'; +import { createMcpExpressApp } from '../../server/express.js'; /** * This example server demonstrates the deprecated HTTP+SSE transport @@ -23,14 +25,12 @@ const getServer = () => { { capabilities: { logging: {} } } ); - server.registerTool( + server.tool( 'start-notification-stream', + 'Starts sending periodic notifications', { - description: 'Starts sending periodic notifications', - inputSchema: { - interval: z.number().describe('Interval in milliseconds between notifications').default(1000), - count: z.number().describe('Number of notifications to send').default(10) - } + interval: z.number().describe('Interval in milliseconds between notifications').default(1000), + count: z.number().describe('Number of notifications to send').default(10) }, async ({ interval, count }, extra): Promise => { const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); @@ -163,7 +163,7 @@ process.on('SIGINT', async () => { for (const sessionId in transports) { try { console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId]!.close(); + await transports[sessionId].close(); delete transports[sessionId]; } catch (error) { console.error(`Error closing transport for session ${sessionId}:`, error); diff --git a/examples/server/src/simpleStatelessStreamableHttp.ts b/src/examples/server/simpleStatelessStreamableHttp.ts similarity index 83% rename from examples/server/src/simpleStatelessStreamableHttp.ts rename to src/examples/server/simpleStatelessStreamableHttp.ts index 3aee2c2123..748d82fdae 100644 --- a/examples/server/src/simpleStatelessStreamableHttp.ts +++ b/src/examples/server/simpleStatelessStreamableHttp.ts @@ -1,7 +1,9 @@ -import type { CallToolResult, GetPromptResult, ReadResourceResult } from '@modelcontextprotocol/server'; -import { createMcpExpressApp, McpServer, StreamableHTTPServerTransport } from '@modelcontextprotocol/server'; -import type { Request, Response } from 'express'; +import { Request, Response } from 'express'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; import * as z from 'zod/v4'; +import { CallToolResult, GetPromptResult, ReadResourceResult } from '../../types.js'; +import { createMcpExpressApp } from '../../server/express.js'; const getServer = () => { // Create an MCP server with implementation details @@ -14,13 +16,11 @@ const getServer = () => { ); // Register a simple prompt - server.registerPrompt( + server.prompt( 'greeting-template', + 'A simple greeting prompt template', { - description: 'A simple greeting prompt template', - argsSchema: { - name: z.string().describe('Name to include in greeting') - } + name: z.string().describe('Name to include in greeting') }, async ({ name }): Promise => { return { @@ -38,14 +38,12 @@ const getServer = () => { ); // Register a tool specifically for testing resumability - server.registerTool( + server.tool( 'start-notification-stream', + 'Starts sending periodic notifications for testing resumability', { - description: 'Starts sending periodic notifications for testing resumability', - inputSchema: { - interval: z.number().describe('Interval in milliseconds between notifications').default(100), - count: z.number().describe('Number of notifications to send (0 for 100)').default(10) - } + interval: z.number().describe('Interval in milliseconds between notifications').default(100), + count: z.number().describe('Number of notifications to send (0 for 100)').default(10) }, async ({ interval, count }, extra): Promise => { const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); @@ -80,7 +78,7 @@ const getServer = () => { ); // Create a simple resource at a fixed URI - server.registerResource( + server.resource( 'greeting-resource', 'https://example.com/greetings/default', { mimeType: 'text/plain' }, diff --git a/examples/server/src/simpleStreamableHttp.ts b/src/examples/server/simpleStreamableHttp.ts similarity index 93% rename from examples/server/src/simpleStreamableHttp.ts rename to src/examples/server/simpleStreamableHttp.ts index 7613e37868..ca13631982 100644 --- a/examples/server/src/simpleStreamableHttp.ts +++ b/src/examples/server/simpleStreamableHttp.ts @@ -1,31 +1,25 @@ +import { Request, Response } from 'express'; import { randomUUID } from 'node:crypto'; - -import { setupAuthServer } from '@modelcontextprotocol/examples-shared'; -import type { +import * as z from 'zod/v4'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { getOAuthProtectedResourceMetadataUrl, mcpAuthMetadataRouter } from '../../server/auth/router.js'; +import { requireBearerAuth } from '../../server/auth/middleware/bearerAuth.js'; +import { createMcpExpressApp } from '../../server/express.js'; +import { CallToolResult, + ElicitResultSchema, GetPromptResult, - OAuthMetadata, + isInitializeRequest, PrimitiveSchemaDefinition, ReadResourceResult, ResourceLink -} from '@modelcontextprotocol/server'; -import { - checkResourceAllowed, - createMcpExpressApp, - ElicitResultSchema, - getOAuthProtectedResourceMetadataUrl, - InMemoryTaskMessageQueue, - InMemoryTaskStore, - isInitializeRequest, - mcpAuthMetadataRouter, - McpServer, - requireBearerAuth, - StreamableHTTPServerTransport -} from '@modelcontextprotocol/server'; -import type { Request, Response } from 'express'; -import * as z from 'zod/v4'; - -import { InMemoryEventStore } from './inMemoryEventStore.js'; +} from '../../types.js'; +import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; +import { InMemoryTaskStore, InMemoryTaskMessageQueue } from '../../experimental/tasks/stores/in-memory.js'; +import { setupAuthServer } from './demoInMemoryOAuthProvider.js'; +import { OAuthMetadata } from '../../shared/auth.js'; +import { checkResourceAllowed } from '../../shared/auth-utils.js'; // Check for OAuth flag const useOAuth = process.argv.includes('--oauth'); @@ -73,18 +67,16 @@ const getServer = () => { ); // Register a tool that sends multiple greetings with notifications (with annotations) - server.registerTool( + server.tool( 'multi-greet', + 'A tool that sends different greetings with delays between them', { - description: 'A tool that sends different greetings with delays between them', - inputSchema: { - name: z.string().describe('Name to greet') - }, - annotations: { - title: 'Multiple Greeting Tool', - readOnlyHint: true, - openWorldHint: false - } + name: z.string().describe('Name to greet') + }, + { + title: 'Multiple Greeting Tool', + readOnlyHint: true, + openWorldHint: false }, async ({ name }, extra): Promise => { const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); @@ -129,13 +121,11 @@ const getServer = () => { ); // Register a tool that demonstrates form elicitation (user input collection with a schema) // This creates a closure that captures the server instance - server.registerTool( + server.tool( 'collect-user-info', + 'A tool that collects user information through form elicitation', { - description: 'A tool that collects user information through form elicitation', - inputSchema: { - infoType: z.enum(['contact', 'preferences', 'feedback']).describe('Type of information to collect') - } + infoType: z.enum(['contact', 'preferences', 'feedback']).describe('Type of information to collect') }, async ({ infoType }, extra): Promise => { let message: string; @@ -312,14 +302,12 @@ const getServer = () => { ); // Register a tool specifically for testing resumability - server.registerTool( + server.tool( 'start-notification-stream', + 'Starts sending periodic notifications for testing resumability', { - description: 'Starts sending periodic notifications for testing resumability', - inputSchema: { - interval: z.number().describe('Interval in milliseconds between notifications').default(100), - count: z.number().describe('Number of notifications to send (0 for 100)').default(50) - } + interval: z.number().describe('Interval in milliseconds between notifications').default(100), + count: z.number().describe('Number of notifications to send (0 for 100)').default(50) }, async ({ interval, count }, extra): Promise => { const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); @@ -552,7 +540,7 @@ if (useOAuth) { throw new Error(`Invalid or expired token: ${text}`); } - const data = (await response.json()) as { aud: string; client_id: string; scope: string; exp: number }; + const data = await response.json(); if (strictOAuth) { if (!data.aud) { @@ -752,7 +740,7 @@ process.on('SIGINT', async () => { for (const sessionId in transports) { try { console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId]!.close(); + await transports[sessionId].close(); delete transports[sessionId]; } catch (error) { console.error(`Error closing transport for session ${sessionId}:`, error); diff --git a/examples/server/src/simpleTaskInteractive.ts b/src/examples/server/simpleTaskInteractive.ts similarity index 96% rename from examples/server/src/simpleTaskInteractive.ts rename to src/examples/server/simpleTaskInteractive.ts index 956c33f8e3..c35126dc0b 100644 --- a/examples/server/src/simpleTaskInteractive.ts +++ b/src/examples/server/simpleTaskInteractive.ts @@ -9,43 +9,35 @@ * creates a task, and the result is fetched via tasks/result endpoint. */ +import { Request, Response } from 'express'; import { randomUUID } from 'node:crypto'; - -import type { +import { Server } from '../../server/index.js'; +import { createMcpExpressApp } from '../../server/express.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { CallToolResult, - CreateMessageRequest, - CreateMessageResult, - CreateTaskOptions, CreateTaskResult, - ElicitRequestFormParams, - ElicitResult, - GetTaskPayloadResult, GetTaskResult, - JSONRPCRequest, - PrimitiveSchemaDefinition, - QueuedMessage, - QueuedRequest, - RequestId, + Tool, + TextContent, + RELATED_TASK_META_KEY, + Task, Result, + RequestId, + JSONRPCRequest, SamplingMessage, - Task, - TaskMessageQueue, - TextContent, - Tool -} from '@modelcontextprotocol/server'; -import { + ElicitRequestFormParams, + CreateMessageRequest, + ElicitResult, + CreateMessageResult, + PrimitiveSchemaDefinition, + ListToolsRequestSchema, CallToolRequestSchema, - createMcpExpressApp, - GetTaskPayloadRequestSchema, GetTaskRequestSchema, - InMemoryTaskStore, - isTerminal, - ListToolsRequestSchema, - RELATED_TASK_META_KEY, - Server, - StreamableHTTPServerTransport -} from '@modelcontextprotocol/server'; -import type { Request, Response } from 'express'; + GetTaskPayloadRequestSchema +} from '../../types.js'; +import { TaskMessageQueue, QueuedMessage, QueuedRequest, isTerminal, CreateTaskOptions } from '../../experimental/tasks/interfaces.js'; +import { InMemoryTaskStore } from '../../experimental/tasks/stores/in-memory.js'; // ============================================================================ // Resolver - Promise-like for passing results between async operations @@ -187,12 +179,12 @@ class TaskMessageQueueWithResolvers implements TaskMessageQueue { class TaskStoreWithNotifications extends InMemoryTaskStore { private updateResolvers = new Map void)[]>(); - override async updateTaskStatus(taskId: string, status: Task['status'], statusMessage?: string, sessionId?: string): Promise { + async updateTaskStatus(taskId: string, status: Task['status'], statusMessage?: string, sessionId?: string): Promise { await super.updateTaskStatus(taskId, status, statusMessage, sessionId); this.notifyUpdate(taskId); } - override async storeTaskResult(taskId: string, status: 'completed' | 'failed', result: Result, sessionId?: string): Promise { + async storeTaskResult(taskId: string, status: 'completed' | 'failed', result: Result, sessionId?: string): Promise { await super.storeTaskResult(taskId, status, result, sessionId); this.notifyUpdate(taskId); } @@ -626,7 +618,7 @@ const createServer = (): Server => { }); // Handle tasks/result - server.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra): Promise => { + server.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra): Promise => { const { taskId } = request.params; console.log(`[Server] tasks/result called for task ${taskId}`); return taskResultHandler.handle(taskId, server, extra.sessionId ?? ''); @@ -739,7 +731,7 @@ process.on('SIGINT', async () => { console.log('\nShutting down server...'); for (const sessionId of Object.keys(transports)) { try { - await transports[sessionId]!.close(); + await transports[sessionId].close(); delete transports[sessionId]; } catch (error) { console.error(`Error closing session ${sessionId}:`, error); diff --git a/examples/server/src/sseAndStreamableHttpCompatibleServer.ts b/src/examples/server/sseAndStreamableHttpCompatibleServer.ts similarity index 89% rename from examples/server/src/sseAndStreamableHttpCompatibleServer.ts rename to src/examples/server/sseAndStreamableHttpCompatibleServer.ts index 335802d0a4..5c91b7e336 100644 --- a/examples/server/src/sseAndStreamableHttpCompatibleServer.ts +++ b/src/examples/server/sseAndStreamableHttpCompatibleServer.ts @@ -1,22 +1,17 @@ +import { Request, Response } from 'express'; import { randomUUID } from 'node:crypto'; - -import type { CallToolResult } from '@modelcontextprotocol/server'; -import { - createMcpExpressApp, - isInitializeRequest, - McpServer, - SSEServerTransport, - StreamableHTTPServerTransport -} from '@modelcontextprotocol/server'; -import type { Request, Response } from 'express'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { SSEServerTransport } from '../../server/sse.js'; import * as z from 'zod/v4'; - -import { InMemoryEventStore } from './inMemoryEventStore.js'; +import { CallToolResult, isInitializeRequest } from '../../types.js'; +import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; +import { createMcpExpressApp } from '../../server/express.js'; /** * This example server demonstrates backwards compatibility with both: * 1. The deprecated HTTP+SSE transport (protocol version 2024-11-05) - * 2. The Streamable HTTP transport (protocol version 2025-11-25) + * 2. The Streamable HTTP transport (protocol version 2025-03-26) * * It maintains a single MCP server instance but exposes two transport options: * - /mcp: The new Streamable HTTP endpoint (supports GET/POST/DELETE) @@ -34,14 +29,12 @@ const getServer = () => { ); // Register a simple tool that sends notifications over time - server.registerTool( + server.tool( 'start-notification-stream', + 'Starts sending periodic notifications for testing resumability', { - description: 'Starts sending periodic notifications for testing resumability', - inputSchema: { - interval: z.number().describe('Interval in milliseconds between notifications').default(100), - count: z.number().describe('Number of notifications to send (0 for 100)').default(50) - } + interval: z.number().describe('Interval in milliseconds between notifications').default(100), + count: z.number().describe('Number of notifications to send (0 for 100)').default(50) }, async ({ interval, count }, extra): Promise => { const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); @@ -84,7 +77,7 @@ const app = createMcpExpressApp(); const transports: Record = {}; //============================================================================= -// STREAMABLE HTTP TRANSPORT (PROTOCOL VERSION 2025-11-25) +// STREAMABLE HTTP TRANSPORT (PROTOCOL VERSION 2025-03-26) //============================================================================= // Handle all MCP Streamable HTTP requests (GET, POST, DELETE) on a single endpoint @@ -221,10 +214,10 @@ app.listen(PORT, error => { ============================================== SUPPORTED TRANSPORT OPTIONS: -1. Streamable Http(Protocol version: 2025-11-25) +1. Streamable Http(Protocol version: 2025-03-26) Endpoint: /mcp Methods: GET, POST, DELETE - Usage: + Usage: - Initialize with POST to /mcp - Establish SSE stream with GET to /mcp - Send requests with POST to /mcp @@ -247,7 +240,7 @@ process.on('SIGINT', async () => { for (const sessionId in transports) { try { console.log(`Closing transport for session ${sessionId}`); - await transports[sessionId]!.close(); + await transports[sessionId].close(); delete transports[sessionId]; } catch (error) { console.error(`Error closing transport for session ${sessionId}:`, error); diff --git a/examples/server/src/ssePollingExample.ts b/src/examples/server/ssePollingExample.ts similarity index 91% rename from examples/server/src/ssePollingExample.ts rename to src/examples/server/ssePollingExample.ts index 4e3d36328f..bbecf2fdbd 100644 --- a/examples/server/src/ssePollingExample.ts +++ b/src/examples/server/ssePollingExample.ts @@ -9,17 +9,17 @@ * - Uses `eventStore` to persist events for replay after reconnection * - Uses `extra.closeSSEStream()` callback to gracefully disconnect clients mid-operation * - * Run with: pnpm tsx src/ssePollingExample.ts + * Run with: npx tsx src/examples/server/ssePollingExample.ts * Test with: curl or the MCP Inspector */ +import { Request, Response } from 'express'; import { randomUUID } from 'node:crypto'; - -import type { CallToolResult } from '@modelcontextprotocol/server'; -import { createMcpExpressApp, McpServer, StreamableHTTPServerTransport } from '@modelcontextprotocol/server'; +import { McpServer } from '../../server/mcp.js'; +import { createMcpExpressApp } from '../../server/express.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { CallToolResult } from '../../types.js'; +import { InMemoryEventStore } from '../shared/inMemoryEventStore.js'; import cors from 'cors'; -import type { Request, Response } from 'express'; - -import { InMemoryEventStore } from './inMemoryEventStore.js'; // Create the MCP server const server = new McpServer( diff --git a/examples/server/src/standaloneSseWithGetStreamableHttp.ts b/src/examples/server/standaloneSseWithGetStreamableHttp.ts similarity index 92% rename from examples/server/src/standaloneSseWithGetStreamableHttp.ts rename to src/examples/server/standaloneSseWithGetStreamableHttp.ts index cceb242992..546d35c70c 100644 --- a/examples/server/src/standaloneSseWithGetStreamableHttp.ts +++ b/src/examples/server/standaloneSseWithGetStreamableHttp.ts @@ -1,8 +1,9 @@ +import { Request, Response } from 'express'; import { randomUUID } from 'node:crypto'; - -import type { ReadResourceResult } from '@modelcontextprotocol/server'; -import { createMcpExpressApp, isInitializeRequest, McpServer, StreamableHTTPServerTransport } from '@modelcontextprotocol/server'; -import type { Request, Response } from 'express'; +import { McpServer } from '../../server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../server/streamableHttp.js'; +import { isInitializeRequest, ReadResourceResult } from '../../types.js'; +import { createMcpExpressApp } from '../../server/express.js'; // Create an MCP server with implementation details const server = new McpServer({ @@ -15,7 +16,7 @@ const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {}; const addResource = (name: string, content: string) => { const uri = `https://mcp-example.com/dynamic/${encodeURIComponent(name)}`; - server.registerResource( + server.resource( name, uri, { mimeType: 'text/plain', description: `Dynamic resource: ${name}` }, diff --git a/examples/server/src/toolWithSampleServer.ts b/src/examples/server/toolWithSampleServer.ts similarity index 89% rename from examples/server/src/toolWithSampleServer.ts rename to src/examples/server/toolWithSampleServer.ts index 4d92031449..e6d7335986 100644 --- a/examples/server/src/toolWithSampleServer.ts +++ b/src/examples/server/toolWithSampleServer.ts @@ -1,6 +1,7 @@ -// Run with: pnpm tsx src/toolWithSampleServer.ts +// Run with: npx tsx src/examples/server/toolWithSampleServer.ts -import { McpServer, StdioServerTransport } from '@modelcontextprotocol/server'; +import { McpServer } from '../../server/mcp.js'; +import { StdioServerTransport } from '../../server/stdio.js'; import * as z from 'zod/v4'; const mcpServer = new McpServer({ diff --git a/examples/server/src/inMemoryEventStore.ts b/src/examples/shared/inMemoryEventStore.ts similarity index 93% rename from examples/server/src/inMemoryEventStore.ts rename to src/examples/shared/inMemoryEventStore.ts index 001459ffa4..d4d02eb913 100644 --- a/examples/server/src/inMemoryEventStore.ts +++ b/src/examples/shared/inMemoryEventStore.ts @@ -1,4 +1,5 @@ -import type { EventStore, JSONRPCMessage } from '@modelcontextprotocol/server'; +import { JSONRPCMessage } from '../../types.js'; +import { EventStore } from '../../server/streamableHttp.js'; /** * Simple in-memory implementation of the EventStore interface for resumability @@ -20,7 +21,7 @@ export class InMemoryEventStore implements EventStore { */ private getStreamIdFromEventId(eventId: string): string { const parts = eventId.split('_'); - return parts.length > 0 ? parts[0]! : ''; + return parts.length > 0 ? parts[0] : ''; } /** diff --git a/packages/server/src/experimental/index.ts b/src/experimental/index.ts similarity index 100% rename from packages/server/src/experimental/index.ts rename to src/experimental/index.ts diff --git a/packages/client/src/experimental/tasks/client.ts b/src/experimental/tasks/client.ts similarity index 94% rename from packages/client/src/experimental/tasks/client.ts rename to src/experimental/tasks/client.ts index df57e91a4a..f62941dc8f 100644 --- a/packages/client/src/experimental/tasks/client.ts +++ b/src/experimental/tasks/client.ts @@ -5,24 +5,14 @@ * @experimental */ -import type { - AnyObjectSchema, - CallToolRequest, - CancelTaskResult, - ClientRequest, - CompatibilityCallToolResultSchema, - GetTaskResult, - ListTasksResult, - Notification, - Request, - RequestOptions, - ResponseMessage, - Result, - SchemaOutput -} from '@modelcontextprotocol/core'; -import { CallToolResultSchema, ErrorCode, McpError } from '@modelcontextprotocol/core'; +import type { Client } from '../../client/index.js'; +import type { RequestOptions } from '../../shared/protocol.js'; +import type { ResponseMessage } from '../../shared/responseMessage.js'; +import type { AnyObjectSchema, SchemaOutput } from '../../server/zod-compat.js'; +import type { CallToolRequest, ClientRequest, Notification, Request, Result } from '../../types.js'; +import { CallToolResultSchema, type CompatibilityCallToolResultSchema, McpError, ErrorCode } from '../../types.js'; -import type { Client } from '../../client/client.js'; +import type { GetTaskResult, ListTasksResult, CancelTaskResult } from './types.js'; /** * Internal interface for accessing Client's private methods. diff --git a/packages/core/src/experimental/tasks/helpers.ts b/src/experimental/tasks/helpers.ts similarity index 100% rename from packages/core/src/experimental/tasks/helpers.ts rename to src/experimental/tasks/helpers.ts diff --git a/src/experimental/tasks/index.ts b/src/experimental/tasks/index.ts new file mode 100644 index 0000000000..398d343932 --- /dev/null +++ b/src/experimental/tasks/index.ts @@ -0,0 +1,34 @@ +/** + * Experimental task features for MCP SDK. + * WARNING: These APIs are experimental and may change without notice. + * + * @experimental + */ + +// Re-export spec types for convenience +export * from './types.js'; + +// SDK implementation interfaces +export * from './interfaces.js'; + +// Assertion helpers +export * from './helpers.js'; + +// Wrapper classes +export * from './client.js'; +export * from './server.js'; +export * from './mcp-server.js'; + +// Store implementations +export * from './stores/in-memory.js'; + +// Re-export response message types for task streaming +export type { + ResponseMessage, + TaskStatusMessage, + TaskCreatedMessage, + ResultMessage, + ErrorMessage, + BaseResponseMessage +} from '../../shared/responseMessage.js'; +export { takeResult, toArrayAsync } from '../../shared/responseMessage.js'; diff --git a/packages/core/src/experimental/tasks/interfaces.ts b/src/experimental/tasks/interfaces.ts similarity index 83% rename from packages/core/src/experimental/tasks/interfaces.ts rename to src/experimental/tasks/interfaces.ts index c1901d70a6..4800e65dc1 100644 --- a/packages/core/src/experimental/tasks/interfaces.ts +++ b/src/experimental/tasks/interfaces.ts @@ -3,20 +3,24 @@ * WARNING: These APIs are experimental and may change without notice. */ -import type { RequestHandlerExtra, RequestTaskStore } from '../../shared/protocol.js'; -import type { - JSONRPCErrorResponse, - JSONRPCNotification, - JSONRPCRequest, - JSONRPCResultResponse, +import { + Task, Request, RequestId, Result, - ServerNotification, + JSONRPCRequest, + JSONRPCNotification, + JSONRPCResponse, + JSONRPCError, ServerRequest, - Task, + ServerNotification, + CallToolResult, + GetTaskResult, ToolExecution -} from '../../types/types.js'; +} from '../../types.js'; +import { CreateTaskResult } from './types.js'; +import type { RequestHandlerExtra, RequestTaskStore } from '../../shared/protocol.js'; +import type { ZodRawShapeCompat, AnySchema, ShapeOutput } from '../../server/zod-compat.js'; // ============================================================================ // Task Handler Types (for registerToolTask) @@ -39,6 +43,48 @@ export interface TaskRequestHandlerExtra extends RequestHandlerExtra, + Args extends undefined | ZodRawShapeCompat | AnySchema = undefined +> = Args extends ZodRawShapeCompat + ? (args: ShapeOutput, extra: ExtraT) => SendResultT | Promise + : Args extends AnySchema + ? (args: unknown, extra: ExtraT) => SendResultT | Promise + : (extra: ExtraT) => SendResultT | Promise; + +/** + * Handler for creating a task. + * @experimental + */ +export type CreateTaskRequestHandler< + SendResultT extends Result, + Args extends undefined | ZodRawShapeCompat | AnySchema = undefined +> = BaseToolCallback; + +/** + * Handler for task operations (get, getResult). + * @experimental + */ +export type TaskRequestHandler< + SendResultT extends Result, + Args extends undefined | ZodRawShapeCompat | AnySchema = undefined +> = BaseToolCallback; + +/** + * Interface for task-based tool handlers. + * @experimental + */ +export interface ToolTaskHandler { + createTask: CreateTaskRequestHandler; + getTask: TaskRequestHandler; + getTaskResult: TaskRequestHandler; +} + /** * Task-specific execution configuration. * taskSupport cannot be 'forbidden' for task-based tools. @@ -78,13 +124,13 @@ export interface QueuedNotification extends BaseQueuedMessage { export interface QueuedResponse extends BaseQueuedMessage { type: 'response'; /** The actual JSONRPC response */ - message: JSONRPCResultResponse; + message: JSONRPCResponse; } export interface QueuedError extends BaseQueuedMessage { type: 'error'; /** The actual JSONRPC error */ - message: JSONRPCErrorResponse; + message: JSONRPCError; } /** diff --git a/packages/server/src/experimental/tasks/mcp-server.ts b/src/experimental/tasks/mcp-server.ts similarity index 94% rename from packages/server/src/experimental/tasks/mcp-server.ts rename to src/experimental/tasks/mcp-server.ts index 6fd5a6cc5c..506f3d72b7 100644 --- a/packages/server/src/experimental/tasks/mcp-server.ts +++ b/src/experimental/tasks/mcp-server.ts @@ -5,10 +5,10 @@ * @experimental */ -import type { AnySchema, TaskToolExecution, ToolAnnotations, ToolExecution, ZodRawShapeCompat } from '@modelcontextprotocol/core'; - -import type { AnyToolHandler, McpServer, RegisteredTool } from '../../server/mcp.js'; -import type { ToolTaskHandler } from './interfaces.js'; +import type { McpServer, RegisteredTool, AnyToolHandler } from '../../server/mcp.js'; +import type { ZodRawShapeCompat, AnySchema } from '../../server/zod-compat.js'; +import type { ToolAnnotations, ToolExecution } from '../../types.js'; +import type { ToolTaskHandler, TaskToolExecution } from './interfaces.js'; /** * Internal interface for accessing McpServer's private _createRegisteredTool method. diff --git a/packages/server/src/experimental/tasks/server.ts b/src/experimental/tasks/server.ts similarity index 91% rename from packages/server/src/experimental/tasks/server.ts rename to src/experimental/tasks/server.ts index 33bde3298b..a4150a8d76 100644 --- a/packages/server/src/experimental/tasks/server.ts +++ b/src/experimental/tasks/server.ts @@ -5,21 +5,11 @@ * @experimental */ -import type { - AnySchema, - CancelTaskResult, - GetTaskResult, - ListTasksResult, - Notification, - Request, - RequestOptions, - ResponseMessage, - Result, - SchemaOutput, - ServerRequest -} from '@modelcontextprotocol/core'; - -import type { Server } from '../../server/server.js'; +import type { Server } from '../../server/index.js'; +import type { RequestOptions } from '../../shared/protocol.js'; +import type { ResponseMessage } from '../../shared/responseMessage.js'; +import type { AnySchema, SchemaOutput } from '../../server/zod-compat.js'; +import type { ServerRequest, Notification, Request, Result, GetTaskResult, ListTasksResult, CancelTaskResult } from '../../types.js'; /** * Experimental task features for low-level MCP servers. diff --git a/packages/core/src/experimental/tasks/stores/in-memory.ts b/src/experimental/tasks/stores/in-memory.ts similarity index 97% rename from packages/core/src/experimental/tasks/stores/in-memory.ts rename to src/experimental/tasks/stores/in-memory.ts index 42ddf5bf4a..4cc903606d 100644 --- a/packages/core/src/experimental/tasks/stores/in-memory.ts +++ b/src/experimental/tasks/stores/in-memory.ts @@ -5,12 +5,10 @@ * @experimental */ +import { Task, Request, RequestId, Result } from '../../../types.js'; +import { TaskStore, isTerminal, TaskMessageQueue, QueuedMessage, CreateTaskOptions } from '../interfaces.js'; import { randomBytes } from 'node:crypto'; -import type { Request, RequestId, Result, Task } from '../../../types/types.js'; -import type { CreateTaskOptions, QueuedMessage, TaskMessageQueue, TaskStore } from '../interfaces.js'; -import { isTerminal } from '../interfaces.js'; - interface StoredTask { task: Task; request: Request; diff --git a/src/experimental/tasks/types.ts b/src/experimental/tasks/types.ts new file mode 100644 index 0000000000..a3845bae1c --- /dev/null +++ b/src/experimental/tasks/types.ts @@ -0,0 +1,43 @@ +/** + * Re-exports of task-related types from the MCP protocol spec. + * WARNING: These APIs are experimental and may change without notice. + * + * These types are defined in types.ts (matching the protocol spec) and + * re-exported here for convenience when working with experimental task features. + */ + +// Task schemas (Zod) +export { + TaskCreationParamsSchema, + RelatedTaskMetadataSchema, + TaskSchema, + CreateTaskResultSchema, + TaskStatusNotificationParamsSchema, + TaskStatusNotificationSchema, + GetTaskRequestSchema, + GetTaskResultSchema, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + ListTasksResultSchema, + CancelTaskRequestSchema, + CancelTaskResultSchema, + ClientTasksCapabilitySchema, + ServerTasksCapabilitySchema +} from '../../types.js'; + +// Task types (inferred from schemas) +export type { + Task, + TaskCreationParams, + RelatedTaskMetadata, + CreateTaskResult, + TaskStatusNotificationParams, + TaskStatusNotification, + GetTaskRequest, + GetTaskResult, + GetTaskPayloadRequest, + ListTasksRequest, + ListTasksResult, + CancelTaskRequest, + CancelTaskResult +} from '../../types.js'; diff --git a/packages/core/src/util/inMemory.ts b/src/inMemory.ts similarity index 93% rename from packages/core/src/util/inMemory.ts rename to src/inMemory.ts index 3f832b06b0..26062624d4 100644 --- a/packages/core/src/util/inMemory.ts +++ b/src/inMemory.ts @@ -1,5 +1,6 @@ -import type { Transport } from '../shared/transport.js'; -import type { AuthInfo, JSONRPCMessage, RequestId } from '../types/types.js'; +import { Transport } from './shared/transport.js'; +import { JSONRPCMessage, RequestId } from './types.js'; +import { AuthInfo } from './server/auth/types.js'; interface QueuedMessage { message: JSONRPCMessage; diff --git a/packages/server/src/server/auth/clients.ts b/src/server/auth/clients.ts similarity index 93% rename from packages/server/src/server/auth/clients.ts rename to src/server/auth/clients.ts index f6aca1be92..4e3f8e17ee 100644 --- a/packages/server/src/server/auth/clients.ts +++ b/src/server/auth/clients.ts @@ -1,4 +1,4 @@ -import type { OAuthClientInformationFull } from '@modelcontextprotocol/core'; +import { OAuthClientInformationFull } from '../../shared/auth.js'; /** * Stores information about registered OAuth clients for this server. diff --git a/packages/core/src/auth/errors.ts b/src/server/auth/errors.ts similarity index 84% rename from packages/core/src/auth/errors.ts rename to src/server/auth/errors.ts index d145b6296b..dff413e38a 100644 --- a/packages/core/src/auth/errors.ts +++ b/src/server/auth/errors.ts @@ -1,4 +1,4 @@ -import type { OAuthErrorResponse } from '../shared/auth.js'; +import { OAuthErrorResponse } from '../../shared/auth.js'; /** * Base class for all OAuth errors @@ -41,7 +41,7 @@ export class OAuthError extends Error { * or is otherwise malformed. */ export class InvalidRequestError extends OAuthError { - static override errorCode = 'invalid_request'; + static errorCode = 'invalid_request'; } /** @@ -49,7 +49,7 @@ export class InvalidRequestError extends OAuthError { * authentication included, or unsupported authentication method). */ export class InvalidClientError extends OAuthError { - static override errorCode = 'invalid_client'; + static errorCode = 'invalid_client'; } /** @@ -58,7 +58,7 @@ export class InvalidClientError extends OAuthError { * authorization request, or was issued to another client. */ export class InvalidGrantError extends OAuthError { - static override errorCode = 'invalid_grant'; + static errorCode = 'invalid_grant'; } /** @@ -66,7 +66,7 @@ export class InvalidGrantError extends OAuthError { * this authorization grant type. */ export class UnauthorizedClientError extends OAuthError { - static override errorCode = 'unauthorized_client'; + static errorCode = 'unauthorized_client'; } /** @@ -74,7 +74,7 @@ export class UnauthorizedClientError extends OAuthError { * by the authorization server. */ export class UnsupportedGrantTypeError extends OAuthError { - static override errorCode = 'unsupported_grant_type'; + static errorCode = 'unsupported_grant_type'; } /** @@ -82,14 +82,14 @@ export class UnsupportedGrantTypeError extends OAuthError { * exceeds the scope granted by the resource owner. */ export class InvalidScopeError extends OAuthError { - static override errorCode = 'invalid_scope'; + static errorCode = 'invalid_scope'; } /** * Access denied error - The resource owner or authorization server denied the request. */ export class AccessDeniedError extends OAuthError { - static override errorCode = 'access_denied'; + static errorCode = 'access_denied'; } /** @@ -97,7 +97,7 @@ export class AccessDeniedError extends OAuthError { * that prevented it from fulfilling the request. */ export class ServerError extends OAuthError { - static override errorCode = 'server_error'; + static errorCode = 'server_error'; } /** @@ -105,7 +105,7 @@ export class ServerError extends OAuthError { * handle the request due to a temporary overloading or maintenance of the server. */ export class TemporarilyUnavailableError extends OAuthError { - static override errorCode = 'temporarily_unavailable'; + static errorCode = 'temporarily_unavailable'; } /** @@ -113,7 +113,7 @@ export class TemporarilyUnavailableError extends OAuthError { * obtaining an authorization code using this method. */ export class UnsupportedResponseTypeError extends OAuthError { - static override errorCode = 'unsupported_response_type'; + static errorCode = 'unsupported_response_type'; } /** @@ -121,7 +121,7 @@ export class UnsupportedResponseTypeError extends OAuthError { * the requested token type. */ export class UnsupportedTokenTypeError extends OAuthError { - static override errorCode = 'unsupported_token_type'; + static errorCode = 'unsupported_token_type'; } /** @@ -129,7 +129,7 @@ export class UnsupportedTokenTypeError extends OAuthError { * or invalid for other reasons. */ export class InvalidTokenError extends OAuthError { - static override errorCode = 'invalid_token'; + static errorCode = 'invalid_token'; } /** @@ -137,7 +137,7 @@ export class InvalidTokenError extends OAuthError { * (Custom, non-standard error) */ export class MethodNotAllowedError extends OAuthError { - static override errorCode = 'method_not_allowed'; + static errorCode = 'method_not_allowed'; } /** @@ -145,7 +145,7 @@ export class MethodNotAllowedError extends OAuthError { * (Custom, non-standard error based on RFC 6585) */ export class TooManyRequestsError extends OAuthError { - static override errorCode = 'too_many_requests'; + static errorCode = 'too_many_requests'; } /** @@ -153,14 +153,14 @@ export class TooManyRequestsError extends OAuthError { * (Custom error for dynamic client registration - RFC 7591) */ export class InvalidClientMetadataError extends OAuthError { - static override errorCode = 'invalid_client_metadata'; + static errorCode = 'invalid_client_metadata'; } /** * Insufficient scope error - The request requires higher privileges than provided by the access token. */ export class InsufficientScopeError extends OAuthError { - static override errorCode = 'insufficient_scope'; + static errorCode = 'insufficient_scope'; } /** @@ -168,7 +168,7 @@ export class InsufficientScopeError extends OAuthError { * (Custom error for resource indicators - RFC 8707) */ export class InvalidTargetError extends OAuthError { - static override errorCode = 'invalid_target'; + static errorCode = 'invalid_target'; } /** @@ -183,7 +183,7 @@ export class CustomOAuthError extends OAuthError { super(message, errorUri); } - override get errorCode(): string { + get errorCode(): string { return this.customErrorCode; } } diff --git a/packages/server/src/server/auth/handlers/authorize.ts b/src/server/auth/handlers/authorize.ts similarity index 91% rename from packages/server/src/server/auth/handlers/authorize.ts rename to src/server/auth/handlers/authorize.ts index 65875529e5..dcb6c03ecf 100644 --- a/packages/server/src/server/auth/handlers/authorize.ts +++ b/src/server/auth/handlers/authorize.ts @@ -1,12 +1,10 @@ -import { InvalidClientError, InvalidRequestError, OAuthError, ServerError, TooManyRequestsError } from '@modelcontextprotocol/core'; -import type { RequestHandler } from 'express'; -import express from 'express'; -import type { Options as RateLimitOptions } from 'express-rate-limit'; -import { rateLimit } from 'express-rate-limit'; +import { RequestHandler } from 'express'; import * as z from 'zod/v4'; - +import express from 'express'; +import { OAuthServerProvider } from '../provider.js'; +import { rateLimit, Options as RateLimitOptions } from 'express-rate-limit'; import { allowedMethods } from '../middleware/allowedMethods.js'; -import type { OAuthServerProvider } from '../provider.js'; +import { InvalidRequestError, InvalidClientError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; export type AuthorizationHandlerOptions = { provider: OAuthServerProvider; @@ -130,7 +128,7 @@ export function authorizationHandler({ provider, rateLimit: rateLimitConfig }: A { state, scopes: requestedScopes, - redirectUri: redirect_uri!, // TODO: Someone to look at. Strict tsconfig showed this could be undefined, while the return type is string. + redirectUri: redirect_uri, codeChallenge: code_challenge, resource: resource ? new URL(resource) : undefined }, @@ -139,10 +137,10 @@ export function authorizationHandler({ provider, rateLimit: rateLimitConfig }: A } catch (error) { // Post-redirect errors - redirect with error parameters if (error instanceof OAuthError) { - res.redirect(302, createErrorRedirect(redirect_uri!, error, state)); + res.redirect(302, createErrorRedirect(redirect_uri, error, state)); } else { const serverError = new ServerError('Internal Server Error'); - res.redirect(302, createErrorRedirect(redirect_uri!, serverError, state)); + res.redirect(302, createErrorRedirect(redirect_uri, serverError, state)); } } }); diff --git a/packages/server/src/server/auth/handlers/metadata.ts b/src/server/auth/handlers/metadata.ts similarity index 76% rename from packages/server/src/server/auth/handlers/metadata.ts rename to src/server/auth/handlers/metadata.ts index 529a6e57a8..e0f07a99b8 100644 --- a/packages/server/src/server/auth/handlers/metadata.ts +++ b/src/server/auth/handlers/metadata.ts @@ -1,8 +1,6 @@ -import type { OAuthMetadata, OAuthProtectedResourceMetadata } from '@modelcontextprotocol/core'; +import express, { RequestHandler } from 'express'; +import { OAuthMetadata, OAuthProtectedResourceMetadata } from '../../../shared/auth.js'; import cors from 'cors'; -import type { RequestHandler } from 'express'; -import express from 'express'; - import { allowedMethods } from '../middleware/allowedMethods.js'; export function metadataHandler(metadata: OAuthMetadata | OAuthProtectedResourceMetadata): RequestHandler { diff --git a/packages/server/src/server/auth/handlers/register.ts b/src/server/auth/handlers/register.ts similarity index 89% rename from packages/server/src/server/auth/handlers/register.ts rename to src/server/auth/handlers/register.ts index a78154d482..1830619b4e 100644 --- a/packages/server/src/server/auth/handlers/register.ts +++ b/src/server/auth/handlers/register.ts @@ -1,21 +1,11 @@ +import express, { RequestHandler } from 'express'; +import { OAuthClientInformationFull, OAuthClientMetadataSchema } from '../../../shared/auth.js'; import crypto from 'node:crypto'; - -import type { OAuthClientInformationFull } from '@modelcontextprotocol/core'; -import { - InvalidClientMetadataError, - OAuthClientMetadataSchema, - OAuthError, - ServerError, - TooManyRequestsError -} from '@modelcontextprotocol/core'; import cors from 'cors'; -import type { RequestHandler } from 'express'; -import express from 'express'; -import type { Options as RateLimitOptions } from 'express-rate-limit'; -import { rateLimit } from 'express-rate-limit'; - -import type { OAuthRegisteredClientsStore } from '../clients.js'; +import { OAuthRegisteredClientsStore } from '../clients.js'; +import { rateLimit, Options as RateLimitOptions } from 'express-rate-limit'; import { allowedMethods } from '../middleware/allowedMethods.js'; +import { InvalidClientMetadataError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; export type ClientRegistrationHandlerOptions = { /** diff --git a/packages/server/src/server/auth/handlers/revoke.ts b/src/server/auth/handlers/revoke.ts similarity index 86% rename from packages/server/src/server/auth/handlers/revoke.ts rename to src/server/auth/handlers/revoke.ts index c7c9f8a6af..da7ef04f81 100644 --- a/packages/server/src/server/auth/handlers/revoke.ts +++ b/src/server/auth/handlers/revoke.ts @@ -1,19 +1,11 @@ -import { - InvalidRequestError, - OAuthError, - OAuthTokenRevocationRequestSchema, - ServerError, - TooManyRequestsError -} from '@modelcontextprotocol/core'; +import { OAuthServerProvider } from '../provider.js'; +import express, { RequestHandler } from 'express'; import cors from 'cors'; -import type { RequestHandler } from 'express'; -import express from 'express'; -import type { Options as RateLimitOptions } from 'express-rate-limit'; -import { rateLimit } from 'express-rate-limit'; - -import { allowedMethods } from '../middleware/allowedMethods.js'; import { authenticateClient } from '../middleware/clientAuth.js'; -import type { OAuthServerProvider } from '../provider.js'; +import { OAuthTokenRevocationRequestSchema } from '../../../shared/auth.js'; +import { rateLimit, Options as RateLimitOptions } from 'express-rate-limit'; +import { allowedMethods } from '../middleware/allowedMethods.js'; +import { InvalidRequestError, ServerError, TooManyRequestsError, OAuthError } from '../errors.js'; export type RevocationHandlerOptions = { provider: OAuthServerProvider; diff --git a/packages/server/src/server/auth/handlers/token.ts b/src/server/auth/handlers/token.ts similarity index 94% rename from packages/server/src/server/auth/handlers/token.ts rename to src/server/auth/handlers/token.ts index 3b7941294c..4cc4e8ab8b 100644 --- a/packages/server/src/server/auth/handlers/token.ts +++ b/src/server/auth/handlers/token.ts @@ -1,22 +1,19 @@ +import * as z from 'zod/v4'; +import express, { RequestHandler } from 'express'; +import { OAuthServerProvider } from '../provider.js'; +import cors from 'cors'; +import { verifyChallenge } from 'pkce-challenge'; +import { authenticateClient } from '../middleware/clientAuth.js'; +import { rateLimit, Options as RateLimitOptions } from 'express-rate-limit'; +import { allowedMethods } from '../middleware/allowedMethods.js'; import { - InvalidGrantError, InvalidRequestError, - OAuthError, + InvalidGrantError, + UnsupportedGrantTypeError, ServerError, TooManyRequestsError, - UnsupportedGrantTypeError -} from '@modelcontextprotocol/core'; -import cors from 'cors'; -import type { RequestHandler } from 'express'; -import express from 'express'; -import type { Options as RateLimitOptions } from 'express-rate-limit'; -import { rateLimit } from 'express-rate-limit'; -import { verifyChallenge } from 'pkce-challenge'; -import * as z from 'zod/v4'; - -import { allowedMethods } from '../middleware/allowedMethods.js'; -import { authenticateClient } from '../middleware/clientAuth.js'; -import type { OAuthServerProvider } from '../provider.js'; + OAuthError +} from '../errors.js'; export type TokenHandlerOptions = { provider: OAuthServerProvider; diff --git a/packages/server/src/server/auth/middleware/allowedMethods.ts b/src/server/auth/middleware/allowedMethods.ts similarity index 86% rename from packages/server/src/server/auth/middleware/allowedMethods.ts rename to src/server/auth/middleware/allowedMethods.ts index 72c076ec4a..74633aa573 100644 --- a/packages/server/src/server/auth/middleware/allowedMethods.ts +++ b/src/server/auth/middleware/allowedMethods.ts @@ -1,5 +1,5 @@ -import { MethodNotAllowedError } from '@modelcontextprotocol/core'; -import type { RequestHandler } from 'express'; +import { RequestHandler } from 'express'; +import { MethodNotAllowedError } from '../errors.js'; /** * Middleware to handle unsupported HTTP methods with a 405 Method Not Allowed response. diff --git a/packages/server/src/server/auth/middleware/bearerAuth.ts b/src/server/auth/middleware/bearerAuth.ts similarity index 93% rename from packages/server/src/server/auth/middleware/bearerAuth.ts rename to src/server/auth/middleware/bearerAuth.ts index 1a16de1a93..dac6530865 100644 --- a/packages/server/src/server/auth/middleware/bearerAuth.ts +++ b/src/server/auth/middleware/bearerAuth.ts @@ -1,8 +1,7 @@ -import type { AuthInfo } from '@modelcontextprotocol/core'; -import { InsufficientScopeError, InvalidTokenError, OAuthError, ServerError } from '@modelcontextprotocol/core'; -import type { RequestHandler } from 'express'; - -import type { OAuthTokenVerifier } from '../provider.js'; +import { RequestHandler } from 'express'; +import { InsufficientScopeError, InvalidTokenError, OAuthError, ServerError } from '../errors.js'; +import { OAuthTokenVerifier } from '../provider.js'; +import { AuthInfo } from '../types.js'; export type BearerAuthMiddlewareOptions = { /** @@ -47,7 +46,7 @@ export function requireBearerAuth({ verifier, requiredScopes = [], resourceMetad } const [type, token] = authHeader.split(' '); - if (type!.toLowerCase() !== 'bearer' || !token) { + if (type.toLowerCase() !== 'bearer' || !token) { throw new InvalidTokenError("Invalid Authorization header format, expected 'Bearer TOKEN'"); } diff --git a/packages/server/src/server/auth/middleware/clientAuth.ts b/src/server/auth/middleware/clientAuth.ts similarity index 88% rename from packages/server/src/server/auth/middleware/clientAuth.ts rename to src/server/auth/middleware/clientAuth.ts index ac4bc8b795..6cc6a1923d 100644 --- a/packages/server/src/server/auth/middleware/clientAuth.ts +++ b/src/server/auth/middleware/clientAuth.ts @@ -1,9 +1,8 @@ -import type { OAuthClientInformationFull } from '@modelcontextprotocol/core'; -import { InvalidClientError, InvalidRequestError, OAuthError, ServerError } from '@modelcontextprotocol/core'; -import type { RequestHandler } from 'express'; import * as z from 'zod/v4'; - -import type { OAuthRegisteredClientsStore } from '../clients.js'; +import { RequestHandler } from 'express'; +import { OAuthRegisteredClientsStore } from '../clients.js'; +import { OAuthClientInformationFull } from '../../../shared/auth.js'; +import { InvalidRequestError, InvalidClientError, ServerError, OAuthError } from '../errors.js'; export type ClientAuthenticationMiddlewareOptions = { /** diff --git a/packages/server/src/server/auth/provider.ts b/src/server/auth/provider.ts similarity index 92% rename from packages/server/src/server/auth/provider.ts rename to src/server/auth/provider.ts index 6d27fb792b..cf1c306def 100644 --- a/packages/server/src/server/auth/provider.ts +++ b/src/server/auth/provider.ts @@ -1,7 +1,7 @@ -import type { AuthInfo, OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '@modelcontextprotocol/core'; -import type { Response } from 'express'; - -import type { OAuthRegisteredClientsStore } from './clients.js'; +import { Response } from 'express'; +import { OAuthRegisteredClientsStore } from './clients.js'; +import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../shared/auth.js'; +import { AuthInfo } from './types.js'; export type AuthorizationParams = { state?: string; diff --git a/packages/server/src/server/auth/providers/proxyProvider.ts b/src/server/auth/providers/proxyProvider.ts similarity index 93% rename from packages/server/src/server/auth/providers/proxyProvider.ts rename to src/server/auth/providers/proxyProvider.ts index 0688754c09..855856c89e 100644 --- a/packages/server/src/server/auth/providers/proxyProvider.ts +++ b/src/server/auth/providers/proxyProvider.ts @@ -1,9 +1,16 @@ -import type { AuthInfo, FetchLike, OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '@modelcontextprotocol/core'; -import { OAuthClientInformationFullSchema, OAuthTokensSchema, ServerError } from '@modelcontextprotocol/core'; -import type { Response } from 'express'; - -import type { OAuthRegisteredClientsStore } from '../clients.js'; -import type { AuthorizationParams, OAuthServerProvider } from '../provider.js'; +import { Response } from 'express'; +import { OAuthRegisteredClientsStore } from '../clients.js'; +import { + OAuthClientInformationFull, + OAuthClientInformationFullSchema, + OAuthTokenRevocationRequest, + OAuthTokens, + OAuthTokensSchema +} from '../../../shared/auth.js'; +import { AuthInfo } from '../types.js'; +import { AuthorizationParams, OAuthServerProvider } from '../provider.js'; +import { ServerError } from '../errors.js'; +import { FetchLike } from '../../../shared/transport.js'; export type ProxyEndpoints = { authorizationUrl: string; diff --git a/packages/server/src/server/auth/router.ts b/src/server/auth/router.ts similarity index 91% rename from packages/server/src/server/auth/router.ts rename to src/server/auth/router.ts index ba8b030e08..1df0be091f 100644 --- a/packages/server/src/server/auth/router.ts +++ b/src/server/auth/router.ts @@ -1,17 +1,11 @@ -import type { OAuthMetadata, OAuthProtectedResourceMetadata } from '@modelcontextprotocol/core'; -import type { RequestHandler } from 'express'; -import express from 'express'; - -import type { AuthorizationHandlerOptions } from './handlers/authorize.js'; -import { authorizationHandler } from './handlers/authorize.js'; +import express, { RequestHandler } from 'express'; +import { clientRegistrationHandler, ClientRegistrationHandlerOptions } from './handlers/register.js'; +import { tokenHandler, TokenHandlerOptions } from './handlers/token.js'; +import { authorizationHandler, AuthorizationHandlerOptions } from './handlers/authorize.js'; +import { revocationHandler, RevocationHandlerOptions } from './handlers/revoke.js'; import { metadataHandler } from './handlers/metadata.js'; -import type { ClientRegistrationHandlerOptions } from './handlers/register.js'; -import { clientRegistrationHandler } from './handlers/register.js'; -import type { RevocationHandlerOptions } from './handlers/revoke.js'; -import { revocationHandler } from './handlers/revoke.js'; -import type { TokenHandlerOptions } from './handlers/token.js'; -import { tokenHandler } from './handlers/token.js'; -import type { OAuthServerProvider } from './provider.js'; +import { OAuthServerProvider } from './provider.js'; +import { OAuthMetadata, OAuthProtectedResourceMetadata } from '../../shared/auth.js'; // Check for dev mode flag that allows HTTP issuer URLs (for development/testing only) const allowInsecureIssuerUrl = diff --git a/src/server/auth/types.ts b/src/server/auth/types.ts new file mode 100644 index 0000000000..a38a7e7508 --- /dev/null +++ b/src/server/auth/types.ts @@ -0,0 +1,36 @@ +/** + * Information about a validated access token, provided to request handlers. + */ +export interface AuthInfo { + /** + * The access token. + */ + token: string; + + /** + * The client ID associated with this token. + */ + clientId: string; + + /** + * Scopes associated with this token. + */ + scopes: string[]; + + /** + * When the token expires (in seconds since epoch). + */ + expiresAt?: number; + + /** + * The RFC 8707 resource server identifier for which this token is valid. + * If set, this MUST match the MCP server's resource identifier (minus hash fragment). + */ + resource?: URL; + + /** + * Additional data associated with the token. + * This field should be used for any additional data that needs to be attached to the auth info. + */ + extra?: Record; +} diff --git a/packages/server/src/server/completable.ts b/src/server/completable.ts similarity index 96% rename from packages/server/src/server/completable.ts rename to src/server/completable.ts index 7174bff376..be067ac55a 100644 --- a/packages/server/src/server/completable.ts +++ b/src/server/completable.ts @@ -1,4 +1,4 @@ -import type { AnySchema, SchemaInput } from '@modelcontextprotocol/core'; +import { AnySchema, SchemaInput } from './zod-compat.js'; export const COMPLETABLE_SYMBOL: unique symbol = Symbol.for('mcp.completable'); diff --git a/packages/server/src/server/express.ts b/src/server/express.ts similarity index 97% rename from packages/server/src/server/express.ts rename to src/server/express.ts index ff23cde85d..a542acd7ac 100644 --- a/packages/server/src/server/express.ts +++ b/src/server/express.ts @@ -1,6 +1,4 @@ -import type { Express } from 'express'; -import express from 'express'; - +import express, { Express } from 'express'; import { hostHeaderValidation, localhostHostValidation } from './middleware/hostHeaderValidation.js'; /** diff --git a/packages/server/src/server/server.ts b/src/server/index.ts similarity index 94% rename from packages/server/src/server/server.ts rename to src/server/index.ts index 8132e342be..aa1a62d004 100644 --- a/packages/server/src/server/server.ts +++ b/src/server/index.ts @@ -1,68 +1,61 @@ -import type { - AnyObjectSchema, - ClientCapabilities, - CreateMessageRequest, - CreateMessageRequestParamsBase, - CreateMessageRequestParamsWithTools, - CreateMessageResult, - CreateMessageResultWithTools, - ElicitRequestFormParams, - ElicitRequestURLParams, - ElicitResult, - Implementation, - InitializeRequest, - InitializeResult, - JsonSchemaType, - jsonSchemaValidator, - ListRootsRequest, - LoggingLevel, - LoggingMessageNotification, - Notification, - NotificationOptions, - ProtocolOptions, - Request, - RequestHandlerExtra, - RequestOptions, - ResourceUpdatedNotification, - Result, - SchemaOutput, - ServerCapabilities, - ServerNotification, - ServerRequest, - ServerResult, - ToolResultContent, - ToolUseContent, - ZodV3Internal, - ZodV4Internal -} from '@modelcontextprotocol/core'; +import { mergeCapabilities, Protocol, type NotificationOptions, type ProtocolOptions, type RequestOptions } from '../shared/protocol.js'; import { - AjvJsonSchemaValidator, - assertClientRequestTaskCapability, - assertToolsCallTaskCapability, - CallToolRequestSchema, - CallToolResultSchema, + type ClientCapabilities, + type CreateMessageRequest, + type CreateMessageResult, CreateMessageResultSchema, + type CreateMessageResultWithTools, CreateMessageResultWithToolsSchema, - CreateTaskResultSchema, + type CreateMessageRequestParamsBase, + type CreateMessageRequestParamsWithTools, + type ElicitRequestFormParams, + type ElicitRequestURLParams, + type ElicitResult, ElicitResultSchema, EmptyResultSchema, ErrorCode, - getObjectShape, + type Implementation, InitializedNotificationSchema, + type InitializeRequest, InitializeRequestSchema, - isZ4Schema, + type InitializeResult, LATEST_PROTOCOL_VERSION, + type ListRootsRequest, ListRootsResultSchema, + type LoggingLevel, LoggingLevelSchema, + type LoggingMessageNotification, McpError, - mergeCapabilities, - Protocol, - safeParse, + type Notification, + type Request, + type ResourceUpdatedNotification, + type Result, + type ServerCapabilities, + type ServerNotification, + type ServerRequest, + type ServerResult, SetLevelRequestSchema, - SUPPORTED_PROTOCOL_VERSIONS -} from '@modelcontextprotocol/core'; - + SUPPORTED_PROTOCOL_VERSIONS, + type ToolResultContent, + type ToolUseContent, + CallToolRequestSchema, + CallToolResultSchema, + CreateTaskResultSchema +} from '../types.js'; +import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; +import type { JsonSchemaType, jsonSchemaValidator } from '../validation/types.js'; +import { + AnyObjectSchema, + getObjectShape, + isZ4Schema, + safeParse, + SchemaOutput, + type ZodV3Internal, + type ZodV4Internal +} from './zod-compat.js'; +import { RequestHandlerExtra } from '../shared/protocol.js'; import { ExperimentalServerTasks } from '../experimental/tasks/server.js'; +import { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js'; export type ServerOptions = ProtocolOptions & { /** @@ -516,7 +509,7 @@ export class Server< // These may appear even without tools/toolChoice in the current request when // a previous sampling request returned tool_use and this is a follow-up with results. if (params.messages.length > 0) { - const lastMessage = params.messages[params.messages.length - 1]!; + const lastMessage = params.messages[params.messages.length - 1]; const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; const hasToolResults = lastContent.some(c => c.type === 'tool_result'); diff --git a/packages/server/src/server/mcp.ts b/src/server/mcp.ts similarity index 99% rename from packages/server/src/server/mcp.ts rename to src/server/mcp.ts index 7cd06a5411..ed41e21a3e 100644 --- a/packages/server/src/server/mcp.ts +++ b/src/server/mcp.ts @@ -1,71 +1,69 @@ -import type { - AnyObjectSchema, +import { Server, ServerOptions } from './index.js'; +import { AnySchema, - BaseMetadata, - CallToolRequest, + AnyObjectSchema, + ZodRawShapeCompat, + SchemaOutput, + ShapeOutput, + normalizeObjectSchema, + safeParseAsync, + getObjectShape, + objectFromShape, + getParseErrorMessage, + getSchemaDescription, + isSchemaOptional, + getLiteralValue +} from './zod-compat.js'; +import { toJsonSchemaCompat } from './zod-json-schema-compat.js'; +import { + Implementation, + Tool, + ListToolsResult, CallToolResult, - CompleteRequestPrompt, - CompleteRequestResourceTemplate, + McpError, + ErrorCode, CompleteResult, - CreateTaskResult, - GetPromptResult, - Implementation, - ListPromptsResult, + PromptReference, + ResourceTemplateReference, + BaseMetadata, + Resource, ListResourcesResult, - ListToolsResult, - LoggingMessageNotification, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + ListToolsRequestSchema, + CallToolRequestSchema, + ListResourcesRequestSchema, + ListPromptsRequestSchema, + GetPromptRequestSchema, + CompleteRequestSchema, + ListPromptsResult, Prompt, PromptArgument, - PromptReference, + GetPromptResult, ReadResourceResult, - RequestHandlerExtra, - Resource, - ResourceTemplateReference, - Result, - SchemaOutput, - SecurityScheme, - ServerNotification, ServerRequest, - ShapeOutput, - Tool, + ServerNotification, ToolAnnotations, - ToolExecution, - Transport, - Variables, - ZodRawShapeCompat -} from '@modelcontextprotocol/core'; -import { + SecurityScheme, + LoggingMessageNotification, + CreateTaskResult, + Result, + CompleteRequestPrompt, + CompleteRequestResourceTemplate, assertCompleteRequestPrompt, assertCompleteRequestResourceTemplate, - CallToolRequestSchema, - CompleteRequestSchema, - ErrorCode, - getLiteralValue, - getObjectShape, - getParseErrorMessage, - GetPromptRequestSchema, - getSchemaDescription, - isSchemaOptional, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ListToolsRequestSchema, - McpError, - normalizeObjectSchema, - objectFromShape, - ReadResourceRequestSchema, - safeParseAsync, - toJsonSchemaCompat, - UriTemplate, - validateAndWarnToolName -} from '@modelcontextprotocol/core'; -import { ZodOptional } from 'zod'; - -import type { ToolTaskHandler } from '../experimental/tasks/interfaces.js'; + CallToolRequest, + ToolExecution +} from '../types.js'; +import { isCompletable, getCompleter } from './completable.js'; +import { UriTemplate, Variables } from '../shared/uriTemplate.js'; +import { RequestHandlerExtra } from '../shared/protocol.js'; +import { Transport } from '../shared/transport.js'; + +import { validateAndWarnToolName } from '../shared/toolNameValidation.js'; import { ExperimentalMcpServerTasks } from '../experimental/tasks/mcp-server.js'; -import { getCompleter, isCompletable } from './completable.js'; -import type { ServerOptions } from './server.js'; -import { Server } from './server.js'; +import type { ToolTaskHandler } from '../experimental/tasks/interfaces.js'; +import { ZodOptional } from 'zod'; /** * High-level MCP server that provides a simpler API for working with resources, tools, and prompts. diff --git a/packages/server/src/server/middleware/hostHeaderValidation.ts b/src/server/middleware/hostHeaderValidation.ts similarity index 96% rename from packages/server/src/server/middleware/hostHeaderValidation.ts rename to src/server/middleware/hostHeaderValidation.ts index f46178db33..165003635b 100644 --- a/packages/server/src/server/middleware/hostHeaderValidation.ts +++ b/src/server/middleware/hostHeaderValidation.ts @@ -1,4 +1,4 @@ -import type { NextFunction, Request, RequestHandler, Response } from 'express'; +import { Request, Response, NextFunction, RequestHandler } from 'express'; /** * Express middleware for DNS rebinding protection. diff --git a/packages/server/src/server/sse.ts b/src/server/sse.ts similarity index 96% rename from packages/server/src/server/sse.ts rename to src/server/sse.ts index 4fd0fa1d6d..b7450a09ed 100644 --- a/packages/server/src/server/sse.ts +++ b/src/server/sse.ts @@ -1,11 +1,11 @@ import { randomUUID } from 'node:crypto'; -import type { IncomingMessage, ServerResponse } from 'node:http'; -import { URL } from 'node:url'; - -import type { AuthInfo, JSONRPCMessage, MessageExtraInfo, RequestInfo, Transport } from '@modelcontextprotocol/core'; -import { JSONRPCMessageSchema } from '@modelcontextprotocol/core'; -import contentType from 'content-type'; +import { IncomingMessage, ServerResponse } from 'node:http'; +import { Transport } from '../shared/transport.js'; +import { JSONRPCMessage, JSONRPCMessageSchema, MessageExtraInfo, RequestInfo } from '../types.js'; import getRawBody from 'raw-body'; +import contentType from 'content-type'; +import { AuthInfo } from './auth/types.js'; +import { URL } from 'node:url'; const MAXIMUM_MESSAGE_SIZE = '4mb'; diff --git a/packages/server/src/server/stdio.ts b/src/server/stdio.ts similarity index 92% rename from packages/server/src/server/stdio.ts rename to src/server/stdio.ts index b539632c15..e552af0fa1 100644 --- a/packages/server/src/server/stdio.ts +++ b/src/server/stdio.ts @@ -1,8 +1,8 @@ import process from 'node:process'; -import type { Readable, Writable } from 'node:stream'; - -import type { JSONRPCMessage, Transport } from '@modelcontextprotocol/core'; -import { ReadBuffer, serializeMessage } from '@modelcontextprotocol/core'; +import { Readable, Writable } from 'node:stream'; +import { ReadBuffer, serializeMessage } from '../shared/stdio.js'; +import { JSONRPCMessage } from '../types.js'; +import { Transport } from '../shared/transport.js'; /** * Server transport for stdio: this communicates with an MCP client by reading from the current process' stdin and writing to stdout. diff --git a/src/server/streamableHttp.ts b/src/server/streamableHttp.ts new file mode 100644 index 0000000000..35e7f64e75 --- /dev/null +++ b/src/server/streamableHttp.ts @@ -0,0 +1,956 @@ +import { IncomingMessage, ServerResponse } from 'node:http'; +import { Transport } from '../shared/transport.js'; +import { + MessageExtraInfo, + RequestInfo, + isInitializeRequest, + isJSONRPCError, + isJSONRPCRequest, + isJSONRPCResponse, + JSONRPCMessage, + JSONRPCMessageSchema, + RequestId, + SUPPORTED_PROTOCOL_VERSIONS, + DEFAULT_NEGOTIATED_PROTOCOL_VERSION +} from '../types.js'; +import getRawBody from 'raw-body'; +import contentType from 'content-type'; +import { randomUUID } from 'node:crypto'; +import { AuthInfo } from './auth/types.js'; + +const MAXIMUM_MESSAGE_SIZE = '4mb'; + +export type StreamId = string; +export type EventId = string; + +/** + * Interface for resumability support via event storage + */ +export interface EventStore { + /** + * Stores an event for later retrieval + * @param streamId ID of the stream the event belongs to + * @param message The JSON-RPC message to store + * @returns The generated event ID for the stored event + */ + storeEvent(streamId: StreamId, message: JSONRPCMessage): Promise; + + /** + * Get the stream ID associated with a given event ID. + * @param eventId The event ID to look up + * @returns The stream ID, or undefined if not found + * + * Optional: If not provided, the SDK will use the streamId returned by + * replayEventsAfter for stream mapping. + */ + getStreamIdForEventId?(eventId: EventId): Promise; + + replayEventsAfter( + lastEventId: EventId, + { + send + }: { + send: (eventId: EventId, message: JSONRPCMessage) => Promise; + } + ): Promise; +} + +/** + * Configuration options for StreamableHTTPServerTransport + */ +export interface StreamableHTTPServerTransportOptions { + /** + * Function that generates a session ID for the transport. + * The session ID SHOULD be globally unique and cryptographically secure (e.g., a securely generated UUID, a JWT, or a cryptographic hash) + * + * Return undefined to disable session management. + */ + sessionIdGenerator: (() => string) | undefined; + + /** + * A callback for session initialization events + * This is called when the server initializes a new session. + * Useful in cases when you need to register multiple mcp sessions + * and need to keep track of them. + * @param sessionId The generated session ID + */ + onsessioninitialized?: (sessionId: string) => void | Promise; + + /** + * A callback for session close events + * This is called when the server closes a session due to a DELETE request. + * Useful in cases when you need to clean up resources associated with the session. + * Note that this is different from the transport closing, if you are handling + * HTTP requests from multiple nodes you might want to close each + * StreamableHTTPServerTransport after a request is completed while still keeping the + * session open/running. + * @param sessionId The session ID that was closed + */ + onsessionclosed?: (sessionId: string) => void | Promise; + + /** + * If true, the server will return JSON responses instead of starting an SSE stream. + * This can be useful for simple request/response scenarios without streaming. + * Default is false (SSE streams are preferred). + */ + enableJsonResponse?: boolean; + + /** + * Event store for resumability support + * If provided, resumability will be enabled, allowing clients to reconnect and resume messages + */ + eventStore?: EventStore; + + /** + * List of allowed host header values for DNS rebinding protection. + * If not specified, host validation is disabled. + * @deprecated Use the `hostHeaderValidation` middleware from `@modelcontextprotocol/sdk/server/middleware/hostHeaderValidation.js` instead, + * or use `createMcpExpressApp` from `@modelcontextprotocol/sdk/server/express.js` which includes localhost protection by default. + */ + allowedHosts?: string[]; + + /** + * List of allowed origin header values for DNS rebinding protection. + * If not specified, origin validation is disabled. + * @deprecated Use the `hostHeaderValidation` middleware from `@modelcontextprotocol/sdk/server/middleware/hostHeaderValidation.js` instead, + * or use `createMcpExpressApp` from `@modelcontextprotocol/sdk/server/express.js` which includes localhost protection by default. + */ + allowedOrigins?: string[]; + + /** + * Enable DNS rebinding protection (requires allowedHosts and/or allowedOrigins to be configured). + * Default is false for backwards compatibility. + * @deprecated Use the `hostHeaderValidation` middleware from `@modelcontextprotocol/sdk/server/middleware/hostHeaderValidation.js` instead, + * or use `createMcpExpressApp` from `@modelcontextprotocol/sdk/server/express.js` which includes localhost protection by default. + */ + enableDnsRebindingProtection?: boolean; + + /** + * Retry interval in milliseconds to suggest to clients in SSE retry field. + * When set, the server will send a retry field in SSE priming events to control + * client reconnection timing for polling behavior. + */ + retryInterval?: number; +} + +/** + * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. + * It supports both SSE streaming and direct HTTP responses. + * + * Usage example: + * + * ```typescript + * // Stateful mode - server sets the session ID + * const statefulTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: () => randomUUID(), + * }); + * + * // Stateless mode - explicitly set session ID to undefined + * const statelessTransport = new StreamableHTTPServerTransport({ + * sessionIdGenerator: undefined, + * }); + * + * // Using with pre-parsed request body + * app.post('/mcp', (req, res) => { + * transport.handleRequest(req, res, req.body); + * }); + * ``` + * + * In stateful mode: + * - Session ID is generated and included in response headers + * - Session ID is always included in initialization responses + * - Requests with invalid session IDs are rejected with 404 Not Found + * - Non-initialization requests without a session ID are rejected with 400 Bad Request + * - State is maintained in-memory (connections, message history) + * + * In stateless mode: + * - No Session ID is included in any responses + * - No session validation is performed + */ +export class StreamableHTTPServerTransport implements Transport { + // when sessionId is not set (undefined), it means the transport is in stateless mode + private sessionIdGenerator: (() => string) | undefined; + private _started: boolean = false; + private _streamMapping: Map = new Map(); + private _requestToStreamMapping: Map = new Map(); + private _requestResponseMap: Map = new Map(); + private _initialized: boolean = false; + private _enableJsonResponse: boolean = false; + private _standaloneSseStreamId: string = '_GET_stream'; + private _eventStore?: EventStore; + private _onsessioninitialized?: (sessionId: string) => void | Promise; + private _onsessionclosed?: (sessionId: string) => void | Promise; + private _allowedHosts?: string[]; + private _allowedOrigins?: string[]; + private _enableDnsRebindingProtection: boolean; + private _retryInterval?: number; + + sessionId?: string; + onclose?: () => void; + onerror?: (error: Error) => void; + onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void; + + constructor(options: StreamableHTTPServerTransportOptions) { + this.sessionIdGenerator = options.sessionIdGenerator; + this._enableJsonResponse = options.enableJsonResponse ?? false; + this._eventStore = options.eventStore; + this._onsessioninitialized = options.onsessioninitialized; + this._onsessionclosed = options.onsessionclosed; + this._allowedHosts = options.allowedHosts; + this._allowedOrigins = options.allowedOrigins; + this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; + this._retryInterval = options.retryInterval; + } + + /** + * Starts the transport. This is required by the Transport interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + async start(): Promise { + if (this._started) { + throw new Error('Transport already started'); + } + this._started = true; + } + + /** + * Validates request headers for DNS rebinding protection. + * @returns Error message if validation fails, undefined if validation passes. + */ + private validateRequestHeaders(req: IncomingMessage): string | undefined { + // Skip validation if protection is not enabled + if (!this._enableDnsRebindingProtection) { + return undefined; + } + + // Validate Host header if allowedHosts is configured + if (this._allowedHosts && this._allowedHosts.length > 0) { + const hostHeader = req.headers.host; + if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { + return `Invalid Host header: ${hostHeader}`; + } + } + + // Validate Origin header if allowedOrigins is configured + if (this._allowedOrigins && this._allowedOrigins.length > 0) { + const originHeader = req.headers.origin; + if (originHeader && !this._allowedOrigins.includes(originHeader)) { + return `Invalid Origin header: ${originHeader}`; + } + } + + return undefined; + } + + /** + * Handles an incoming HTTP request, whether GET or POST + */ + async handleRequest(req: IncomingMessage & { auth?: AuthInfo }, res: ServerResponse, parsedBody?: unknown): Promise { + // Validate request headers for DNS rebinding protection + const validationError = this.validateRequestHeaders(req); + if (validationError) { + res.writeHead(403).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: validationError + }, + id: null + }) + ); + this.onerror?.(new Error(validationError)); + return; + } + + if (req.method === 'POST') { + await this.handlePostRequest(req, res, parsedBody); + } else if (req.method === 'GET') { + await this.handleGetRequest(req, res); + } else if (req.method === 'DELETE') { + await this.handleDeleteRequest(req, res); + } else { + await this.handleUnsupportedRequest(res); + } + } + + /** + * Writes a priming event to establish resumption capability. + * Only sends if eventStore is configured (opt-in for resumability) and + * the client's protocol version supports empty SSE data (>= 2025-11-25). + */ + private async _maybeWritePrimingEvent(res: ServerResponse, streamId: string, protocolVersion: string): Promise { + if (!this._eventStore) { + return; + } + + // Priming events have empty data which older clients cannot handle. + // Only send priming events to clients with protocol version >= 2025-11-25 + // which includes the fix for handling empty SSE data. + if (protocolVersion < '2025-11-25') { + return; + } + + const primingEventId = await this._eventStore.storeEvent(streamId, {} as JSONRPCMessage); + + let primingEvent = `id: ${primingEventId}\ndata: \n\n`; + if (this._retryInterval !== undefined) { + primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; + } + res.write(primingEvent); + } + + /** + * Handles GET requests for SSE stream + */ + private async handleGetRequest(req: IncomingMessage, res: ServerResponse): Promise { + // The client MUST include an Accept header, listing text/event-stream as a supported content type. + const acceptHeader = req.headers.accept; + if (!acceptHeader?.includes('text/event-stream')) { + res.writeHead(406).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Not Acceptable: Client must accept text/event-stream' + }, + id: null + }) + ); + return; + } + + // If an Mcp-Session-Id is returned by the server during initialization, + // clients using the Streamable HTTP transport MUST include it + // in the Mcp-Session-Id header on all of their subsequent HTTP requests. + if (!this.validateSession(req, res)) { + return; + } + if (!this.validateProtocolVersion(req, res)) { + return; + } + // Handle resumability: check for Last-Event-ID header + if (this._eventStore) { + const lastEventId = req.headers['last-event-id'] as string | undefined; + if (lastEventId) { + await this.replayEvents(lastEventId, res); + return; + } + } + + // The server MUST either return Content-Type: text/event-stream in response to this HTTP GET, + // or else return HTTP 405 Method Not Allowed + const headers: Record = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive' + }; + + // After initialization, always include the session ID if we have one + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + + // Check if there's already an active standalone SSE stream for this session + if (this._streamMapping.get(this._standaloneSseStreamId) !== undefined) { + // Only one GET SSE stream is allowed per session + res.writeHead(409).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Conflict: Only one SSE stream is allowed per session' + }, + id: null + }) + ); + return; + } + + // We need to send headers immediately as messages will arrive much later, + // otherwise the client will just wait for the first message + res.writeHead(200, headers).flushHeaders(); + + // Assign the response to the standalone SSE stream + this._streamMapping.set(this._standaloneSseStreamId, res); + // Set up close handler for client disconnects + res.on('close', () => { + this._streamMapping.delete(this._standaloneSseStreamId); + }); + + // Add error handler for standalone SSE stream + res.on('error', error => { + this.onerror?.(error as Error); + }); + } + + /** + * Replays events that would have been sent after the specified event ID + * Only used when resumability is enabled + */ + private async replayEvents(lastEventId: string, res: ServerResponse): Promise { + if (!this._eventStore) { + return; + } + try { + // If getStreamIdForEventId is available, use it for conflict checking + let streamId: string | undefined; + if (this._eventStore.getStreamIdForEventId) { + streamId = await this._eventStore.getStreamIdForEventId(lastEventId); + + if (!streamId) { + res.writeHead(400).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Invalid event ID format' + }, + id: null + }) + ); + return; + } + + // Check conflict with the SAME streamId we'll use for mapping + if (this._streamMapping.get(streamId) !== undefined) { + res.writeHead(409).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Conflict: Stream already has an active connection' + }, + id: null + }) + ); + return; + } + } + + const headers: Record = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + Connection: 'keep-alive' + }; + + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + res.writeHead(200, headers).flushHeaders(); + + // Replay events - returns the streamId for backwards compatibility + const replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { + send: async (eventId: string, message: JSONRPCMessage) => { + if (!this.writeSSEEvent(res, message, eventId)) { + this.onerror?.(new Error('Failed replay events')); + res.end(); + } + } + }); + + this._streamMapping.set(replayedStreamId, res); + + // Set up close handler for client disconnects + res.on('close', () => { + this._streamMapping.delete(replayedStreamId); + }); + + // Add error handler for replay stream + res.on('error', error => { + this.onerror?.(error as Error); + }); + } catch (error) { + this.onerror?.(error as Error); + } + } + + /** + * Writes an event to the SSE stream with proper formatting + */ + private writeSSEEvent(res: ServerResponse, message: JSONRPCMessage, eventId?: string): boolean { + let eventData = `event: message\n`; + // Include event ID if provided - this is important for resumability + if (eventId) { + eventData += `id: ${eventId}\n`; + } + eventData += `data: ${JSON.stringify(message)}\n\n`; + + return res.write(eventData); + } + + /** + * Handles unsupported requests (PUT, PATCH, etc.) + */ + private async handleUnsupportedRequest(res: ServerResponse): Promise { + res.writeHead(405, { + Allow: 'GET, POST, DELETE' + }).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Method not allowed.' + }, + id: null + }) + ); + } + + /** + * Handles POST requests containing JSON-RPC messages + */ + private async handlePostRequest(req: IncomingMessage & { auth?: AuthInfo }, res: ServerResponse, parsedBody?: unknown): Promise { + try { + // Validate the Accept header + const acceptHeader = req.headers.accept; + // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types. + if (!acceptHeader?.includes('application/json') || !acceptHeader.includes('text/event-stream')) { + res.writeHead(406).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Not Acceptable: Client must accept both application/json and text/event-stream' + }, + id: null + }) + ); + return; + } + + const ct = req.headers['content-type']; + if (!ct || !ct.includes('application/json')) { + res.writeHead(415).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Unsupported Media Type: Content-Type must be application/json' + }, + id: null + }) + ); + return; + } + + const authInfo: AuthInfo | undefined = req.auth; + const requestInfo: RequestInfo = { headers: req.headers }; + + let rawMessage; + if (parsedBody !== undefined) { + rawMessage = parsedBody; + } else { + const parsedCt = contentType.parse(ct); + const body = await getRawBody(req, { + limit: MAXIMUM_MESSAGE_SIZE, + encoding: parsedCt.parameters.charset ?? 'utf-8' + }); + rawMessage = JSON.parse(body.toString()); + } + + let messages: JSONRPCMessage[]; + + // handle batch and single messages + if (Array.isArray(rawMessage)) { + messages = rawMessage.map(msg => JSONRPCMessageSchema.parse(msg)); + } else { + messages = [JSONRPCMessageSchema.parse(rawMessage)]; + } + + // Check if this is an initialization request + // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/ + const isInitializationRequest = messages.some(isInitializeRequest); + if (isInitializationRequest) { + // If it's a server with session management and the session ID is already set we should reject the request + // to avoid re-initialization. + if (this._initialized && this.sessionId !== undefined) { + res.writeHead(400).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32600, + message: 'Invalid Request: Server already initialized' + }, + id: null + }) + ); + return; + } + if (messages.length > 1) { + res.writeHead(400).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32600, + message: 'Invalid Request: Only one initialization request is allowed' + }, + id: null + }) + ); + return; + } + this.sessionId = this.sessionIdGenerator?.(); + this._initialized = true; + + // If we have a session ID and an onsessioninitialized handler, call it immediately + // This is needed in cases where the server needs to keep track of multiple sessions + if (this.sessionId && this._onsessioninitialized) { + await Promise.resolve(this._onsessioninitialized(this.sessionId)); + } + } + if (!isInitializationRequest) { + // If an Mcp-Session-Id is returned by the server during initialization, + // clients using the Streamable HTTP transport MUST include it + // in the Mcp-Session-Id header on all of their subsequent HTTP requests. + if (!this.validateSession(req, res)) { + return; + } + // Mcp-Protocol-Version header is required for all requests after initialization. + if (!this.validateProtocolVersion(req, res)) { + return; + } + } + + // check if it contains requests + const hasRequests = messages.some(isJSONRPCRequest); + + if (!hasRequests) { + // if it only contains notifications or responses, return 202 + res.writeHead(202).end(); + + // handle each message + for (const message of messages) { + this.onmessage?.(message, { authInfo, requestInfo }); + } + } else if (hasRequests) { + // The default behavior is to use SSE streaming + // but in some cases server will return JSON responses + const streamId = randomUUID(); + + // Extract protocol version for priming event decision. + // For initialize requests, get from request params. + // For other requests, get from header (already validated). + const initRequest = messages.find(m => isInitializeRequest(m)); + const clientProtocolVersion = initRequest + ? initRequest.params.protocolVersion + : ((req.headers['mcp-protocol-version'] as string) ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION); + + if (!this._enableJsonResponse) { + const headers: Record = { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive' + }; + + // After initialization, always include the session ID if we have one + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + + res.writeHead(200, headers); + + await this._maybeWritePrimingEvent(res, streamId, clientProtocolVersion); + } + // Store the response for this request to send messages back through this connection + // We need to track by request ID to maintain the connection + for (const message of messages) { + if (isJSONRPCRequest(message)) { + this._streamMapping.set(streamId, res); + this._requestToStreamMapping.set(message.id, streamId); + } + } + // Set up close handler for client disconnects + res.on('close', () => { + this._streamMapping.delete(streamId); + }); + + // Add error handler for stream write errors + res.on('error', error => { + this.onerror?.(error as Error); + }); + + // handle each message + for (const message of messages) { + // Build closeSSEStream callback for requests when eventStore is configured + // AND client supports resumability (protocol version >= 2025-11-25). + // Old clients can't resume if the stream is closed early because they + // didn't receive a priming event with an event ID. + let closeSSEStream: (() => void) | undefined; + let closeStandaloneSSEStream: (() => void) | undefined; + if (isJSONRPCRequest(message) && this._eventStore && clientProtocolVersion >= '2025-11-25') { + closeSSEStream = () => { + this.closeSSEStream(message.id); + }; + closeStandaloneSSEStream = () => { + this.closeStandaloneSSEStream(); + }; + } + + this.onmessage?.(message, { authInfo, requestInfo, closeSSEStream, closeStandaloneSSEStream }); + } + // The server SHOULD NOT close the SSE stream before sending all JSON-RPC responses + // This will be handled by the send() method when responses are ready + } + } catch (error) { + // return JSON-RPC formatted error + res.writeHead(400).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32700, + message: 'Parse error', + data: String(error) + }, + id: null + }) + ); + this.onerror?.(error as Error); + } + } + + /** + * Handles DELETE requests to terminate sessions + */ + private async handleDeleteRequest(req: IncomingMessage, res: ServerResponse): Promise { + if (!this.validateSession(req, res)) { + return; + } + if (!this.validateProtocolVersion(req, res)) { + return; + } + await Promise.resolve(this._onsessionclosed?.(this.sessionId!)); + await this.close(); + res.writeHead(200).end(); + } + + /** + * Validates session ID for non-initialization requests + * Returns true if the session is valid, false otherwise + */ + private validateSession(req: IncomingMessage, res: ServerResponse): boolean { + if (this.sessionIdGenerator === undefined) { + // If the sessionIdGenerator ID is not set, the session management is disabled + // and we don't need to validate the session ID + return true; + } + if (!this._initialized) { + // If the server has not been initialized yet, reject all requests + res.writeHead(400).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Server not initialized' + }, + id: null + }) + ); + return false; + } + + const sessionId = req.headers['mcp-session-id']; + + if (!sessionId) { + // Non-initialization requests without a session ID should return 400 Bad Request + res.writeHead(400).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Mcp-Session-Id header is required' + }, + id: null + }) + ); + return false; + } else if (Array.isArray(sessionId)) { + res.writeHead(400).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: 'Bad Request: Mcp-Session-Id header must be a single value' + }, + id: null + }) + ); + return false; + } else if (sessionId !== this.sessionId) { + // Reject requests with invalid session ID with 404 Not Found + res.writeHead(404).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32001, + message: 'Session not found' + }, + id: null + }) + ); + return false; + } + + return true; + } + + private validateProtocolVersion(req: IncomingMessage, res: ServerResponse): boolean { + let protocolVersion = req.headers['mcp-protocol-version'] ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; + if (Array.isArray(protocolVersion)) { + protocolVersion = protocolVersion[protocolVersion.length - 1]; + } + + if (!SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) { + res.writeHead(400).end( + JSON.stringify({ + jsonrpc: '2.0', + error: { + code: -32000, + message: `Bad Request: Unsupported protocol version (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(', ')})` + }, + id: null + }) + ); + return false; + } + return true; + } + + async close(): Promise { + // Close all SSE connections + this._streamMapping.forEach(response => { + response.end(); + }); + this._streamMapping.clear(); + + // Clear any pending responses + this._requestResponseMap.clear(); + this.onclose?.(); + } + + /** + * Close an SSE stream for a specific request, triggering client reconnection. + * Use this to implement polling behavior during long-running operations - + * client will reconnect after the retry interval specified in the priming event. + */ + closeSSEStream(requestId: RequestId): void { + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) return; + + const stream = this._streamMapping.get(streamId); + if (stream) { + stream.end(); + this._streamMapping.delete(streamId); + } + } + + /** + * Close the standalone GET SSE stream, triggering client reconnection. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream(): void { + const stream = this._streamMapping.get(this._standaloneSseStreamId); + if (stream) { + stream.end(); + this._streamMapping.delete(this._standaloneSseStreamId); + } + } + + async send(message: JSONRPCMessage, options?: { relatedRequestId?: RequestId }): Promise { + let requestId = options?.relatedRequestId; + if (isJSONRPCResponse(message) || isJSONRPCError(message)) { + // If the message is a response, use the request ID from the message + requestId = message.id; + } + + // Check if this message should be sent on the standalone SSE stream (no request ID) + // Ignore notifications from tools (which have relatedRequestId set) + // Those will be sent via dedicated response SSE streams + if (requestId === undefined) { + // For standalone SSE streams, we can only send requests and notifications + if (isJSONRPCResponse(message) || isJSONRPCError(message)) { + throw new Error('Cannot send a response on a standalone SSE stream unless resuming a previous client request'); + } + + // Generate and store event ID if event store is provided + // Store even if stream is disconnected so events can be replayed on reconnect + let eventId: string | undefined; + if (this._eventStore) { + // Stores the event and gets the generated event ID + eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); + } + + const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); + if (standaloneSse === undefined) { + // Stream is disconnected - event is stored for replay, nothing more to do + return; + } + + // Send the message to the standalone SSE stream + this.writeSSEEvent(standaloneSse, message, eventId); + return; + } + + // Get the response for this request + const streamId = this._requestToStreamMapping.get(requestId); + const response = this._streamMapping.get(streamId!); + if (!streamId) { + throw new Error(`No connection established for request ID: ${String(requestId)}`); + } + + if (!this._enableJsonResponse) { + // For SSE responses, generate event ID if event store is provided + let eventId: string | undefined; + + if (this._eventStore) { + eventId = await this._eventStore.storeEvent(streamId, message); + } + if (response) { + // Write the event to the response stream + this.writeSSEEvent(response, message, eventId); + } + } + + if (isJSONRPCResponse(message) || isJSONRPCError(message)) { + this._requestResponseMap.set(requestId, message); + const relatedIds = Array.from(this._requestToStreamMapping.entries()) + .filter(([_, streamId]) => this._streamMapping.get(streamId) === response) + .map(([id]) => id); + + // Check if we have responses for all requests using this connection + const allResponsesReady = relatedIds.every(id => this._requestResponseMap.has(id)); + + if (allResponsesReady) { + if (!response) { + throw new Error(`No connection established for request ID: ${String(requestId)}`); + } + if (this._enableJsonResponse) { + // All responses ready, send as JSON + const headers: Record = { + 'Content-Type': 'application/json' + }; + if (this.sessionId !== undefined) { + headers['mcp-session-id'] = this.sessionId; + } + + const responses = relatedIds.map(id => this._requestResponseMap.get(id)!); + + response.writeHead(200, headers); + if (responses.length === 1) { + response.end(JSON.stringify(responses[0])); + } else { + response.end(JSON.stringify(responses)); + } + } else { + // End the SSE stream + response.end(); + } + // Clean up + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + } + } + } +} diff --git a/packages/core/src/util/zod-compat.ts b/src/server/zod-compat.ts similarity index 96% rename from packages/core/src/util/zod-compat.ts rename to src/server/zod-compat.ts index 65daae0698..04ee5361fe 100644 --- a/packages/core/src/util/zod-compat.ts +++ b/src/server/zod-compat.ts @@ -4,8 +4,9 @@ // ---------------------------------------------------- import type * as z3 from 'zod/v3'; -import * as z3rt from 'zod/v3'; import type * as z4 from 'zod/v4/core'; + +import * as z3rt from 'zod/v3'; import * as z4mini from 'zod/v4-mini'; // --- Unified schema types --- @@ -34,6 +35,7 @@ export interface ZodV4Internal { value?: unknown; values?: unknown[]; shape?: Record | (() => Record); + description?: string; }; }; value?: unknown; @@ -218,12 +220,15 @@ export function getParseErrorMessage(error: unknown): string { /** * Gets the description from a schema, if available. * Works with both Zod v3 and v4. - * - * Both versions expose a `.description` getter that returns the description - * from their respective internal storage (v3: _def, v4: globalRegistry). */ export function getSchemaDescription(schema: AnySchema): string | undefined { - return (schema as { description?: string }).description; + if (isZ4Schema(schema)) { + const v4Schema = schema as unknown as ZodV4Internal; + return v4Schema._zod?.def?.description; + } + const v3Schema = schema as unknown as ZodV3Internal; + // v3 may have description on the schema itself or in _def + return (schema as { description?: string }).description ?? v3Schema._def?.description; } /** diff --git a/packages/core/src/util/zod-json-schema-compat.ts b/src/server/zod-json-schema-compat.ts similarity index 93% rename from packages/core/src/util/zod-json-schema-compat.ts rename to src/server/zod-json-schema-compat.ts index cbb8b15e97..cde66b1772 100644 --- a/packages/core/src/util/zod-json-schema-compat.ts +++ b/src/server/zod-json-schema-compat.ts @@ -6,11 +6,11 @@ import type * as z3 from 'zod/v3'; import type * as z4c from 'zod/v4/core'; + import * as z4mini from 'zod/v4-mini'; -import { zodToJsonSchema } from 'zod-to-json-schema'; -import type { AnyObjectSchema, AnySchema } from './zod-compat.js'; -import { getLiteralValue, getObjectShape, isZ4Schema, safeParse } from './zod-compat.js'; +import { AnySchema, AnyObjectSchema, getObjectShape, safeParse, isZ4Schema, getLiteralValue } from './zod-compat.js'; +import { zodToJsonSchema } from 'zod-to-json-schema'; type JsonSchema = Record; diff --git a/packages/core/src/shared/auth-utils.ts b/src/shared/auth-utils.ts similarity index 100% rename from packages/core/src/shared/auth-utils.ts rename to src/shared/auth-utils.ts diff --git a/packages/core/src/shared/auth.ts b/src/shared/auth.ts similarity index 100% rename from packages/core/src/shared/auth.ts rename to src/shared/auth.ts diff --git a/packages/core/src/shared/metadataUtils.ts b/src/shared/metadataUtils.ts similarity index 94% rename from packages/core/src/shared/metadataUtils.ts rename to src/shared/metadataUtils.ts index 6cede430b5..18f84a4c95 100644 --- a/packages/core/src/shared/metadataUtils.ts +++ b/src/shared/metadataUtils.ts @@ -1,4 +1,4 @@ -import type { BaseMetadata } from '../types/types.js'; +import { BaseMetadata } from '../types.js'; /** * Utilities for working with BaseMetadata objects. diff --git a/packages/core/src/shared/protocol.ts b/src/shared/protocol.ts similarity index 97% rename from packages/core/src/shared/protocol.ts rename to src/shared/protocol.ts index 9c65015d14..e195478f27 100644 --- a/packages/core/src/shared/protocol.ts +++ b/src/shared/protocol.ts @@ -1,59 +1,53 @@ -import type { CreateTaskOptions, QueuedMessage, TaskMessageQueue, TaskStore } from '../experimental/tasks/interfaces.js'; -import { isTerminal } from '../experimental/tasks/interfaces.js'; -import type { - AuthInfo, - CancelledNotification, +import { AnySchema, AnyObjectSchema, SchemaOutput, safeParse } from '../server/zod-compat.js'; +import { + CancelledNotificationSchema, ClientCapabilities, - GetTaskPayloadRequest, + CreateTaskResultSchema, + ErrorCode, GetTaskRequest, - GetTaskResult, - JSONRPCErrorResponse, + GetTaskRequestSchema, + GetTaskResultSchema, + GetTaskPayloadRequest, + GetTaskPayloadRequestSchema, + ListTasksRequestSchema, + ListTasksResultSchema, + CancelTaskRequestSchema, + CancelTaskResultSchema, + isJSONRPCError, + isJSONRPCRequest, + isJSONRPCResponse, + isJSONRPCNotification, + JSONRPCError, JSONRPCNotification, JSONRPCRequest, JSONRPCResponse, - JSONRPCResultResponse, - MessageExtraInfo, + McpError, Notification, + PingRequestSchema, Progress, ProgressNotification, - RelatedTaskMetadata, + ProgressNotificationSchema, + RELATED_TASK_META_KEY, Request, RequestId, - RequestInfo, - RequestMeta, Result, ServerCapabilities, - Task, + RequestMeta, + MessageExtraInfo, + RequestInfo, + GetTaskResult, TaskCreationParams, - TaskStatusNotification -} from '../types/types.js'; -import { - CancelledNotificationSchema, - CancelTaskRequestSchema, - CancelTaskResultSchema, - CreateTaskResultSchema, - ErrorCode, - GetTaskPayloadRequestSchema, - GetTaskRequestSchema, - GetTaskResultSchema, - isJSONRPCErrorResponse, - isJSONRPCNotification, - isJSONRPCRequest, - isJSONRPCResultResponse, - isTaskAugmentedRequestParams, - ListTasksRequestSchema, - ListTasksResultSchema, - McpError, - PingRequestSchema, - ProgressNotificationSchema, - RELATED_TASK_META_KEY, + RelatedTaskMetadata, + CancelledNotification, + Task, + TaskStatusNotification, TaskStatusNotificationSchema -} from '../types/types.js'; -import type { AnyObjectSchema, AnySchema, SchemaOutput } from '../util/zod-compat.js'; -import { safeParse } from '../util/zod-compat.js'; -import { getMethodLiteral, parseWithCompat } from '../util/zod-json-schema-compat.js'; -import type { ResponseMessage } from './responseMessage.js'; -import type { Transport, TransportSendOptions } from './transport.js'; +} from '../types.js'; +import { Transport, TransportSendOptions } from './transport.js'; +import { AuthInfo } from '../server/auth/types.js'; +import { isTerminal, TaskStore, TaskMessageQueue, QueuedMessage, CreateTaskOptions } from '../experimental/tasks/interfaces.js'; +import { getMethodLiteral, parseWithCompat } from '../server/zod-json-schema-compat.js'; +import { ResponseMessage } from './responseMessage.js'; /** * Callback for progress notifications. @@ -330,7 +324,7 @@ export abstract class Protocol = new Map(); private _requestHandlerAbortControllers: Map = new Map(); private _notificationHandlers: Map Promise> = new Map(); - private _responseHandlers: Map void> = new Map(); + private _responseHandlers: Map void> = new Map(); private _progressHandlers: Map = new Map(); private _timeoutInfo: Map = new Map(); private _pendingDebouncedNotifications = new Set(); @@ -341,7 +335,7 @@ export abstract class Protocol void> = new Map(); + private _requestResolvers: Map void> = new Map(); /** * Callback for when the connection is closed for any reason. @@ -414,18 +408,18 @@ export abstract class Protocol { - if (!notification.params.requestId) { - return; - } // Handle request cancellation const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); controller?.abort(notification.params.reason); @@ -625,7 +616,7 @@ export abstract class Protocol { _onmessage?.(message, extra); - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + if (isJSONRPCResponse(message) || isJSONRPCError(message)) { this._onresponse(message); } else if (isJSONRPCRequest(message)) { this._onrequest(message, extra); @@ -684,7 +675,7 @@ export abstract class Protocol = { @@ -800,7 +791,7 @@ export abstract class Protocol; if (result.task && typeof result.task === 'object') { const task = result.task as Record; @@ -903,7 +894,7 @@ export abstract class Protocol { + const responseResolver = (response: JSONRPCResponse | Error) => { const handler = this._responseHandlers.get(messageId); if (handler) { handler(response); diff --git a/packages/core/src/shared/responseMessage.ts b/src/shared/responseMessage.ts similarity index 96% rename from packages/core/src/shared/responseMessage.ts rename to src/shared/responseMessage.ts index 8a0dcc2c22..6fefcf1f6c 100644 --- a/packages/core/src/shared/responseMessage.ts +++ b/src/shared/responseMessage.ts @@ -1,4 +1,4 @@ -import type { McpError, Result, Task } from '../types/types.js'; +import { Result, Task, McpError } from '../types.js'; /** * Base message type diff --git a/packages/core/src/shared/stdio.ts b/src/shared/stdio.ts similarity index 89% rename from packages/core/src/shared/stdio.ts rename to src/shared/stdio.ts index 49c658b969..fe14612bda 100644 --- a/packages/core/src/shared/stdio.ts +++ b/src/shared/stdio.ts @@ -1,5 +1,4 @@ -import type { JSONRPCMessage } from '../types/types.js'; -import { JSONRPCMessageSchema } from '../types/types.js'; +import { JSONRPCMessage, JSONRPCMessageSchema } from '../types.js'; /** * Buffers a continuous stdio stream into discrete JSON-RPC messages. diff --git a/packages/core/src/shared/toolNameValidation.ts b/src/shared/toolNameValidation.ts similarity index 100% rename from packages/core/src/shared/toolNameValidation.ts rename to src/shared/toolNameValidation.ts diff --git a/packages/core/src/shared/transport.ts b/src/shared/transport.ts similarity index 95% rename from packages/core/src/shared/transport.ts rename to src/shared/transport.ts index 87608f124b..f9b21bed32 100644 --- a/packages/core/src/shared/transport.ts +++ b/src/shared/transport.ts @@ -1,4 +1,4 @@ -import type { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types/types.js'; +import { JSONRPCMessage, MessageExtraInfo, RequestId } from '../types.js'; export type FetchLike = (url: string | URL, init?: RequestInit) => Promise; @@ -6,7 +6,7 @@ export type FetchLike = (url: string | URL, init?: RequestInit) => Promise for manipulation. * Handles Headers objects, arrays of tuples, and plain objects. */ -export function normalizeHeaders(headers: RequestInit['headers'] | undefined): Record { +export function normalizeHeaders(headers: HeadersInit | undefined): Record { if (!headers) return {}; if (headers instanceof Headers) { diff --git a/packages/core/src/shared/uriTemplate.ts b/src/shared/uriTemplate.ts similarity index 98% rename from packages/core/src/shared/uriTemplate.ts rename to src/shared/uriTemplate.ts index 631b65cb01..1dd57f56f6 100644 --- a/packages/core/src/shared/uriTemplate.ts +++ b/src/shared/uriTemplate.ts @@ -65,7 +65,7 @@ export class UriTemplate { const operator = this.getOperator(expr); const exploded = expr.includes('*'); const names = this.getNames(expr); - const name = names[0]!; + const name = names[0]; // Validate variable name length for (const name of names) { @@ -210,7 +210,7 @@ export class UriTemplate { if (part.operator === '?' || part.operator === '&') { for (let i = 0; i < part.names.length; i++) { - const name = part.names[i]!; + const name = part.names[i]; const prefix = i === 0 ? '\\' + part.operator : '&'; patterns.push({ pattern: prefix + this.escapeRegExp(name) + '=([^&]+)', @@ -271,8 +271,8 @@ export class UriTemplate { const result: Variables = {}; for (let i = 0; i < names.length; i++) { - const { name, exploded } = names[i]!; - const value = match[i + 1]!; + const { name, exploded } = names[i]; + const value = match[i + 1]; const cleanName = name.replace('*', ''); if (exploded && value.includes(',')) { diff --git a/src/spec.types.ts b/src/spec.types.ts new file mode 100644 index 0000000000..34b83d518b --- /dev/null +++ b/src/spec.types.ts @@ -0,0 +1,2285 @@ +/** + * This file is automatically generated from the Model Context Protocol specification. + * + * Source: https://github.com/modelcontextprotocol/modelcontextprotocol + * Pulled from: https://raw.githubusercontent.com/modelcontextprotocol/modelcontextprotocol/main/schema/draft/schema.ts + * Last updated from commit: 7dcdd69262bd488ddec071bf4eefedabf1742023 + * + * DO NOT EDIT THIS FILE MANUALLY. Changes will be overwritten by automated updates. + * To update this file, run: npm run fetch:spec-types + *//* JSON-RPC types */ + +/** + * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. + * + * @category JSON-RPC + */ +export type JSONRPCMessage = + | JSONRPCRequest + | JSONRPCNotification + | JSONRPCResponse + | JSONRPCError; + +/** @internal */ +export const LATEST_PROTOCOL_VERSION = "DRAFT-2025-v3"; +/** @internal */ +export const JSONRPC_VERSION = "2.0"; + +/** + * A progress token, used to associate progress notifications with the original request. + * + * @category Common Types + */ +export type ProgressToken = string | number; + +/** + * An opaque token used to represent a cursor for pagination. + * + * @category Common Types + */ +export type Cursor = string; + +/** + * Common params for any request. + * + * @internal + */ +export interface RequestParams { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken?: ProgressToken; + [key: string]: unknown; + }; +} + +/** @internal */ +export interface Request { + method: string; + // Allow unofficial extensions of `Request.params` without impacting `RequestParams`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + params?: { [key: string]: any }; +} + +/** @internal */ +export interface NotificationParams { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** @internal */ +export interface Notification { + method: string; + // Allow unofficial extensions of `Notification.params` without impacting `NotificationParams`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + params?: { [key: string]: any }; +} + +/** + * @category Common Types + */ +export interface Result { + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; + [key: string]: unknown; +} + +/** + * @category Common Types + */ +export interface Error { + /** + * The error type that occurred. + */ + code: number; + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string; + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data?: unknown; +} + +/** + * A uniquely identifying ID for a request in JSON-RPC. + * + * @category Common Types + */ +export type RequestId = string | number; + +/** + * A request that expects a response. + * + * @category JSON-RPC + */ +export interface JSONRPCRequest extends Request { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; +} + +/** + * A notification which does not expect a response. + * + * @category JSON-RPC + */ +export interface JSONRPCNotification extends Notification { + jsonrpc: typeof JSONRPC_VERSION; +} + +/** + * A successful (non-error) response to a request. + * + * @category JSON-RPC + */ +export interface JSONRPCResponse { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + result: Result; +} + +// Standard JSON-RPC error codes +export const PARSE_ERROR = -32700; +export const INVALID_REQUEST = -32600; +export const METHOD_NOT_FOUND = -32601; +export const INVALID_PARAMS = -32602; +export const INTERNAL_ERROR = -32603; + +// Implementation-specific JSON-RPC error codes [-32000, -32099] +/** @internal */ +export const URL_ELICITATION_REQUIRED = -32042; + +/** + * A response to a request that indicates an error occurred. + * + * @category JSON-RPC + */ +export interface JSONRPCError { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + error: Error; +} + +/** + * An error response that indicates that the server requires the client to provide additional information via an elicitation request. + * + * @internal + */ +export interface URLElicitationRequiredError + extends Omit { + error: Error & { + code: typeof URL_ELICITATION_REQUIRED; + data: { + elicitations: ElicitRequestURLParams[]; + [key: string]: unknown; + }; + }; +} + +/* Empty result */ +/** + * A response that indicates success but carries no data. + * + * @category Common Types + */ +export type EmptyResult = Result; + +/* Cancellation */ +/** + * Parameters for a `notifications/cancelled` notification. + * + * @category `notifications/cancelled` + */ +export interface CancelledNotificationParams extends NotificationParams { + /** + * The ID of the request to cancel. + * + * This MUST correspond to the ID of a request previously issued in the same direction. + */ + requestId: RequestId; + + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason?: string; +} + +/** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + * + * @category `notifications/cancelled` + */ +export interface CancelledNotification extends JSONRPCNotification { + method: "notifications/cancelled"; + params: CancelledNotificationParams; +} + +/* Initialization */ +/** + * Parameters for an `initialize` request. + * + * @category `initialize` + */ +export interface InitializeRequestParams extends RequestParams { + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string; + capabilities: ClientCapabilities; + clientInfo: Implementation; +} + +/** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + * + * @category `initialize` + */ +export interface InitializeRequest extends JSONRPCRequest { + method: "initialize"; + params: InitializeRequestParams; +} + +/** + * After receiving an initialize request from the client, the server sends this response. + * + * @category `initialize` + */ +export interface InitializeResult extends Result { + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: string; + capabilities: ServerCapabilities; + serverInfo: Implementation; + + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + instructions?: string; +} + +/** + * This notification is sent from the client to the server after initialization has finished. + * + * @category `notifications/initialized` + */ +export interface InitializedNotification extends JSONRPCNotification { + method: "notifications/initialized"; + params?: NotificationParams; +} + +/** + * 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. + * + * @category `initialize` + */ +export interface ClientCapabilities { + /** + * Experimental, non-standard capabilities that the client supports. + */ + experimental?: { [key: string]: object }; + /** + * Present if the client supports listing roots. + */ + roots?: { + /** + * Whether the client supports notifications for changes to the roots list. + */ + listChanged?: boolean; + }; + /** + * Present if the client supports sampling from an LLM. + */ + sampling?: { + /** + * Whether the client supports context inclusion via includeContext parameter. + * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). + */ + context?: object; + /** + * Whether the client supports tool use via tools and toolChoice parameters. + */ + tools?: object; + }; + /** + * Present if the client supports elicitation from the server. + */ + elicitation?: { form?: object; url?: object }; +} + +/** + * 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. + * + * @category `initialize` + */ +export interface ServerCapabilities { + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental?: { [key: string]: object }; + /** + * Present if the server supports sending log messages to the client. + */ + logging?: object; + /** + * Present if the server supports argument autocompletion suggestions. + */ + completions?: object; + /** + * Present if the server offers any prompt templates. + */ + prompts?: { + /** + * Whether this server supports notifications for changes to the prompt list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any resources to read. + */ + resources?: { + /** + * Whether this server supports subscribing to resource updates. + */ + subscribe?: boolean; + /** + * Whether this server supports notifications for changes to the resource list. + */ + listChanged?: boolean; + }; + /** + * Present if the server offers any tools to call. + */ + tools?: { + /** + * Whether this server supports notifications for changes to the tool list. + */ + listChanged?: boolean; + }; +} + +/** + * An optionally-sized icon that can be displayed in a user interface. + * + * @category Common Types + */ +export interface Icon { + /** + * A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a + * `data:` URI with Base64-encoded image data. + * + * Consumers SHOULD takes steps to ensure URLs serving icons are from the + * same domain as the client/server or a trusted domain. + * + * Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain + * executable JavaScript. + * + * @format uri + */ + src: string; + + /** + * Optional MIME type override if the source MIME type is missing or generic. + * For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`. + */ + mimeType?: string; + + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + sizes?: string[]; + + /** + * Optional specifier for the theme this icon is designed for. `light` indicates + * the icon is designed to be used with a light background, and `dark` indicates + * the icon is designed to be used with a dark background. + * + * If not provided, the client should assume the icon can be used with any theme. + */ + theme?: "light" | "dark"; +} + +/** + * Base interface to add `icons` property. + * + * @internal + */ +export interface Icons { + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons?: Icon[]; +} + +/** + * Base interface for metadata with name (identifier) and title (display name) properties. + * + * @internal + */ +export interface BaseMetadata { + /** + * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present). + */ + name: string; + + /** + * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, + * even by those unfamiliar with domain-specific terminology. + * + * If not provided, the name should be used for display (except for Tool, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title?: string; +} + +/** + * Describes the MCP implementation. + * + * @category `initialize` + */ +export interface Implementation extends BaseMetadata, Icons { + version: string; + + /** + * An optional human-readable description of what this implementation does. + * + * This can be used by clients or servers to provide context about their purpose + * and capabilities. For example, a server might describe the types of resources + * or tools it provides, while a client might describe its intended use case. + */ + description?: string; + + /** + * An optional URL of the website for this implementation. + * + * @format uri + */ + websiteUrl?: string; +} + +/* Ping */ +/** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + * + * @category `ping` + */ +export interface PingRequest extends JSONRPCRequest { + method: "ping"; + params?: RequestParams; +} + +/* Progress notifications */ + +/** + * Parameters for a `notifications/progress` notification. + * + * @category `notifications/progress` + */ +export interface ProgressNotificationParams extends NotificationParams { + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressToken; + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + * + * @TJS-type number + */ + progress: number; + /** + * Total number of items to process (or total progress required), if known. + * + * @TJS-type number + */ + total?: number; + /** + * An optional message describing the current progress. + */ + message?: string; +} + +/** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category `notifications/progress` + */ +export interface ProgressNotification extends JSONRPCNotification { + method: "notifications/progress"; + params: ProgressNotificationParams; +} + +/* Pagination */ +/** + * Common parameters for paginated requests. + * + * @internal + */ +export interface PaginatedRequestParams extends RequestParams { + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor?: Cursor; +} + +/** @internal */ +export interface PaginatedRequest extends JSONRPCRequest { + params?: PaginatedRequestParams; +} + +/** @internal */ +export interface PaginatedResult extends Result { + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor?: Cursor; +} + +/* Resources */ +/** + * Sent from the client to request a list of resources the server has. + * + * @category `resources/list` + */ +export interface ListResourcesRequest extends PaginatedRequest { + method: "resources/list"; +} + +/** + * The server's response to a resources/list request from the client. + * + * @category `resources/list` + */ +export interface ListResourcesResult extends PaginatedResult { + resources: Resource[]; +} + +/** + * Sent from the client to request a list of resource templates the server has. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesRequest extends PaginatedRequest { + method: "resources/templates/list"; +} + +/** + * The server's response to a resources/templates/list request from the client. + * + * @category `resources/templates/list` + */ +export interface ListResourceTemplatesResult extends PaginatedResult { + resourceTemplates: ResourceTemplate[]; +} + +/** + * Common parameters when working with resources. + * + * @internal + */ +export interface ResourceRequestParams extends RequestParams { + /** + * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string; +} + +/** + * Parameters for a `resources/read` request. + * + * @category `resources/read` + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface ReadResourceRequestParams extends ResourceRequestParams { } + +/** + * Sent from the client to the server, to read a specific resource URI. + * + * @category `resources/read` + */ +export interface ReadResourceRequest extends JSONRPCRequest { + method: "resources/read"; + params: ReadResourceRequestParams; +} + +/** + * The server's response to a resources/read request from the client. + * + * @category `resources/read` + */ +export interface ReadResourceResult extends Result { + contents: (TextResourceContents | BlobResourceContents)[]; +} + +/** + * 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. + * + * @category `notifications/resources/list_changed` + */ +export interface ResourceListChangedNotification extends JSONRPCNotification { + method: "notifications/resources/list_changed"; + params?: NotificationParams; +} + +/** + * Parameters for a `resources/subscribe` request. + * + * @category `resources/subscribe` + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface SubscribeRequestParams extends ResourceRequestParams { } + +/** + * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + * + * @category `resources/subscribe` + */ +export interface SubscribeRequest extends JSONRPCRequest { + method: "resources/subscribe"; + params: SubscribeRequestParams; +} + +/** + * Parameters for a `resources/unsubscribe` request. + * + * @category `resources/unsubscribe` + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface UnsubscribeRequestParams extends ResourceRequestParams { } + +/** + * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + * + * @category `resources/unsubscribe` + */ +export interface UnsubscribeRequest extends JSONRPCRequest { + method: "resources/unsubscribe"; + params: UnsubscribeRequestParams; +} + +/** + * Parameters for a `notifications/resources/updated` notification. + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotificationParams extends NotificationParams { + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + * + * @format uri + */ + uri: string; +} + +/** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + * + * @category `notifications/resources/updated` + */ +export interface ResourceUpdatedNotification extends JSONRPCNotification { + method: "notifications/resources/updated"; + params: ResourceUpdatedNotificationParams; +} + +/** + * A known resource that the server is capable of reading. + * + * @category `resources/list` + */ +export interface Resource extends BaseMetadata, Icons { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size?: number; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * A template description for resources available on the server. + * + * @category `resources/templates/list` + */ +export interface ResourceTemplate extends BaseMetadata, Icons { + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + * + * @format uri-template + */ + uriTemplate: string; + + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * The contents of a specific resource or sub-resource. + * + * @internal + */ +export interface ResourceContents { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * @category Content + */ +export interface TextResourceContents extends ResourceContents { + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string; +} + +/** + * @category Content + */ +export interface BlobResourceContents extends ResourceContents { + /** + * A base64-encoded string representing the binary data of the item. + * + * @format byte + */ + blob: string; +} + +/* Prompts */ +/** + * Sent from the client to request a list of prompts and prompt templates the server has. + * + * @category `prompts/list` + */ +export interface ListPromptsRequest extends PaginatedRequest { + method: "prompts/list"; +} + +/** + * The server's response to a prompts/list request from the client. + * + * @category `prompts/list` + */ +export interface ListPromptsResult extends PaginatedResult { + prompts: Prompt[]; +} + +/** + * Parameters for a `prompts/get` request. + * + * @category `prompts/get` + */ +export interface GetPromptRequestParams extends RequestParams { + /** + * The name of the prompt or prompt template. + */ + name: string; + /** + * Arguments to use for templating the prompt. + */ + arguments?: { [key: string]: string }; +} + +/** + * Used by the client to get a prompt provided by the server. + * + * @category `prompts/get` + */ +export interface GetPromptRequest extends JSONRPCRequest { + method: "prompts/get"; + params: GetPromptRequestParams; +} + +/** + * The server's response to a prompts/get request from the client. + * + * @category `prompts/get` + */ +export interface GetPromptResult extends Result { + /** + * An optional description for the prompt. + */ + description?: string; + messages: PromptMessage[]; +} + +/** + * A prompt or prompt template that the server offers. + * + * @category `prompts/list` + */ +export interface Prompt extends BaseMetadata, Icons { + /** + * An optional description of what this prompt provides + */ + description?: string; + + /** + * A list of arguments to use for templating the prompt. + */ + arguments?: PromptArgument[]; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * Describes an argument that a prompt can accept. + * + * @category `prompts/list` + */ +export interface PromptArgument extends BaseMetadata { + /** + * A human-readable description of the argument. + */ + description?: string; + /** + * Whether this argument must be provided. + */ + required?: boolean; +} + +/** + * The sender or recipient of messages and data in a conversation. + * + * @category Common Types + */ +export type Role = "user" | "assistant"; + +/** + * Describes a message returned as part of a prompt. + * + * This is similar to `SamplingMessage`, but also supports the embedding of + * resources from the MCP server. + * + * @category `prompts/get` + */ +export interface PromptMessage { + role: Role; + content: ContentBlock; +} + +/** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + * + * @category Content + */ +export interface ResourceLink extends Resource { + type: "resource_link"; +} + +/** + * The contents of a resource, embedded into a prompt or tool call result. + * + * It is up to the client how best to render embedded resources for the benefit + * of the LLM and/or the user. + * + * @category Content + */ +export interface EmbeddedResource { + type: "resource"; + resource: TextResourceContents | BlobResourceContents; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} +/** + * 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. + * + * @category `notifications/prompts/list_changed` + */ +export interface PromptListChangedNotification extends JSONRPCNotification { + method: "notifications/prompts/list_changed"; + params?: NotificationParams; +} + +/* Tools */ +/** + * Sent from the client to request a list of tools the server has. + * + * @category `tools/list` + */ +export interface ListToolsRequest extends PaginatedRequest { + method: "tools/list"; +} + +/** + * The server's response to a tools/list request from the client. + * + * @category `tools/list` + */ +export interface ListToolsResult extends PaginatedResult { + tools: Tool[]; +} + +/** + * The server's response to a tool call. + * + * @category `tools/call` + */ +export interface CallToolResult extends Result { + /** + * A list of content objects that represent the unstructured result of the tool call. + */ + content: ContentBlock[]; + + /** + * An optional JSON object that represents the structured result of the tool call. + */ + structuredContent?: { [key: string]: unknown }; + + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + isError?: boolean; +} + +/** + * Parameters for a `tools/call` request. + * + * @category `tools/call` + */ +export interface CallToolRequestParams extends RequestParams { + /** + * The name of the tool. + */ + name: string; + /** + * Arguments to use for the tool call. + */ + arguments?: { [key: string]: unknown }; +} + +/** + * Used by the client to invoke a tool provided by the server. + * + * @category `tools/call` + */ +export interface CallToolRequest extends JSONRPCRequest { + method: "tools/call"; + params: CallToolRequestParams; +} + +/** + * 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. + * + * @category `notifications/tools/list_changed` + */ +export interface ToolListChangedNotification extends JSONRPCNotification { + method: "notifications/tools/list_changed"; + params?: NotificationParams; +} + +/** + * Security scheme indicating no authentication is required. + * + * @category `tools/list` + */ +export interface NoAuthSecurityScheme { + type: "noauth"; +} + +/** + * Security scheme indicating OAuth 2.0 authentication is required. + * + * @category `tools/list` + */ +export interface OAuth2SecurityScheme { + type: "oauth2"; + /** + * Optional list of OAuth 2.0 scopes required for this tool. + */ + scopes?: string[]; +} + +/** + * A security scheme that can be used to authenticate tool calls. + * + * @category `tools/list` + */ +export type SecurityScheme = NoAuthSecurityScheme | OAuth2SecurityScheme; + +/** + * Additional properties describing a Tool to clients. + * + * NOTE: all properties in ToolAnnotations are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on ToolAnnotations + * received from untrusted servers. + * + * @category `tools/list` + */ +export interface ToolAnnotations { + /** + * A human-readable title for the tool. + */ + title?: string; + + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint?: boolean; + + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint?: boolean; + + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint?: boolean; + + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint?: boolean; +} + +/** + * Definition for a tool the client can call. + * + * @category `tools/list` + */ +export interface Tool extends BaseMetadata, Icons { + /** + * A human-readable description of the tool. + * + * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * A JSON Schema object defining the expected parameters for the tool. + */ + inputSchema: { + type: "object"; + properties?: { [key: string]: object }; + required?: string[]; + }; + + /** + * An optional JSON Schema object defining the structure of the tool's output returned in + * the structuredContent field of a CallToolResult. + */ + outputSchema?: { + type: "object"; + properties?: { [key: string]: object }; + required?: string[]; + }; + + /** + * Optional additional tool information. + * + * Display name precedence order is: title, annotations.title, then name. + */ + annotations?: ToolAnnotations; + + /** + * Optional list of security schemes supported by this tool. + * If missing, the tool follows the server's default authentication policy. + * If present, lists the supported authentication schemes (e.g., "noauth", "oauth2"). + */ + securitySchemes?: SecurityScheme[]; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/* Logging */ + +/** + * Parameters for a `logging/setLevel` request. + * + * @category `logging/setLevel` + */ +export interface SetLevelRequestParams extends RequestParams { + /** + * 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/message. + */ + level: LoggingLevel; +} + +/** + * A request from the client to the server, to enable or adjust logging. + * + * @category `logging/setLevel` + */ +export interface SetLevelRequest extends JSONRPCRequest { + method: "logging/setLevel"; + params: SetLevelRequestParams; +} + +/** + * Parameters for a `notifications/message` notification. + * + * @category `notifications/message` + */ +export interface LoggingMessageNotificationParams extends NotificationParams { + /** + * The severity of this log message. + */ + level: LoggingLevel; + /** + * An optional name of the logger issuing this message. + */ + logger?: string; + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown; +} + +/** + * JSONRPCNotification 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. + * + * @category `notifications/message` + */ +export interface LoggingMessageNotification extends JSONRPCNotification { + method: "notifications/message"; + params: LoggingMessageNotificationParams; +} + +/** + * The severity of a log message. + * + * These map to syslog message severities, as specified in RFC-5424: + * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 + * + * @category Common Types + */ +export type LoggingLevel = + | "debug" + | "info" + | "notice" + | "warning" + | "error" + | "critical" + | "alert" + | "emergency"; + +/* Sampling */ +/** + * Parameters for a `sampling/createMessage` request. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequestParams extends RequestParams { + messages: SamplingMessage[]; + /** + * The server's preferences for which model to select. The client MAY ignore these preferences. + */ + modelPreferences?: ModelPreferences; + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt?: string; + /** + * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. + * The client MAY ignore this request. + * + * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client + * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + */ + includeContext?: "none" | "thisServer" | "allServers"; + /** + * @TJS-type number + */ + temperature?: number; + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number; + stopSequences?: string[]; + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata?: object; + /** + * Tools that the model may use during generation. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + */ + tools?: Tool[]; + /** + * Controls how the model uses tools. + * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice?: ToolChoice; +} + +/** + * Controls tool selection behavior for sampling requests. + * + * @category `sampling/createMessage` + */ +export interface ToolChoice { + /** + * Controls the tool use ability of the model: + * - "auto": Model decides whether to use tools (default) + * - "required": Model MUST use at least one tool before completing + * - "none": Model MUST NOT use any tools + */ + mode?: "auto" | "required" | "none"; +} + +/** + * 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. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageRequest extends JSONRPCRequest { + method: "sampling/createMessage"; + params: CreateMessageRequestParams; +} + +/** + * The client's response to a sampling/create_message request from the server. The client should inform the user before returning the sampled message, to allow them to inspect the response (human in the loop) and decide whether to allow the server to see it. + * + * @category `sampling/createMessage` + */ +export interface CreateMessageResult extends Result, SamplingMessage { + /** + * The name of the model that generated the message. + */ + model: string; + + /** + * The reason why sampling stopped, if known. + * + * Standard values: + * - "endTurn": Natural end of the assistant's turn + * - "stopSequence": A stop sequence was encountered + * - "maxTokens": Maximum token limit was reached + * - "toolUse": The model wants to use one or more tools + * + * This field is an open string to allow for provider-specific stop reasons. + */ + stopReason?: "endTurn" | "stopSequence" | "maxTokens" | "toolUse" | string; +} + +/** + * Describes a message issued to or received from an LLM API. + * + * @category `sampling/createMessage` + */ +export interface SamplingMessage { + role: Role; + content: SamplingMessageContentBlock | SamplingMessageContentBlock[]; + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} +export type SamplingMessageContentBlock = + | TextContent + | ImageContent + | AudioContent + | ToolUseContent + | ToolResultContent; + +/** + * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed + * + * @category Common Types + */ +export interface Annotations { + /** + * Describes who the intended audience of this object or data is. + * + * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). + */ + audience?: Role[]; + + /** + * Describes how important this data is for operating the server. + * + * A value of 1 means "most important," and indicates that the data is + * effectively required, while 0 means "least important," and indicates that + * the data is entirely optional. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + priority?: number; + + /** + * The moment the resource was last modified, as an ISO 8601 formatted string. + * + * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"). + * + * Examples: last activity timestamp in an open file, timestamp when the resource + * was attached, etc. + */ + lastModified?: string; +} + +/** + * @category Content + */ +export type ContentBlock = + | TextContent + | ImageContent + | AudioContent + | ResourceLink + | EmbeddedResource; + +/** + * Text provided to or from an LLM. + * + * @category Content + */ +export interface TextContent { + type: "text"; + + /** + * The text content of the message. + */ + text: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * An image provided to or from an LLM. + * + * @category Content + */ +export interface ImageContent { + type: "image"; + + /** + * The base64-encoded image data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * Audio provided to or from an LLM. + * + * @category Content + */ +export interface AudioContent { + type: "audio"; + + /** + * The base64-encoded audio data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * A request from the assistant to call a tool. + * + * @category `sampling/createMessage` + */ +export interface ToolUseContent { + type: "tool_use"; + + /** + * A unique identifier for this tool use. + * + * This ID is used to match tool results to their corresponding tool uses. + */ + id: string; + + /** + * The name of the tool to call. + */ + name: string; + + /** + * The arguments to pass to the tool, conforming to the tool's input schema. + */ + input: { [key: string]: unknown }; + + /** + * Optional metadata about the tool use. Clients SHOULD preserve this field when + * including tool uses in subsequent sampling requests to enable caching optimizations. + * + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * The result of a tool use, provided by the user back to the assistant. + * + * @category `sampling/createMessage` + */ +export interface ToolResultContent { + type: "tool_result"; + + /** + * The ID of the tool use this result corresponds to. + * + * This MUST match the ID from a previous ToolUseContent. + */ + toolUseId: string; + + /** + * The unstructured result content of the tool use. + * + * This has the same format as CallToolResult.content and can include text, images, + * audio, resource links, and embedded resources. + */ + content: ContentBlock[]; + + /** + * An optional structured result object. + * + * If the tool defined an outputSchema, this SHOULD conform to that schema. + */ + structuredContent?: { [key: string]: unknown }; + + /** + * Whether the tool use resulted in an error. + * + * If true, the content typically describes the error that occurred. + * Default: false + */ + isError?: boolean; + + /** + * Optional metadata about the tool result. Clients SHOULD preserve this field when + * including tool results in subsequent sampling requests to enable caching optimizations. + * + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * The server's preferences for model selection, requested of the client during sampling. + * + * Because LLMs can vary along multiple dimensions, choosing the "best" model is + * rarely straightforward. Different models excel in different areas—some are + * faster but less capable, others are more capable but more expensive, and so + * on. This interface allows servers to express their priorities across multiple + * dimensions to help clients make an appropriate selection for their use case. + * + * These preferences are always advisory. The client MAY ignore them. It is also + * up to the client to decide how to interpret these preferences and how to + * balance them against other considerations. + * + * @category `sampling/createMessage` + */ +export interface ModelPreferences { + /** + * Optional hints to use for model selection. + * + * If multiple hints are specified, the client MUST evaluate them in order + * (such that the first match is taken). + * + * The client SHOULD prioritize these hints over the numeric priorities, but + * MAY still use the priorities to select from ambiguous matches. + */ + hints?: ModelHint[]; + + /** + * How much to prioritize cost when selecting a model. A value of 0 means cost + * is not important, while a value of 1 means cost is the most important + * factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + costPriority?: number; + + /** + * How much to prioritize sampling speed (latency) when selecting a model. A + * value of 0 means speed is not important, while a value of 1 means speed is + * the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + speedPriority?: number; + + /** + * How much to prioritize intelligence and capabilities when selecting a + * model. A value of 0 means intelligence is not important, while a value of 1 + * means intelligence is the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + intelligencePriority?: number; +} + +/** + * Hints to use for model selection. + * + * Keys not declared here are currently left unspecified by the spec and are up + * to the client to interpret. + * + * @category `sampling/createMessage` + */ +export interface ModelHint { + /** + * A hint for a model name. + * + * The client SHOULD treat this as a substring of a model name; for example: + * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` + * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. + * - `claude` should match any Claude model + * + * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: + * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` + */ + name?: string; +} + +/* Autocomplete */ +/** + * Parameters for a `completion/complete` request. + * + * @category `completion/complete` + */ +export interface CompleteRequestParams extends RequestParams { + ref: PromptReference | ResourceTemplateReference; + /** + * The argument's information + */ + argument: { + /** + * The name of the argument + */ + name: string; + /** + * The value of the argument to use for completion matching. + */ + value: string; + }; + + /** + * Additional, optional context for completions + */ + context?: { + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments?: { [key: string]: string }; + }; +} + +/** + * A request from the client to the server, to ask for completion options. + * + * @category `completion/complete` + */ +export interface CompleteRequest extends JSONRPCRequest { + method: "completion/complete"; + params: CompleteRequestParams; +} + +/** + * The server's response to a completion/complete request + * + * @category `completion/complete` + */ +export interface CompleteResult extends Result { + completion: { + /** + * An array of completion values. Must not exceed 100 items. + */ + values: string[]; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total?: number; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore?: boolean; + }; +} + +/** + * A reference to a resource or resource template definition. + * + * @category `completion/complete` + */ +export interface ResourceTemplateReference { + type: "ref/resource"; + /** + * The URI or URI template of the resource. + * + * @format uri-template + */ + uri: string; +} + +/** + * Identifies a prompt. + * + * @category `completion/complete` + */ +export interface PromptReference extends BaseMetadata { + type: "ref/prompt"; +} + +/* Roots */ +/** + * Sent from the server to request a list of root URIs from the client. Roots allow + * servers to ask for specific directories or files to operate on. A common example + * for roots is providing a set of repositories or directories a server should operate + * on. + * + * This request is typically used when the server needs to understand the file system + * structure or access specific locations that the client has permission to read from. + * + * @category `roots/list` + */ +export interface ListRootsRequest extends JSONRPCRequest { + method: "roots/list"; + params?: RequestParams; +} + +/** + * The client's response to a roots/list request from the server. + * This result contains an array of Root objects, each representing a root directory + * or file that the server can operate on. + * + * @category `roots/list` + */ +export interface ListRootsResult extends Result { + roots: Root[]; +} + +/** + * Represents a root directory or file that the server can operate on. + * + * @category `roots/list` + */ +export interface Root { + /** + * The URI identifying the root. This *must* start with file:// for now. + * This restriction may be relaxed in future versions of the protocol to allow + * other URI schemes. + * + * @format uri + */ + uri: string; + /** + * An optional name for the root. This can be used to provide a human-readable + * identifier for the root, which may be useful for display purposes or for + * referencing the root in other parts of the application. + */ + name?: string; + + /** + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + */ + _meta?: { [key: string]: unknown }; +} + +/** + * A notification from the client to the server, informing it that the list of roots has changed. + * This notification should be sent whenever the client adds, removes, or modifies any root. + * The server should then request an updated list of roots using the ListRootsRequest. + * + * @category `notifications/roots/list_changed` + */ +export interface RootsListChangedNotification extends JSONRPCNotification { + method: "notifications/roots/list_changed"; + params?: NotificationParams; +} + +/** + * The parameters for a request to elicit non-sensitive information from the user via a form in the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequestFormParams extends RequestParams { + /** + * The elicitation mode. + */ + mode?: "form"; + + /** + * The message to present to the user describing what information is being requested. + */ + message: string; + + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: { + $schema?: string; + type: "object"; + properties: { + [key: string]: PrimitiveSchemaDefinition; + }; + required?: string[]; + }; +} + +/** + * The parameters for a request to elicit information from the user via a URL in the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequestURLParams extends RequestParams { + /** + * The elicitation mode. + */ + mode: "url"; + + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: string; + + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: string; + + /** + * The URL that the user should navigate to. + * + * @format uri + */ + url: string; +} + +/** + * The parameters for a request to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export type ElicitRequestParams = + | ElicitRequestFormParams + | ElicitRequestURLParams; + +/** + * A request from the server to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ +export interface ElicitRequest extends JSONRPCRequest { + method: "elicitation/create"; + params: ElicitRequestParams; +} + +/** + * Restricted schema definitions that only allow primitive types + * without nested objects or arrays. + * + * @category `elicitation/create` + */ +export type PrimitiveSchemaDefinition = + | StringSchema + | NumberSchema + | BooleanSchema + | EnumSchema; + +/** + * @category `elicitation/create` + */ +export interface StringSchema { + type: "string"; + title?: string; + description?: string; + minLength?: number; + maxLength?: number; + format?: "email" | "uri" | "date" | "date-time"; + default?: string; +} + +/** + * @category `elicitation/create` + */ +export interface NumberSchema { + type: "number" | "integer"; + title?: string; + description?: string; + minimum?: number; + maximum?: number; + default?: number; +} + +/** + * @category `elicitation/create` + */ +export interface BooleanSchema { + type: "boolean"; + title?: string; + description?: string; + default?: boolean; +} + +/** + * Schema for single-selection enumeration without display titles for options. + * + * @category `elicitation/create` + */ +export interface UntitledSingleSelectEnumSchema { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum values to choose from. + */ + enum: string[]; + /** + * Optional default value. + */ + default?: string; +} + +/** + * Schema for single-selection enumeration with display titles for each option. + * + * @category `elicitation/create` + */ +export interface TitledSingleSelectEnumSchema { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum options with values and display labels. + */ + oneOf: Array<{ + /** + * The enum value. + */ + const: string; + /** + * Display label for this option. + */ + title: string; + }>; + /** + * Optional default value. + */ + default?: string; +} + +/** + * @category `elicitation/create` + */ +// Combined single selection enumeration +export type SingleSelectEnumSchema = + | UntitledSingleSelectEnumSchema + | TitledSingleSelectEnumSchema; + +/** + * Schema for multiple-selection enumeration without display titles for options. + * + * @category `elicitation/create` + */ +export interface UntitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for the array items. + */ + items: { + type: "string"; + /** + * Array of enum values to choose from. + */ + enum: string[]; + }; + /** + * Optional default value. + */ + default?: string[]; +} + +/** + * Schema for multiple-selection enumeration with display titles for each option. + * + * @category `elicitation/create` + */ +export interface TitledMultiSelectEnumSchema { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for array items with enum options and display labels. + */ + items: { + /** + * Array of enum options with values and display labels. + */ + anyOf: Array<{ + /** + * The constant enum value. + */ + const: string; + /** + * Display title for this option. + */ + title: string; + }>; + }; + /** + * Optional default value. + */ + default?: string[]; +} + +/** + * @category `elicitation/create` + */ +// Combined multiple selection enumeration +export type MultiSelectEnumSchema = + | UntitledMultiSelectEnumSchema + | TitledMultiSelectEnumSchema; + +/** + * Use TitledSingleSelectEnumSchema instead. + * This interface will be removed in a future version. + * + * @category `elicitation/create` + */ +export interface LegacyTitledEnumSchema { + type: "string"; + title?: string; + description?: string; + enum: string[]; + /** + * (Legacy) Display names for enum values. + * Non-standard according to JSON schema 2020-12. + */ + enumNames?: string[]; + default?: string; +} + +/** + * @category `elicitation/create` + */ +// Union type for all enum schemas +export type EnumSchema = + | SingleSelectEnumSchema + | MultiSelectEnumSchema + | LegacyTitledEnumSchema; + +/** + * The client's response to an elicitation request. + * + * @category `elicitation/create` + */ +export interface ElicitResult extends Result { + /** + * The user action in response to the elicitation. + * - "accept": User submitted the form/confirmed the action + * - "decline": User explicitly decline the action + * - "cancel": User dismissed without making an explicit choice + */ + action: "accept" | "decline" | "cancel"; + + /** + * The submitted form data, only present when action is "accept" and mode was "form". + * Contains values matching the requested schema. + * Omitted for out-of-band mode responses. + */ + content?: { [key: string]: string | number | boolean | string[] }; +} + +/** + * An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request. + * + * @category `notifications/elicitation/complete` + */ +export interface ElicitationCompleteNotification extends JSONRPCNotification { + method: "notifications/elicitation/complete"; + params: { + /** + * The ID of the elicitation that completed. + */ + elicitationId: string; + }; +} + +/* Client messages */ +/** @internal */ +export type ClientRequest = + | PingRequest + | InitializeRequest + | CompleteRequest + | SetLevelRequest + | GetPromptRequest + | ListPromptsRequest + | ListResourcesRequest + | ListResourceTemplatesRequest + | ReadResourceRequest + | SubscribeRequest + | UnsubscribeRequest + | CallToolRequest + | ListToolsRequest; + +/** @internal */ +export type ClientNotification = + | CancelledNotification + | ProgressNotification + | InitializedNotification + | RootsListChangedNotification; + +/** @internal */ +export type ClientResult = + | EmptyResult + | CreateMessageResult + | ListRootsResult + | ElicitResult; + +/* Server messages */ +/** @internal */ +export type ServerRequest = + | PingRequest + | CreateMessageRequest + | ListRootsRequest + | ElicitRequest; + +/** @internal */ +export type ServerNotification = + | CancelledNotification + | ProgressNotification + | LoggingMessageNotification + | ResourceUpdatedNotification + | ResourceListChangedNotification + | ToolListChangedNotification + | PromptListChangedNotification + | ElicitationCompleteNotification; + +/** @internal */ +export type ServerResult = + | EmptyResult + | InitializeResult + | CompleteResult + | GetPromptResult + | ListPromptsResult + | ListResourceTemplatesResult + | ListResourcesResult + | ReadResourceResult + | CallToolResult + | ListToolsResult; diff --git a/packages/core/src/types/types.ts b/src/types.ts similarity index 85% rename from packages/core/src/types/types.ts rename to src/types.ts index 948f302926..21c24adb27 100644 --- a/packages/core/src/types/types.ts +++ b/src/types.ts @@ -1,4 +1,5 @@ import * as z from 'zod/v4'; +import { AuthInfo } from './server/auth/types.js'; export const LATEST_PROTOCOL_VERSION = '2025-11-25'; export const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26'; @@ -9,43 +10,6 @@ export const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task'; /* JSON-RPC types */ export const JSONRPC_VERSION = '2.0'; -/** - * Information about a validated access token, provided to request handlers. - */ -export interface AuthInfo { - /** - * The access token. - */ - token: string; - - /** - * The client ID associated with this token. - */ - clientId: string; - - /** - * Scopes associated with this token. - */ - scopes: string[]; - - /** - * When the token expires (in seconds since epoch). - */ - expiresAt?: number; - - /** - * The RFC 8707 resource server identifier for which this token is valid. - * If set, this MUST match the MCP server's resource identifier (minus hash fragment). - */ - resource?: URL; - - /** - * Additional data associated with the token. - * This field should be used for any additional data that needs to be attached to the auth info. - */ - extra?: Record; -} - /** * Utility types */ @@ -82,15 +46,10 @@ export const TaskCreationParamsSchema = z.looseObject({ pollInterval: z.number().optional() }); -export const TaskMetadataSchema = z.object({ - ttl: z.number().optional() -}); - /** - * Metadata for associating messages with a task. - * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + * Task association metadata, used to signal which task a message originated from. */ -export const RelatedTaskMetadataSchema = z.object({ +export const RelatedTaskMetadataSchema = z.looseObject({ taskId: z.string() }); @@ -108,53 +67,42 @@ const RequestMetaSchema = z.looseObject({ /** * Common params for any request. */ -const BaseRequestParamsSchema = z.object({ +const BaseRequestParamsSchema = z.looseObject({ /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. + * If specified, the caller is requesting that the receiver create a task to represent the request. + * Task creation parameters are now at the top level instead of in _meta. */ - _meta: RequestMetaSchema.optional() -}); - -/** - * Common params for any task-augmented request. - */ -export const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ + task: TaskCreationParamsSchema.optional(), /** - * If specified, the caller is requesting task-augmented execution for this request. - * The request will return a CreateTaskResult immediately, and the actual result can be - * retrieved later via tasks/result. - * - * Task augmentation is subject to capability negotiation - receivers MUST declare support - * for task augmentation of specific request types in their capabilities. + * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. */ - task: TaskMetadataSchema.optional() + _meta: RequestMetaSchema.optional() }); -/** - * Checks if a value is a valid TaskAugmentedRequestParams. - * @param value - The value to check. - * - * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise. - */ -export const isTaskAugmentedRequestParams = (value: unknown): value is TaskAugmentedRequestParams => - TaskAugmentedRequestParamsSchema.safeParse(value).success; - export const RequestSchema = z.object({ method: z.string(), - params: BaseRequestParamsSchema.loose().optional() + params: BaseRequestParamsSchema.optional() }); -const NotificationsParamsSchema = z.object({ +const NotificationsParamsSchema = z.looseObject({ /** * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ - _meta: RequestMetaSchema.optional() + _meta: z + .object({ + /** + * If specified, this notification is related to the provided task. + */ + [RELATED_TASK_META_KEY]: z.optional(RelatedTaskMetadataSchema) + }) + .passthrough() + .optional() }); export const NotificationSchema = z.object({ method: z.string(), - params: NotificationsParamsSchema.loose().optional() + params: NotificationsParamsSchema.optional() }); export const ResultSchema = z.looseObject({ @@ -162,7 +110,14 @@ export const ResultSchema = z.looseObject({ * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) * for notes on _meta usage. */ - _meta: RequestMetaSchema.optional() + _meta: z + .looseObject({ + /** + * If specified, this result is related to the provided task. + */ + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() + }) + .optional() }); /** @@ -198,7 +153,7 @@ export const isJSONRPCNotification = (value: unknown): value is JSONRPCNotificat /** * A successful (non-error) response to a request. */ -export const JSONRPCResultResponseSchema = z +export const JSONRPCResponseSchema = z .object({ jsonrpc: z.literal(JSONRPC_VERSION), id: RequestIdSchema, @@ -206,21 +161,7 @@ export const JSONRPCResultResponseSchema = z }) .strict(); -/** - * Checks if a value is a valid JSONRPCResultResponse. - * @param value - The value to check. - * - * @returns True if the value is a valid JSONRPCResultResponse, false otherwise. - */ -export const isJSONRPCResultResponse = (value: unknown): value is JSONRPCResultResponse => - JSONRPCResultResponseSchema.safeParse(value).success; - -/** - * @deprecated Use {@link isJSONRPCResultResponse} instead. - * - * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse}) - */ -export const isJSONRPCResponse = isJSONRPCResultResponse; +export const isJSONRPCResponse = (value: unknown): value is JSONRPCResponse => JSONRPCResponseSchema.safeParse(value).success; /** * Error codes defined by the JSON-RPC specification. @@ -244,10 +185,10 @@ export enum ErrorCode { /** * A response to a request that indicates an error occurred. */ -export const JSONRPCErrorResponseSchema = z +export const JSONRPCErrorSchema = z .object({ jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema.optional(), + id: RequestIdSchema, error: z.object({ /** * The error type that occurred. @@ -260,38 +201,14 @@ export const JSONRPCErrorResponseSchema = z /** * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). */ - data: z.unknown().optional() + data: z.optional(z.unknown()) }) }) .strict(); -/** - * @deprecated Use {@link JSONRPCErrorResponseSchema} instead. - */ -export const JSONRPCErrorSchema = JSONRPCErrorResponseSchema; - -/** - * Checks if a value is a valid JSONRPCErrorResponse. - * @param value - The value to check. - * - * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise. - */ -export const isJSONRPCErrorResponse = (value: unknown): value is JSONRPCErrorResponse => - JSONRPCErrorResponseSchema.safeParse(value).success; - -/** - * @deprecated Use {@link isJSONRPCErrorResponse} instead. - */ -export const isJSONRPCError = isJSONRPCErrorResponse; - -export const JSONRPCMessageSchema = z.union([ - JSONRPCRequestSchema, - JSONRPCNotificationSchema, - JSONRPCResultResponseSchema, - JSONRPCErrorResponseSchema -]); +export const isJSONRPCError = (value: unknown): value is JSONRPCError => JSONRPCErrorSchema.safeParse(value).success; -export const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); +export const JSONRPCMessageSchema = z.union([JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResponseSchema, JSONRPCErrorSchema]); /* Empty result */ /** @@ -305,7 +222,7 @@ export const CancelledNotificationParamsSchema = NotificationsParamsSchema.exten * * This MUST correspond to the ID of a request previously issued in the same direction. */ - requestId: RequestIdSchema.optional(), + requestId: RequestIdSchema, /** * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. */ @@ -345,15 +262,7 @@ export const IconSchema = z.object({ * * If not provided, the client should assume that the icon can be used at any size. */ - sizes: z.array(z.string()).optional(), - /** - * Optional specifier for the theme this icon is designed for. `light` indicates - * the icon is designed to be used with a light background, and `dark` indicates - * the icon is designed to be used with a dark background. - * - * If not provided, the client should assume the icon can be used with any theme. - */ - theme: z.enum(['light', 'dark']).optional() + sizes: z.array(z.string()).optional() }); /** @@ -403,16 +312,7 @@ export const ImplementationSchema = BaseMetadataSchema.extend({ /** * An optional URL of the website for this implementation. */ - websiteUrl: z.string().optional(), - - /** - * An optional human-readable description of what this implementation does. - * - * This can be used by clients or servers to provide context about their purpose - * and capabilities. For example, a server might describe the types of resources - * or tools it provides, while a client might describe its intended use case. - */ - description: z.string().optional() + websiteUrl: z.string().optional() }); const FormElicitationCapabilitySchema = z.intersection( @@ -443,68 +343,82 @@ const ElicitationCapabilitySchema = z.preprocess( /** * Task capabilities for clients, indicating which request types support task creation. */ -export const ClientTasksCapabilitySchema = z.looseObject({ - /** - * Present if the client supports listing tasks. - */ - list: AssertObjectSchema.optional(), - /** - * Present if the client supports cancelling tasks. - */ - cancel: AssertObjectSchema.optional(), - /** - * Capabilities for task creation on specific request types. - */ - requests: z - .looseObject({ - /** - * Task support for sampling requests. - */ - sampling: z - .looseObject({ - createMessage: AssertObjectSchema.optional() - }) - .optional(), - /** - * Task support for elicitation requests. - */ - elicitation: z - .looseObject({ - create: AssertObjectSchema.optional() +export const ClientTasksCapabilitySchema = z + .object({ + /** + * Present if the client supports listing tasks. + */ + list: z.optional(z.object({}).passthrough()), + /** + * Present if the client supports cancelling tasks. + */ + cancel: z.optional(z.object({}).passthrough()), + /** + * Capabilities for task creation on specific request types. + */ + requests: z.optional( + z + .object({ + /** + * Task support for sampling requests. + */ + sampling: z.optional( + z + .object({ + createMessage: z.optional(z.object({}).passthrough()) + }) + .passthrough() + ), + /** + * Task support for elicitation requests. + */ + elicitation: z.optional( + z + .object({ + create: z.optional(z.object({}).passthrough()) + }) + .passthrough() + ) }) - .optional() - }) - .optional() -}); + .passthrough() + ) + }) + .passthrough(); /** * Task capabilities for servers, indicating which request types support task creation. */ -export const ServerTasksCapabilitySchema = z.looseObject({ - /** - * Present if the server supports listing tasks. - */ - list: AssertObjectSchema.optional(), - /** - * Present if the server supports cancelling tasks. - */ - cancel: AssertObjectSchema.optional(), - /** - * Capabilities for task creation on specific request types. - */ - requests: z - .looseObject({ - /** - * Task support for tool requests. - */ - tools: z - .looseObject({ - call: AssertObjectSchema.optional() +export const ServerTasksCapabilitySchema = z + .object({ + /** + * Present if the server supports listing tasks. + */ + list: z.optional(z.object({}).passthrough()), + /** + * Present if the server supports cancelling tasks. + */ + cancel: z.optional(z.object({}).passthrough()), + /** + * Capabilities for task creation on specific request types. + */ + requests: z.optional( + z + .object({ + /** + * Task support for tool requests. + */ + tools: z.optional( + z + .object({ + call: z.optional(z.object({}).passthrough()) + }) + .passthrough() + ) }) - .optional() - }) - .optional() -}); + .passthrough() + ) + }) + .passthrough(); /** * 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. @@ -548,7 +462,7 @@ export const ClientCapabilitiesSchema = z.object({ /** * Present if the client supports task creation. */ - tasks: ClientTasksCapabilitySchema.optional() + tasks: z.optional(ClientTasksCapabilitySchema) }); export const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ @@ -572,62 +486,64 @@ export const isInitializeRequest = (value: unknown): value is InitializeRequest /** * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. */ -export const ServerCapabilitiesSchema = z.object({ - /** - * Experimental, non-standard capabilities that the server supports. - */ - experimental: z.record(z.string(), AssertObjectSchema).optional(), - /** - * Present if the server supports sending log messages to the client. - */ - logging: AssertObjectSchema.optional(), - /** - * Present if the server supports sending completions to the client. - */ - completions: AssertObjectSchema.optional(), - /** - * Present if the server offers any prompt templates. - */ - prompts: z - .object({ - /** - * Whether this server supports issuing notifications for changes to the prompt list. - */ - listChanged: z.boolean().optional() - }) - .optional(), - /** - * Present if the server offers any resources to read. - */ - resources: z - .object({ - /** - * Whether this server supports clients subscribing to resource updates. - */ - subscribe: z.boolean().optional(), - - /** - * Whether this server supports issuing notifications for changes to the resource list. - */ - listChanged: z.boolean().optional() - }) - .optional(), - /** - * Present if the server offers any tools to call. - */ - tools: z - .object({ - /** - * Whether this server supports issuing notifications for changes to the tool list. - */ - listChanged: z.boolean().optional() - }) - .optional(), - /** - * Present if the server supports task creation. - */ - tasks: ServerTasksCapabilitySchema.optional() -}); +export const ServerCapabilitiesSchema = z + .object({ + /** + * Experimental, non-standard capabilities that the server supports. + */ + experimental: z.record(z.string(), AssertObjectSchema).optional(), + /** + * Present if the server supports sending log messages to the client. + */ + logging: AssertObjectSchema.optional(), + /** + * Present if the server supports sending completions to the client. + */ + completions: AssertObjectSchema.optional(), + /** + * Present if the server offers any prompt templates. + */ + prompts: z.optional( + z.object({ + /** + * Whether this server supports issuing notifications for changes to the prompt list. + */ + listChanged: z.optional(z.boolean()) + }) + ), + /** + * Present if the server offers any resources to read. + */ + resources: z + .object({ + /** + * Whether this server supports clients subscribing to resource updates. + */ + subscribe: z.boolean().optional(), + + /** + * Whether this server supports issuing notifications for changes to the resource list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server offers any tools to call. + */ + tools: z + .object({ + /** + * Whether this server supports issuing notifications for changes to the tool list. + */ + listChanged: z.boolean().optional() + }) + .optional(), + /** + * Present if the server supports task creation. + */ + tasks: z.optional(ServerTasksCapabilitySchema) + }) + .passthrough(); /** * After receiving an initialize request from the client, the server sends this response. @@ -651,8 +567,7 @@ export const InitializeResultSchema = ResultSchema.extend({ * This notification is sent from the client to the server after initialization has finished. */ export const InitializedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/initialized'), - params: NotificationsParamsSchema.optional() + method: z.literal('notifications/initialized') }); export const isInitializedNotification = (value: unknown): value is InitializedNotification => @@ -663,8 +578,7 @@ export const isInitializedNotification = (value: unknown): value is InitializedN * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. */ export const PingRequestSchema = RequestSchema.extend({ - method: z.literal('ping'), - params: BaseRequestParamsSchema.optional() + method: z.literal('ping') }); /* Progress notifications */ @@ -719,21 +633,16 @@ export const PaginatedResultSchema = ResultSchema.extend({ * An opaque token representing the pagination position after the last returned result. * If present, there may be more results available. */ - nextCursor: CursorSchema.optional() + nextCursor: z.optional(CursorSchema) }); -/** - * The status of a task. - * */ -export const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']); - /* Tasks */ /** * A pollable state object associated with a request. */ export const TaskSchema = z.object({ taskId: z.string(), - status: TaskStatusSchema, + status: z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']), /** * Time in milliseconds to keep task results available after completion. * If null, the task has unlimited lifetime until manually cleaned up. @@ -799,14 +708,6 @@ export const GetTaskPayloadRequestSchema = RequestSchema.extend({ }) }); -/** - * The response to a tasks/result request. - * The structure matches the result type of the original request. - * For example, a tools/call task would return the CallToolResult structure. - * - */ -export const GetTaskPayloadResultSchema = ResultSchema.loose(); - /** * A request to list tasks. */ @@ -1045,8 +946,7 @@ export const ReadResourceResultSchema = ResultSchema.extend({ * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. */ export const ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/resources/list_changed'), - params: NotificationsParamsSchema.optional() + method: z.literal('notifications/resources/list_changed') }); export const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; @@ -1238,29 +1138,31 @@ export const AudioContentSchema = z.object({ * A tool call request from an assistant (LLM). * Represents the assistant's request to use a tool. */ -export const ToolUseContentSchema = z.object({ - type: z.literal('tool_use'), - /** - * The name of the tool to invoke. - * Must match a tool name from the request's tools array. - */ - name: z.string(), - /** - * Unique identifier for this tool call. - * Used to correlate with ToolResultContent in subsequent messages. - */ - id: z.string(), - /** - * Arguments to pass to the tool. - * Must conform to the tool's inputSchema. - */ - input: z.record(z.string(), z.unknown()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); +export const ToolUseContentSchema = z + .object({ + type: z.literal('tool_use'), + /** + * The name of the tool to invoke. + * Must match a tool name from the request's tools array. + */ + name: z.string(), + /** + * Unique identifier for this tool call. + * Used to correlate with ToolResultContent in subsequent messages. + */ + id: z.string(), + /** + * Arguments to pass to the tool. + * Must conform to the tool's inputSchema. + */ + input: z.object({}).passthrough(), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()) + }) + .passthrough(); /** * The contents of a resource, embedded into a prompt or tool call result. @@ -1314,7 +1216,7 @@ export const GetPromptResultSchema = ResultSchema.extend({ /** * An optional description for the prompt. */ - description: z.string().optional(), + description: z.optional(z.string()), messages: z.array(PromptMessageSchema) }); @@ -1322,8 +1224,7 @@ export const GetPromptResultSchema = ResultSchema.extend({ * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. */ export const PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/prompts/list_changed'), - params: NotificationsParamsSchema.optional() + method: z.literal('notifications/prompts/list_changed') }); /* Tools */ @@ -1461,11 +1362,11 @@ export const ToolSchema = z.object({ /** * Optional additional tool information. */ - annotations: ToolAnnotationsSchema.optional(), + annotations: z.optional(ToolAnnotationsSchema), /** * Execution-related properties for this tool. */ - execution: ToolExecutionSchema.optional(), + execution: z.optional(ToolExecutionSchema), /** * Optional list of security schemes supported by this tool. @@ -1528,7 +1429,7 @@ export const CallToolResultSchema = ResultSchema.extend({ * server does not support tool calls, or any other exceptional conditions, * should be reported as an MCP error response. */ - isError: z.boolean().optional() + isError: z.optional(z.boolean()) }); /** @@ -1543,7 +1444,7 @@ export const CompatibilityCallToolResultSchema = CallToolResultSchema.or( /** * Parameters for a `tools/call` request. */ -export const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ +export const CallToolRequestParamsSchema = BaseRequestParamsSchema.extend({ /** * The name of the tool to call. */ @@ -1551,7 +1452,7 @@ export const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.exte /** * Arguments to pass to the tool. */ - arguments: z.record(z.string(), z.unknown()).optional() + arguments: z.optional(z.record(z.string(), z.unknown())) }); /** @@ -1566,8 +1467,7 @@ export const CallToolRequestSchema = RequestSchema.extend({ * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. */ export const ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/tools/list_changed'), - params: NotificationsParamsSchema.optional() + method: z.literal('notifications/tools/list_changed') }); /** @@ -1716,19 +1616,19 @@ export const ModelPreferencesSchema = z.object({ /** * Optional hints to use for model selection. */ - hints: z.array(ModelHintSchema).optional(), + hints: z.optional(z.array(ModelHintSchema)), /** * How much to prioritize cost when selecting a model. */ - costPriority: z.number().min(0).max(1).optional(), + costPriority: z.optional(z.number().min(0).max(1)), /** * How much to prioritize sampling speed (latency) when selecting a model. */ - speedPriority: z.number().min(0).max(1).optional(), + speedPriority: z.optional(z.number().min(0).max(1)), /** * How much to prioritize intelligence and capabilities when selecting a model. */ - intelligencePriority: z.number().min(0).max(1).optional() + intelligencePriority: z.optional(z.number().min(0).max(1)) }); /** @@ -1741,26 +1641,28 @@ export const ToolChoiceSchema = z.object({ * - "required": Model MUST use at least one tool before completing * - "none": Model MUST NOT use any tools */ - mode: z.enum(['auto', 'required', 'none']).optional() + mode: z.optional(z.enum(['auto', 'required', 'none'])) }); /** * The result of a tool execution, provided by the user (server). * Represents the outcome of invoking a tool requested via ToolUseContent. */ -export const ToolResultContentSchema = z.object({ - type: z.literal('tool_result'), - toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'), - content: z.array(ContentBlockSchema).default([]), - structuredContent: z.object({}).loose().optional(), - isError: z.boolean().optional(), +export const ToolResultContentSchema = z + .object({ + type: z.literal('tool_result'), + toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'), + content: z.array(ContentBlockSchema).default([]), + structuredContent: z.object({}).passthrough().optional(), + isError: z.optional(z.boolean()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()) + }) + .passthrough(); /** * Basic content types for sampling responses (without tool use). @@ -1783,20 +1685,22 @@ export const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ /** * Describes a message issued to or received from an LLM API. */ -export const SamplingMessageSchema = z.object({ - role: RoleSchema, - content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); +export const SamplingMessageSchema = z + .object({ + role: RoleSchema, + content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]), + /** + * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) + * for notes on _meta usage. + */ + _meta: z.optional(z.object({}).passthrough()) + }) + .passthrough(); /** * Parameters for a `sampling/createMessage` request. */ -export const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ +export const CreateMessageRequestParamsSchema = BaseRequestParamsSchema.extend({ messages: z.array(SamplingMessageSchema), /** * The server's preferences for which model to select. The client MAY modify or omit this request. @@ -1830,13 +1734,13 @@ export const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema * Tools that the model may use during generation. * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. */ - tools: z.array(ToolSchema).optional(), + tools: z.optional(z.array(ToolSchema)), /** * Controls how the model uses tools. * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. * Default is `{ mode: "auto" }`. */ - toolChoice: ToolChoiceSchema.optional() + toolChoice: z.optional(ToolChoiceSchema) }); /** * 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. @@ -2035,7 +1939,7 @@ export const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, Boolea /** * Parameters for an `elicitation/create` request for form-based elicitation. */ -export const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ +export const ElicitRequestFormParamsSchema = BaseRequestParamsSchema.extend({ /** * The elicitation mode. * @@ -2060,7 +1964,7 @@ export const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.ex /** * Parameters for an `elicitation/create` request for URL-based elicitation. */ -export const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ +export const ElicitRequestURLParamsSchema = BaseRequestParamsSchema.extend({ /** * The elicitation mode. */ @@ -2262,8 +2166,7 @@ export const RootSchema = z.object({ * Sent from the server to request a list of root URIs from the client. */ export const ListRootsRequestSchema = RequestSchema.extend({ - method: z.literal('roots/list'), - params: BaseRequestParamsSchema.optional() + method: z.literal('roots/list') }); /** @@ -2277,8 +2180,7 @@ export const ListRootsResultSchema = ResultSchema.extend({ * A notification from the client to the server, informing it that the list of roots has changed. */ export const RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/roots/list_changed'), - params: NotificationsParamsSchema.optional() + method: z.literal('notifications/roots/list_changed') }); /* Client messages */ @@ -2298,8 +2200,7 @@ export const ClientRequestSchema = z.union([ ListToolsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, - ListTasksRequestSchema, - CancelTaskRequestSchema + ListTasksRequestSchema ]); export const ClientNotificationSchema = z.union([ @@ -2329,8 +2230,7 @@ export const ServerRequestSchema = z.union([ ListRootsRequestSchema, GetTaskRequestSchema, GetTaskPayloadRequestSchema, - ListTasksRequestSchema, - CancelTaskRequestSchema + ListTasksRequestSchema ]); export const ServerNotificationSchema = z.union([ @@ -2465,7 +2365,6 @@ export interface MessageExtraInfo { export type ProgressToken = Infer; export type Cursor = Infer; export type Request = Infer; -export type TaskAugmentedRequestParams = Infer; export type RequestMeta = Infer; export type Notification = Infer; export type Result = Infer; @@ -2473,15 +2372,7 @@ export type RequestId = Infer; export type JSONRPCRequest = Infer; export type JSONRPCNotification = Infer; export type JSONRPCResponse = Infer; -export type JSONRPCErrorResponse = Infer; -/** - * @deprecated Use {@link JSONRPCErrorResponse} instead. - * - * Please note that spec types have renamed {@link JSONRPCError} to {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCError}) and future versions will remove {@link JSONRPCError}. - */ -export type JSONRPCError = JSONRPCErrorResponse; -export type JSONRPCResultResponse = Infer; - +export type JSONRPCError = Infer; export type JSONRPCMessage = Infer; export type RequestParams = Infer; export type NotificationParams = Infer; @@ -2519,9 +2410,7 @@ export type ProgressNotification = Infer; /* Tasks */ export type Task = Infer; -export type TaskStatus = Infer; export type TaskCreationParams = Infer; -export type TaskMetadata = Infer; export type RelatedTaskMetadata = Infer; export type CreateTaskResult = Infer; export type TaskStatusNotificationParams = Infer; @@ -2533,7 +2422,6 @@ export type ListTasksRequest = Infer; export type ListTasksResult = Infer; export type CancelTaskRequest = Infer; export type CancelTaskResult = Infer; -export type GetTaskPayloadResult = Infer; /* Pagination */ export type PaginatedRequestParams = Infer; @@ -2545,8 +2433,7 @@ export type ResourceContents = Infer; export type TextResourceContents = Infer; export type BlobResourceContents = Infer; export type Resource = Infer; -// TODO: Overlaps with exported `ResourceTemplate` class from `server`. -export type ResourceTemplateType = Infer; +export type ResourceTemplate = Infer; export type ListResourcesRequest = Infer; export type ListResourcesResult = Infer; export type ListResourceTemplatesRequest = Infer; diff --git a/packages/core/src/validation/ajv-provider.ts b/src/validation/ajv-provider.ts similarity index 96% rename from packages/core/src/validation/ajv-provider.ts rename to src/validation/ajv-provider.ts index 4a9d572142..115a98521b 100644 --- a/packages/core/src/validation/ajv-provider.ts +++ b/src/validation/ajv-provider.ts @@ -4,8 +4,7 @@ import { Ajv } from 'ajv'; import _addFormats from 'ajv-formats'; - -import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator, JsonSchemaValidatorResult } from './types.js'; +import type { JsonSchemaType, JsonSchemaValidator, JsonSchemaValidatorResult, jsonSchemaValidator } from './types.js'; function createDefaultAjvInstance(): Ajv { const ajv = new Ajv({ diff --git a/packages/core/src/validation/cfworker-provider.ts b/src/validation/cfworker-provider.ts similarity index 95% rename from packages/core/src/validation/cfworker-provider.ts rename to src/validation/cfworker-provider.ts index 460408d62e..7e6329d9d5 100644 --- a/packages/core/src/validation/cfworker-provider.ts +++ b/src/validation/cfworker-provider.ts @@ -7,8 +7,7 @@ */ import { Validator } from '@cfworker/json-schema'; - -import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator, JsonSchemaValidatorResult } from './types.js'; +import type { JsonSchemaType, JsonSchemaValidator, JsonSchemaValidatorResult, jsonSchemaValidator } from './types.js'; /** * JSON Schema draft version supported by @cfworker/json-schema diff --git a/packages/core/src/index.ts b/src/validation/index.ts similarity index 54% rename from packages/core/src/index.ts rename to src/validation/index.ts index f4eaeabfca..a6df86d6a2 100644 --- a/packages/core/src/index.ts +++ b/src/validation/index.ts @@ -1,22 +1,3 @@ -export * from './auth/errors.js'; -export * from './shared/auth.js'; -export * from './shared/auth-utils.js'; -export * from './shared/metadataUtils.js'; -export * from './shared/protocol.js'; -export * from './shared/responseMessage.js'; -export * from './shared/stdio.js'; -export * from './shared/toolNameValidation.js'; -export * from './shared/transport.js'; -export * from './shared/uriTemplate.js'; -export * from './types/types.js'; -export * from './util/inMemory.js'; -export * from './util/zod-compat.js'; -export * from './util/zod-json-schema-compat.js'; - -// experimental exports -export * from './experimental/index.js'; -export * from './validation/ajv-provider.js'; -export * from './validation/cfworker-provider.js'; /** * JSON Schema validation * @@ -46,4 +27,4 @@ export * from './validation/cfworker-provider.js'; */ // Core types only - implementations are exported via separate entry points -export type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator, JsonSchemaValidatorResult } from './validation/types.js'; +export type { JsonSchemaType, JsonSchemaValidator, JsonSchemaValidatorResult, jsonSchemaValidator } from './types.js'; diff --git a/packages/core/src/validation/types.ts b/src/validation/types.ts similarity index 100% rename from packages/core/src/validation/types.ts rename to src/validation/types.ts diff --git a/packages/client/test/client/auth-extensions.test.ts b/test/client/auth-extensions.test.ts similarity index 97% rename from packages/client/test/client/auth-extensions.test.ts rename to test/client/auth-extensions.test.ts index f7bde7f241..a7217307dc 100644 --- a/packages/client/test/client/auth-extensions.test.ts +++ b/test/client/auth-extensions.test.ts @@ -1,13 +1,12 @@ -import { createMockOAuthFetch } from '@modelcontextprotocol/test-helpers'; -import { describe, expect, it } from 'vitest'; - +import { describe, it, expect } from 'vitest'; import { auth } from '../../src/client/auth.js'; import { ClientCredentialsProvider, - createPrivateKeyJwtAuth, PrivateKeyJwtProvider, - StaticPrivateKeyJwtProvider + StaticPrivateKeyJwtProvider, + createPrivateKeyJwtAuth } from '../../src/client/auth-extensions.js'; +import { createMockOAuthFetch } from '../helpers/oauth.js'; const RESOURCE_SERVER_URL = 'https://resource.example.com/'; const AUTH_SERVER_URL = 'https://auth.example.com'; @@ -275,7 +274,7 @@ describe('createPrivateKeyJwtAuth', () => { const assertion = params.get('client_assertion')!; // Decode the payload to verify audience const [, payloadB64] = assertion.split('.'); - const payload = JSON.parse(Buffer.from(payloadB64!, 'base64url').toString()); + const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString()); expect(payload.aud).toBe('https://issuer.example.com'); }); diff --git a/packages/client/test/client/auth.test.ts b/test/client/auth.test.ts similarity index 96% rename from packages/client/test/client/auth.test.ts rename to test/client/auth.test.ts index cb01d37d5e..d6e7e86845 100644 --- a/packages/client/test/client/auth.test.ts +++ b/test/client/auth.test.ts @@ -1,23 +1,23 @@ -import type { AuthorizationServerMetadata, OAuthTokens } from '@modelcontextprotocol/core'; -import { InvalidClientMetadataError, LATEST_PROTOCOL_VERSION, ServerError } from '@modelcontextprotocol/core'; -import { expect, type Mock, vi } from 'vitest'; - +import { LATEST_PROTOCOL_VERSION } from '../../src/types.js'; import { - auth, - buildDiscoveryUrls, - discoverAuthorizationServerMetadata, discoverOAuthMetadata, - discoverOAuthProtectedResourceMetadata, + discoverAuthorizationServerMetadata, + buildDiscoveryUrls, + startAuthorization, exchangeAuthorization, - extractWWWAuthenticateParams, - isHttpsUrl, - type OAuthClientProvider, refreshAuthorization, registerClient, + discoverOAuthProtectedResourceMetadata, + extractWWWAuthenticateParams, + auth, + type OAuthClientProvider, selectClientAuthMethod, - startAuthorization + isHttpsUrl } from '../../src/client/auth.js'; import { createPrivateKeyJwtAuth } from '../../src/client/auth-extensions.js'; +import { InvalidClientMetadataError, ServerError } from '../../src/server/auth/errors.js'; +import { AuthorizationServerMetadata, OAuthTokens } from '../../src/shared/auth.js'; +import { expect, vi, type Mock } from 'vitest'; // Mock pkce-challenge vi.mock('pkce-challenge', () => ({ @@ -125,7 +125,7 @@ describe('OAuth Authorization', () => { expect(metadata).toEqual(validMetadata); const calls = mockFetch.mock.calls; expect(calls.length).toBe(1); - const [url] = calls[0]!; + const [url] = calls[0]; expect(url.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); }); @@ -159,7 +159,7 @@ describe('OAuth Authorization', () => { expect(mockFetch).toHaveBeenCalledTimes(2); // Verify first call had MCP header - expect(mockFetch.mock.calls[0]![1]?.headers).toHaveProperty('MCP-Protocol-Version'); + expect(mockFetch.mock.calls[0][1]?.headers).toHaveProperty('MCP-Protocol-Version'); }); it('throws an error when all fetch attempts fail', async () => { @@ -230,7 +230,7 @@ describe('OAuth Authorization', () => { expect(metadata).toEqual(validMetadata); const calls = mockFetch.mock.calls; expect(calls.length).toBe(1); - const [url] = calls[0]!; + const [url] = calls[0]; expect(url.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource/path/name'); }); @@ -245,7 +245,7 @@ describe('OAuth Authorization', () => { expect(metadata).toEqual(validMetadata); const calls = mockFetch.mock.calls; expect(calls.length).toBe(1); - const [url] = calls[0]!; + const [url] = calls[0]; expect(url.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource/path?param=value'); }); @@ -272,14 +272,14 @@ describe('OAuth Authorization', () => { expect(calls.length).toBe(2); // First call should be path-aware - const [firstUrl, firstOptions] = calls[0]!; + const [firstUrl, firstOptions] = calls[0]; expect(firstUrl.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource/path/name'); expect(firstOptions.headers).toEqual({ 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION }); // Second call should be root fallback - const [secondUrl, secondOptions] = calls[1]!; + const [secondUrl, secondOptions] = calls[1]; expect(secondUrl.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); expect(secondOptions.headers).toEqual({ 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION @@ -335,7 +335,7 @@ describe('OAuth Authorization', () => { const calls = mockFetch.mock.calls; expect(calls.length).toBe(1); // Should not attempt fallback - const [url] = calls[0]!; + const [url] = calls[0]; expect(url.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); }); @@ -353,7 +353,7 @@ describe('OAuth Authorization', () => { const calls = mockFetch.mock.calls; expect(calls.length).toBe(1); // Should not attempt fallback - const [url] = calls[0]!; + const [url] = calls[0]; expect(url.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); }); @@ -381,7 +381,7 @@ describe('OAuth Authorization', () => { expect(calls.length).toBe(3); // Final call should be root fallback - const [lastUrl, lastOptions] = calls[2]!; + const [lastUrl, lastOptions] = calls[2]; expect(lastUrl.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); expect(lastOptions.headers).toEqual({ 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION @@ -404,7 +404,7 @@ describe('OAuth Authorization', () => { const calls = mockFetch.mock.calls; expect(calls.length).toBe(1); // Should not attempt fallback when explicit URL is provided - const [url] = calls[0]!; + const [url] = calls[0]; expect(url.toString()).toBe('https://custom.example.com/metadata'); }); @@ -426,7 +426,7 @@ describe('OAuth Authorization', () => { expect(customFetch).toHaveBeenCalledTimes(1); expect(mockFetch).not.toHaveBeenCalled(); - const [url, options] = customFetch.mock.calls[0]!; + const [url, options] = customFetch.mock.calls[0]; expect(url.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); expect(options.headers).toEqual({ 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION @@ -455,7 +455,7 @@ describe('OAuth Authorization', () => { expect(metadata).toEqual(validMetadata); const calls = mockFetch.mock.calls; expect(calls.length).toBe(1); - const [url, options] = calls[0]!; + const [url, options] = calls[0]; expect(url.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); expect(options.headers).toEqual({ 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION @@ -473,7 +473,7 @@ describe('OAuth Authorization', () => { expect(metadata).toEqual(validMetadata); const calls = mockFetch.mock.calls; expect(calls.length).toBe(1); - const [url, options] = calls[0]!; + const [url, options] = calls[0]; expect(url.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server/path/name'); expect(options.headers).toEqual({ 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION @@ -501,14 +501,14 @@ describe('OAuth Authorization', () => { expect(calls.length).toBe(2); // First call should be path-aware - const [firstUrl, firstOptions] = calls[0]!; + const [firstUrl, firstOptions] = calls[0]; expect(firstUrl.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server/path/name'); expect(firstOptions.headers).toEqual({ 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION }); // Second call should be root fallback - const [secondUrl, secondOptions] = calls[1]!; + const [secondUrl, secondOptions] = calls[1]; expect(secondUrl.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); expect(secondOptions.headers).toEqual({ 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION @@ -548,7 +548,7 @@ describe('OAuth Authorization', () => { const calls = mockFetch.mock.calls; expect(calls.length).toBe(1); // Should not attempt fallback - const [url] = calls[0]!; + const [url] = calls[0]; expect(url.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); }); @@ -565,7 +565,7 @@ describe('OAuth Authorization', () => { const calls = mockFetch.mock.calls; expect(calls.length).toBe(1); // Should not attempt fallback - const [url] = calls[0]!; + const [url] = calls[0]; expect(url.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); }); @@ -593,7 +593,7 @@ describe('OAuth Authorization', () => { expect(calls.length).toBe(3); // Final call should be root fallback - const [lastUrl, lastOptions] = calls[2]!; + const [lastUrl, lastOptions] = calls[2]; expect(lastUrl.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); expect(lastOptions.headers).toEqual({ 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION @@ -630,7 +630,7 @@ describe('OAuth Authorization', () => { expect(mockFetch).toHaveBeenCalledTimes(2); // Verify first call had MCP header - expect(mockFetch.mock.calls[0]![1]?.headers).toHaveProperty('MCP-Protocol-Version'); + expect(mockFetch.mock.calls[0][1]?.headers).toHaveProperty('MCP-Protocol-Version'); }); it('throws an error when all fetch attempts fail', async () => { @@ -722,7 +722,7 @@ describe('OAuth Authorization', () => { expect(customFetch).toHaveBeenCalledTimes(1); expect(mockFetch).not.toHaveBeenCalled(); - const [url, options] = customFetch.mock.calls[0]!; + const [url, options] = customFetch.mock.calls[0]; expect(url.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); expect(options.headers).toEqual({ 'MCP-Protocol-Version': LATEST_PROTOCOL_VERSION @@ -771,7 +771,7 @@ describe('OAuth Authorization', () => { const urls = buildDiscoveryUrls(new URL('https://auth.example.com/tenant1')); expect(urls).toHaveLength(3); - expect(urls[0]!.url.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server/tenant1'); + expect(urls[0].url.toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server/tenant1'); }); }); @@ -817,8 +817,8 @@ describe('OAuth Authorization', () => { // Verify it tried the URLs in the correct order const calls = mockFetch.mock.calls; expect(calls.length).toBe(2); - expect(calls[0]![0].toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server/tenant1'); - expect(calls[1]![0].toString()).toBe('https://auth.example.com/.well-known/openid-configuration/tenant1'); + expect(calls[0][0].toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server/tenant1'); + expect(calls[1][0].toString()).toBe('https://auth.example.com/.well-known/openid-configuration/tenant1'); }); it('continues on 4xx errors', async () => { @@ -865,10 +865,10 @@ describe('OAuth Authorization', () => { expect(calls.length).toBe(2); // First call should have headers - expect(calls[0]![1]?.headers).toHaveProperty('MCP-Protocol-Version'); + expect(calls[0][1]?.headers).toHaveProperty('MCP-Protocol-Version'); // Second call should not have headers (CORS retry) - expect(calls[1]![1]?.headers).toBeUndefined(); + expect(calls[1][1]?.headers).toBeUndefined(); }); it('supports custom fetch function', async () => { @@ -896,7 +896,7 @@ describe('OAuth Authorization', () => { expect(metadata).toEqual(validOAuthMetadata); const calls = mockFetch.mock.calls; - const [, options] = calls[0]!; + const [, options] = calls[0]; expect(options.headers).toEqual({ 'MCP-Protocol-Version': '2025-01-01', Accept: 'application/json' @@ -1140,7 +1140,7 @@ describe('OAuth Authorization', () => { }) ); - const options = mockFetch.mock.calls[0]![1]; + const options = mockFetch.mock.calls[0][1]; expect(options.headers).toBeInstanceOf(Headers); expect(options.headers.get('Content-Type')).toBe('application/x-www-form-urlencoded'); expect(options.body).toBeInstanceOf(URLSearchParams); @@ -1180,7 +1180,7 @@ describe('OAuth Authorization', () => { }) ); - const options = mockFetch.mock.calls[0]![1]; + const options = mockFetch.mock.calls[0][1]; expect(options.headers).toBeInstanceOf(Headers); expect(options.headers.get('Content-Type')).toBe('application/x-www-form-urlencoded'); @@ -1229,10 +1229,10 @@ describe('OAuth Authorization', () => { }) ); - const headers = mockFetch.mock.calls[0]![1].headers as Headers; + const headers = mockFetch.mock.calls[0][1].headers as Headers; expect(headers.get('Content-Type')).toBe('application/x-www-form-urlencoded'); expect(headers.get('Authorization')).toBe('Basic Y2xpZW50MTIzOnNlY3JldDEyMw=='); - const body = mockFetch.mock.calls[0]![1].body as URLSearchParams; + const body = mockFetch.mock.calls[0][1].body as URLSearchParams; expect(body.get('grant_type')).toBe('authorization_code'); expect(body.get('code')).toBe('code123'); expect(body.get('code_verifier')).toBe('verifier123'); @@ -1297,7 +1297,7 @@ describe('OAuth Authorization', () => { expect(customFetch).toHaveBeenCalledTimes(1); expect(mockFetch).not.toHaveBeenCalled(); - const [url, options] = customFetch.mock.calls[0]!; + const [url, options] = customFetch.mock.calls[0]; expect(url.toString()).toBe('https://auth.example.com/token'); expect(options).toEqual( expect.objectContaining({ @@ -1366,9 +1366,9 @@ describe('OAuth Authorization', () => { }) ); - const headers = mockFetch.mock.calls[0]![1].headers as Headers; + const headers = mockFetch.mock.calls[0][1].headers as Headers; expect(headers.get('Content-Type')).toBe('application/x-www-form-urlencoded'); - const body = mockFetch.mock.calls[0]![1].body as URLSearchParams; + const body = mockFetch.mock.calls[0][1].body as URLSearchParams; expect(body.get('grant_type')).toBe('refresh_token'); expect(body.get('refresh_token')).toBe('refresh123'); expect(body.get('client_id')).toBe('client123'); @@ -1410,10 +1410,10 @@ describe('OAuth Authorization', () => { }) ); - const headers = mockFetch.mock.calls[0]![1].headers as Headers; + const headers = mockFetch.mock.calls[0][1].headers as Headers; expect(headers.get('Content-Type')).toBe('application/x-www-form-urlencoded'); expect(headers.get('Authorization')).toBe('Basic Y2xpZW50MTIzOnNlY3JldDEyMw=='); - const body = mockFetch.mock.calls[0]![1].body as URLSearchParams; + const body = mockFetch.mock.calls[0][1].body as URLSearchParams; expect(body.get('grant_type')).toBe('refresh_token'); expect(body.get('refresh_token')).toBe('refresh123'); expect(body.get('client_id')).toBeNull(); @@ -1740,10 +1740,10 @@ describe('OAuth Authorization', () => { expect(mockFetch).toHaveBeenCalledTimes(3); // First call should be to protected resource metadata - expect(mockFetch.mock.calls[0]![0].toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); + expect(mockFetch.mock.calls[0][0].toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); // Second call should be to oauth metadata at the root path - expect(mockFetch.mock.calls[1]![0].toString()).toBe('https://resource.example.com/.well-known/oauth-authorization-server'); + expect(mockFetch.mock.calls[1][0].toString()).toBe('https://resource.example.com/.well-known/oauth-authorization-server'); }); it('uses base URL (with root path) as authorization server when protected-resource-metadata discovery fails', async () => { @@ -1869,7 +1869,7 @@ describe('OAuth Authorization', () => { }) ); - const redirectCall = (mockProvider.redirectToAuthorization as Mock).mock.calls[0]!; + const redirectCall = (mockProvider.redirectToAuthorization as Mock).mock.calls[0]; const authUrl: URL = redirectCall[0]; expect(authUrl.searchParams.get('resource')).toBe('https://api.example.com/mcp-server'); }); @@ -2126,7 +2126,7 @@ describe('OAuth Authorization', () => { }) ); - const redirectCall = (mockProvider.redirectToAuthorization as Mock).mock.calls[0]!; + const redirectCall = (mockProvider.redirectToAuthorization as Mock).mock.calls[0]; const authUrl: URL = redirectCall[0]; // Should use the PRM's resource value, not the full requested URL expect(authUrl.searchParams.get('resource')).toBe('https://api.example.com/'); @@ -2184,7 +2184,7 @@ describe('OAuth Authorization', () => { }) ); - const redirectCall = (mockProvider.redirectToAuthorization as Mock).mock.calls[0]!; + const redirectCall = (mockProvider.redirectToAuthorization as Mock).mock.calls[0]; const authUrl: URL = redirectCall[0]; // Resource parameter should not be present when PRM is not available expect(authUrl.searchParams.has('resource')).toBe(false); @@ -2379,9 +2379,9 @@ describe('OAuth Authorization', () => { expect(result).toBe('REDIRECT'); // Verify the authorization URL includes the scopes from PRM - const redirectCall = (mockProvider.redirectToAuthorization as Mock).mock.calls[0]!; + const redirectCall = (mockProvider.redirectToAuthorization as Mock).mock.calls[0]; const authUrl: URL = redirectCall[0]; - expect(authUrl?.searchParams.get('scope')).toBe('mcp:read mcp:write mcp:admin'); + expect(authUrl.searchParams.get('scope')).toBe('mcp:read mcp:write mcp:admin'); }); it('prefers explicit scope parameter over scopes_supported from PRM', async () => { @@ -2444,7 +2444,7 @@ describe('OAuth Authorization', () => { expect(result).toBe('REDIRECT'); // Verify the authorization URL uses the explicit scope, not scopes_supported - const redirectCall = (mockProvider.redirectToAuthorization as Mock).mock.calls[0]!; + const redirectCall = (mockProvider.redirectToAuthorization as Mock).mock.calls[0]; const authUrl: URL = redirectCall[0]; expect(authUrl.searchParams.get('scope')).toBe('mcp:read'); }); @@ -2501,10 +2501,10 @@ describe('OAuth Authorization', () => { const calls = mockFetch.mock.calls; // First call should be to PRM - expect(calls[0]![0].toString()).toBe('https://my.resource.com/.well-known/oauth-protected-resource/path/name'); + expect(calls[0][0].toString()).toBe('https://my.resource.com/.well-known/oauth-protected-resource/path/name'); // Second call should be to AS metadata with the path from authorization server - expect(calls[1]![0].toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server/oauth'); + expect(calls[1][0].toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server/oauth'); }); it('supports overriding the fetch function used for requests', async () => { @@ -2565,10 +2565,10 @@ describe('OAuth Authorization', () => { expect(mockFetch).not.toHaveBeenCalled(); // Verify custom fetch was called for PRM discovery - expect(customFetch.mock.calls[0]![0].toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); + expect(customFetch.mock.calls[0][0].toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); // Verify custom fetch was called for AS metadata discovery - expect(customFetch.mock.calls[1]![0].toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); + expect(customFetch.mock.calls[1][0].toString()).toBe('https://auth.example.com/.well-known/oauth-authorization-server'); }); }); @@ -2627,7 +2627,7 @@ describe('OAuth Authorization', () => { }); expect(tokens).toEqual(validTokens); - const request = mockFetch.mock.calls[0]![1]; + const request = mockFetch.mock.calls[0][1]; // Check Authorization header const authHeader = request.headers.get('Authorization'); @@ -2655,7 +2655,7 @@ describe('OAuth Authorization', () => { }); expect(tokens).toEqual(validTokens); - const request = mockFetch.mock.calls[0]![1]; + const request = mockFetch.mock.calls[0][1]; // Check no Authorization header expect(request.headers.get('Authorization')).toBeNull(); @@ -2681,7 +2681,7 @@ describe('OAuth Authorization', () => { }); expect(tokens).toEqual(validTokens); - const request = mockFetch.mock.calls[0]![1]; + const request = mockFetch.mock.calls[0][1]; // Check Authorization header - should use Basic auth as it's the most secure const authHeader = request.headers.get('Authorization'); @@ -2716,7 +2716,7 @@ describe('OAuth Authorization', () => { }); expect(tokens).toEqual(validTokens); - const request = mockFetch.mock.calls[0]![1]; + const request = mockFetch.mock.calls[0][1]; // Check no Authorization header expect(request.headers.get('Authorization')).toBeNull(); @@ -2741,7 +2741,7 @@ describe('OAuth Authorization', () => { }); expect(tokens).toEqual(validTokens); - const request = mockFetch.mock.calls[0]![1]; + const request = mockFetch.mock.calls[0][1]; // Check headers expect(request.headers.get('Content-Type')).toBe('application/x-www-form-urlencoded'); @@ -2795,7 +2795,7 @@ describe('OAuth Authorization', () => { }); expect(tokens).toEqual(validTokens); - const request = mockFetch.mock.calls[0]![1]; + const request = mockFetch.mock.calls[0][1]; // Check Authorization header const authHeader = request.headers.get('Authorization'); @@ -2822,7 +2822,7 @@ describe('OAuth Authorization', () => { }); expect(tokens).toEqual(validTokens); - const request = mockFetch.mock.calls[0]![1]; + const request = mockFetch.mock.calls[0][1]; // Check no Authorization header expect(request.headers.get('Authorization')).toBeNull(); @@ -2836,7 +2836,7 @@ describe('OAuth Authorization', () => { describe('RequestInit headers passthrough', () => { it('custom headers from RequestInit are passed to auth discovery requests', async () => { - const { createFetchWithInit } = await import('@modelcontextprotocol/core'); + const { createFetchWithInit } = await import('../../src/shared/transport.js'); const customFetch = vi.fn().mockResolvedValue({ ok: true, @@ -2858,7 +2858,7 @@ describe('OAuth Authorization', () => { await discoverOAuthProtectedResourceMetadata('https://resource.example.com', undefined, wrappedFetch); expect(customFetch).toHaveBeenCalledTimes(1); - const [url, options] = customFetch.mock.calls[0]!; + const [url, options] = customFetch.mock.calls[0]; expect(url.toString()).toBe('https://resource.example.com/.well-known/oauth-protected-resource'); expect(options.headers).toMatchObject({ @@ -2869,7 +2869,7 @@ describe('OAuth Authorization', () => { }); it('auth-specific headers override base headers from RequestInit', async () => { - const { createFetchWithInit } = await import('@modelcontextprotocol/core'); + const { createFetchWithInit } = await import('../../src/shared/transport.js'); const customFetch = vi.fn().mockResolvedValue({ ok: true, @@ -2896,7 +2896,7 @@ describe('OAuth Authorization', () => { }); expect(customFetch).toHaveBeenCalled(); - const [, options] = customFetch.mock.calls[0]!; + const [, options] = customFetch.mock.calls[0]; // Auth-specific Accept header should override base Accept header expect(options.headers).toMatchObject({ @@ -2907,7 +2907,7 @@ describe('OAuth Authorization', () => { }); it('other RequestInit options are passed through', async () => { - const { createFetchWithInit } = await import('@modelcontextprotocol/core'); + const { createFetchWithInit } = await import('../../src/shared/transport.js'); const customFetch = vi.fn().mockResolvedValue({ ok: true, @@ -2931,7 +2931,7 @@ describe('OAuth Authorization', () => { await discoverOAuthProtectedResourceMetadata('https://resource.example.com', undefined, wrappedFetch); expect(customFetch).toHaveBeenCalledTimes(1); - const [, options] = customFetch.mock.calls[0]!; + const [, options] = customFetch.mock.calls[0]; // All RequestInit options should be preserved expect(options.credentials).toBe('include'); diff --git a/packages/client/test/client/cross-spawn.test.ts b/test/client/cross-spawn.test.ts similarity index 94% rename from packages/client/test/client/cross-spawn.test.ts rename to test/client/cross-spawn.test.ts index 8e4a80fc24..26ae682fe4 100644 --- a/packages/client/test/client/cross-spawn.test.ts +++ b/test/client/cross-spawn.test.ts @@ -1,10 +1,8 @@ -import type { ChildProcess } from 'node:child_process'; - -import type { JSONRPCMessage } from '@modelcontextprotocol/core'; +import { StdioClientTransport, getDefaultEnvironment } from '../../src/client/stdio.js'; import spawn from 'cross-spawn'; -import type { Mock, MockedFunction } from 'vitest'; - -import { getDefaultEnvironment, StdioClientTransport } from '../../src/client/stdio.js'; +import { JSONRPCMessage } from '../../src/types.js'; +import { ChildProcess } from 'node:child_process'; +import { Mock, MockedFunction } from 'vitest'; // mock cross-spawn vi.mock('cross-spawn'); diff --git a/test/integration/test/client/client.test.ts b/test/client/index.test.ts similarity index 97% rename from test/integration/test/client/client.test.ts rename to test/client/index.test.ts index 5574a2d849..9735eb2bac 100644 --- a/test/integration/test/client/client.test.ts +++ b/test/client/index.test.ts @@ -1,31 +1,36 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable no-constant-binary-expression */ /* eslint-disable @typescript-eslint/no-unused-expressions */ -import { Client, getSupportedElicitationModes } from '@modelcontextprotocol/client'; -import type { Prompt, Resource, Tool, Transport } from '@modelcontextprotocol/core'; +import { Client, getSupportedElicitationModes } from '../../src/client/index.js'; import { + RequestSchema, + NotificationSchema, + ResultSchema, + LATEST_PROTOCOL_VERSION, + SUPPORTED_PROTOCOL_VERSIONS, + InitializeRequestSchema, + ListResourcesRequestSchema, + ListToolsRequestSchema, + ListToolsResultSchema, + ListPromptsRequestSchema, CallToolRequestSchema, CallToolResultSchema, CreateMessageRequestSchema, - CreateTaskResultSchema, ElicitRequestSchema, ElicitResultSchema, - ErrorCode, - InitializeRequestSchema, - InMemoryTransport, - LATEST_PROTOCOL_VERSION, - ListPromptsRequestSchema, - ListResourcesRequestSchema, ListRootsRequestSchema, - ListToolsRequestSchema, - ListToolsResultSchema, + ErrorCode, McpError, - NotificationSchema, - RequestSchema, - ResultSchema, - SUPPORTED_PROTOCOL_VERSIONS -} from '@modelcontextprotocol/core'; -import { InMemoryTaskStore, McpServer, Server } from '@modelcontextprotocol/server'; + CreateTaskResultSchema, + Tool, + Prompt, + Resource +} from '../../src/types.js'; +import { Transport } from '../../src/shared/transport.js'; +import { Server } from '../../src/server/index.js'; +import { McpServer } from '../../src/server/mcp.js'; +import { InMemoryTransport } from '../../src/inMemory.js'; +import { InMemoryTaskStore } from '../../src/experimental/tasks/stores/in-memory.js'; import * as z3 from 'zod/v3'; import * as z4 from 'zod/v4'; @@ -1287,9 +1292,9 @@ test('should handle tool list changed notification with auto refresh', async () // Should be 1 notification with 2 tools because autoRefresh is true expect(notifications).toHaveLength(1); - expect(notifications[0]![0]).toBeNull(); - expect(notifications[0]![1]).toHaveLength(2); - expect(notifications[0]![1]?.[1]!.name).toBe('test-tool'); + expect(notifications[0][0]).toBeNull(); + expect(notifications[0][1]).toHaveLength(2); + expect(notifications[0][1]?.[1].name).toBe('test-tool'); }); /*** @@ -1347,8 +1352,8 @@ test('should handle tool list changed notification with manual refresh', async ( // Should be 1 notification with no tool data because autoRefresh is false expect(notifications).toHaveLength(1); - expect(notifications[0]![0]).toBeNull(); - expect(notifications[0]![1]).toBeNull(); + expect(notifications[0][0]).toBeNull(); + expect(notifications[0][1]).toBeNull(); }); /*** @@ -1407,9 +1412,9 @@ test('should handle prompt list changed notification with auto refresh', async ( // Should be 1 notification with 2 prompts because autoRefresh is true expect(notifications).toHaveLength(1); - expect(notifications[0]![0]).toBeNull(); - expect(notifications[0]![1]).toHaveLength(2); - expect(notifications[0]![1]?.[1]!.name).toBe('test-prompt'); + expect(notifications[0][0]).toBeNull(); + expect(notifications[0][1]).toHaveLength(2); + expect(notifications[0][1]?.[1].name).toBe('test-prompt'); }); /*** @@ -1462,9 +1467,9 @@ test('should handle resource list changed notification with auto refresh', async // Should be 1 notification with 2 resources because autoRefresh is true expect(notifications).toHaveLength(1); - expect(notifications[0]![0]).toBeNull(); - expect(notifications[0]![1]).toHaveLength(2); - expect(notifications[0]![1]?.[1]!.name).toBe('test-resource'); + expect(notifications[0][0]).toBeNull(); + expect(notifications[0][1]).toHaveLength(2); + expect(notifications[0][1]?.[1].name).toBe('test-resource'); }); /*** @@ -1548,10 +1553,10 @@ test('should handle multiple list changed handlers configured together', async ( // Both handlers should have received their respective notifications expect(toolNotifications).toHaveLength(1); - expect(toolNotifications[0]![1]).toHaveLength(2); + expect(toolNotifications[0][1]).toHaveLength(2); expect(promptNotifications).toHaveLength(1); - expect(promptNotifications[0]![1]).toHaveLength(2); + expect(promptNotifications[0][1]).toHaveLength(2); }); /*** @@ -1650,8 +1655,8 @@ test('should activate listChanged handler when server advertises capability', as // Handler SHOULD have been called expect(notifications).toHaveLength(1); - expect(notifications[0]![0]).toBeNull(); - expect(notifications[0]![1]).toHaveLength(1); + expect(notifications[0][0]).toBeNull(); + expect(notifications[0][1]).toHaveLength(1); }); /*** @@ -2414,7 +2419,7 @@ describe('Task-based execution', () => { // Verify task was created successfully by listing tasks const taskList = await client.experimental.tasks.listTasks(); expect(taskList.tasks.length).toBeGreaterThan(0); - const task = taskList.tasks[0]!; + const task = taskList.tasks[0]; expect(task.status).toBe('completed'); }); @@ -2488,7 +2493,7 @@ describe('Task-based execution', () => { // Query task status by listing tasks and getting the first one const taskList = await client.experimental.tasks.listTasks(); expect(taskList.tasks.length).toBeGreaterThan(0); - const task = taskList.tasks[0]!; + const task = taskList.tasks[0]; expect(task).toBeDefined(); expect(task.taskId).toBeDefined(); expect(task.status).toBe('completed'); @@ -3487,9 +3492,9 @@ test('should expose requestStream() method for streaming responses', async () => // Should have received only a result message (no task messages) expect(messages.length).toBe(1); - expect(messages[0]!.type).toBe('result'); - if (messages[0]!.type === 'result') { - expect(messages[0]!.result.content).toEqual([{ type: 'text', text: 'Tool result' }]); + expect(messages[0].type).toBe('result'); + if (messages[0].type === 'result') { + expect(messages[0].result.content).toEqual([{ type: 'text', text: 'Tool result' }]); } await client.close(); @@ -3542,9 +3547,9 @@ test('should expose callToolStream() method for streaming tool calls', async () // Should have received messages ending with result expect(messages.length).toBe(1); - expect(messages[0]!.type).toBe('result'); - if (messages[0]!.type === 'result') { - expect(messages[0]!.result.content).toEqual([{ type: 'text', text: 'Tool result' }]); + expect(messages[0].type).toBe('result'); + if (messages[0].type === 'result') { + expect(messages[0].result.content).toEqual([{ type: 'text', text: 'Tool result' }]); } await client.close(); @@ -3623,9 +3628,9 @@ test('should validate structured output in callToolStream()', async () => { // Should have received result with validated structured content expect(messages.length).toBe(1); - expect(messages[0]!.type).toBe('result'); - if (messages[0]!.type === 'result') { - expect(messages[0]!.result.structuredContent).toEqual({ value: 42 }); + expect(messages[0].type).toBe('result'); + if (messages[0].type === 'result') { + expect(messages[0].result.structuredContent).toEqual({ value: 42 }); } await client.close(); @@ -3699,9 +3704,9 @@ test('callToolStream() should yield error when structuredContent does not match } expect(messages.length).toBe(1); - expect(messages[0]!.type).toBe('error'); - if (messages[0]!.type === 'error') { - expect(messages[0]!.error.message).toMatch(/Structured content does not match the tool's output schema/); + expect(messages[0].type).toBe('error'); + if (messages[0].type === 'error') { + expect(messages[0].error.message).toMatch(/Structured content does not match the tool's output schema/); } await client.close(); @@ -3771,9 +3776,9 @@ test('callToolStream() should yield error when tool with outputSchema returns no } expect(messages.length).toBe(1); - expect(messages[0]!.type).toBe('error'); - if (messages[0]!.type === 'error') { - expect(messages[0]!.error.message).toMatch(/Tool test-tool has an output schema but did not return structured content/); + expect(messages[0].type).toBe('error'); + if (messages[0].type === 'error') { + expect(messages[0].error.message).toMatch(/Tool test-tool has an output schema but did not return structured content/); } await client.close(); @@ -3836,9 +3841,9 @@ test('callToolStream() should handle tools without outputSchema normally', async } expect(messages.length).toBe(1); - expect(messages[0]!.type).toBe('result'); - if (messages[0]!.type === 'result') { - expect(messages[0]!.result.content).toEqual([{ type: 'text', text: 'Normal response' }]); + expect(messages[0].type).toBe('result'); + if (messages[0].type === 'result') { + expect(messages[0].result.content).toEqual([{ type: 'text', text: 'Normal response' }]); } await client.close(); @@ -3931,10 +3936,10 @@ test('callToolStream() should handle complex JSON schema validation', async () = } expect(messages.length).toBe(1); - expect(messages[0]!.type).toBe('result'); - if (messages[0]!.type === 'result') { - expect(messages[0]!.result.structuredContent).toBeDefined(); - const structuredContent = messages[0]!.result.structuredContent as { name: string; age: number }; + expect(messages[0].type).toBe('result'); + if (messages[0].type === 'result') { + expect(messages[0].result.structuredContent).toBeDefined(); + const structuredContent = messages[0].result.structuredContent as { name: string; age: number }; expect(structuredContent.name).toBe('John Doe'); expect(structuredContent.age).toBe(30); } @@ -4010,9 +4015,9 @@ test('callToolStream() should yield error with additional properties when not al } expect(messages.length).toBe(1); - expect(messages[0]!.type).toBe('error'); - if (messages[0]!.type === 'error') { - expect(messages[0]!.error.message).toMatch(/Structured content does not match the tool's output schema/); + expect(messages[0].type).toBe('error'); + if (messages[0].type === 'error') { + expect(messages[0].error.message).toMatch(/Structured content does not match the tool's output schema/); } await client.close(); @@ -4085,10 +4090,10 @@ test('callToolStream() should not validate structuredContent when isError is tru // Should have received result (not error), with isError flag set expect(messages.length).toBe(1); - expect(messages[0]!.type).toBe('result'); - if (messages[0]!.type === 'result') { - expect(messages[0]!.result.isError).toBe(true); - expect(messages[0]!.result.content).toEqual([{ type: 'text', text: 'Something went wrong' }]); + expect(messages[0].type).toBe('result'); + if (messages[0].type === 'result') { + expect(messages[0].result.isError).toBe(true); + expect(messages[0].result.content).toEqual([{ type: 'text', text: 'Something went wrong' }]); } await client.close(); diff --git a/packages/client/test/client/middleware.test.ts b/test/client/middleware.test.ts similarity index 96% rename from packages/client/test/client/middleware.test.ts rename to test/client/middleware.test.ts index 451715423d..06bda69c82 100644 --- a/packages/client/test/client/middleware.test.ts +++ b/test/client/middleware.test.ts @@ -1,8 +1,7 @@ -import type { FetchLike } from '@modelcontextprotocol/core'; -import type { Mocked, MockedFunction, MockInstance } from 'vitest'; - -import type { OAuthClientProvider } from '../../src/client/auth.js'; -import { applyMiddlewares, createMiddleware, withLogging, withOAuth } from '../../src/client/middleware.js'; +import { withOAuth, withLogging, applyMiddlewares, createMiddleware } from '../../src/client/middleware.js'; +import { OAuthClientProvider } from '../../src/client/auth.js'; +import { FetchLike } from '../../src/shared/transport.js'; +import { MockInstance, Mocked, MockedFunction } from 'vitest'; vi.mock('../../src/client/auth.js', async () => { const actual = await vi.importActual('../../src/client/auth.js'); @@ -65,7 +64,7 @@ describe('withOAuth', () => { ); const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs![1]?.headers as Headers; + const headers = callArgs[1]?.headers as Headers; expect(headers.get('Authorization')).toBe('Bearer test-token'); }); @@ -91,7 +90,7 @@ describe('withOAuth', () => { ); const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs![1]?.headers as Headers; + const headers = callArgs[1]?.headers as Headers; expect(headers.get('Authorization')).toBe('Bearer test-token'); }); @@ -106,7 +105,7 @@ describe('withOAuth', () => { expect(mockFetch).toHaveBeenCalledTimes(1); const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs![1]?.headers as Headers; + const headers = callArgs[1]?.headers as Headers; expect(headers.get('Authorization')).toBeNull(); }); @@ -153,7 +152,7 @@ describe('withOAuth', () => { // Verify the retry used the new token const retryCallArgs = mockFetch.mock.calls[1]; - const retryHeaders = retryCallArgs![1]?.headers as Headers; + const retryHeaders = retryCallArgs[1]?.headers as Headers; expect(retryHeaders.get('Authorization')).toBe('Bearer new-token'); }); @@ -201,7 +200,7 @@ describe('withOAuth', () => { // Verify the retry used the new token const retryCallArgs = mockFetch.mock.calls[1]; - const retryHeaders = retryCallArgs![1]?.headers as Headers; + const retryHeaders = retryCallArgs[1]?.headers as Headers; expect(retryHeaders.get('Authorization')).toBe('Bearer new-token'); }); @@ -291,7 +290,7 @@ describe('withOAuth', () => { ); const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs![1]?.headers as Headers; + const headers = callArgs[1]?.headers as Headers; expect(headers.get('Content-Type')).toBe('application/json'); expect(headers.get('Authorization')).toBe('Bearer test-token'); }); @@ -493,7 +492,7 @@ describe('withLogging', () => { responseHeaders: undefined }); - const logCall = mockLogger.mock.calls[0]![0]; + const logCall = mockLogger.mock.calls[0][0]; expect(logCall.requestHeaders?.get('Authorization')).toBe('Bearer token'); expect(logCall.requestHeaders?.get('Content-Type')).toBe('application/json'); }); @@ -516,7 +515,7 @@ describe('withLogging', () => { await enhancedFetch('https://api.example.com/data'); - const logCall = mockLogger.mock.calls[0]![0]; + const logCall = mockLogger.mock.calls[0][0]; expect(logCall.responseHeaders?.get('Content-Type')).toBe('application/json'); expect(logCall.responseHeaders?.get('Cache-Control')).toBe('no-cache'); }); @@ -610,7 +609,7 @@ describe('withLogging', () => { await enhancedFetch('https://api.example.com/data'); - const logCall = mockLogger.mock.calls[0]![0]; + const logCall = mockLogger.mock.calls[0][0]; expect(logCall.duration).toBeGreaterThanOrEqual(90); // Allow some margin for timing }); }); @@ -655,7 +654,7 @@ describe('applyMiddleware', () => { ); const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs![1]?.headers as Headers; + const headers = callArgs[1]?.headers as Headers; expect(headers.get('X-Middleware-1')).toBe('applied'); }); @@ -687,7 +686,7 @@ describe('applyMiddleware', () => { await composedFetch('https://api.example.com/data'); const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs![1]?.headers as Headers; + const headers = callArgs[1]?.headers as Headers; expect(headers.get('X-Middleware-1')).toBe('applied'); expect(headers.get('X-Middleware-2')).toBe('applied'); expect(headers.get('X-Middleware-3')).toBe('applied'); @@ -712,7 +711,7 @@ describe('applyMiddleware', () => { // Should have both Authorization header and logging const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs![1]?.headers as Headers; + const headers = callArgs[1]?.headers as Headers; expect(headers.get('Authorization')).toBe('Bearer test-token'); expect(mockLogger).toHaveBeenCalledWith({ method: 'GET', @@ -812,7 +811,7 @@ describe('Integration Tests', () => { ); const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs![1]?.headers as Headers; + const headers = callArgs[1]?.headers as Headers; expect(headers.get('Authorization')).toBe('Bearer sse-token'); expect(headers.get('Content-Type')).toBe('application/json'); }); @@ -858,7 +857,7 @@ describe('Integration Tests', () => { }); const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs![1]?.headers as Headers; + const headers = callArgs[1]?.headers as Headers; expect(headers.get('Authorization')).toBe('Bearer streamable-token'); expect(headers.get('Accept')).toBe('application/json, text/event-stream'); }); @@ -944,7 +943,7 @@ describe('createMiddleware', () => { ); const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs![1]?.headers as Headers; + const headers = callArgs[1]?.headers as Headers; expect(headers.get('X-Custom-Header')).toBe('custom-value'); }); @@ -970,13 +969,13 @@ describe('createMiddleware', () => { // Test API route await enhancedFetch('https://example.com/api/users'); let callArgs = mockFetch.mock.calls[0]; - const headers = callArgs![1]?.headers as Headers; + const headers = callArgs[1]?.headers as Headers; expect(headers.get('X-API-Version')).toBe('v2'); // Test non-API route await enhancedFetch('https://example.com/public/page'); callArgs = mockFetch.mock.calls[1]; - const maybeHeaders = callArgs![1]?.headers as Headers | undefined; + const maybeHeaders = callArgs[1]?.headers as Headers | undefined; expect(maybeHeaders?.get('X-API-Version')).toBeUndefined(); }); @@ -1017,7 +1016,7 @@ describe('createMiddleware', () => { const response = await next(input, init); if (response.headers.get('content-type')?.includes('application/json')) { - const data = (await response.json()) as Record; + const data = await response.json(); const transformed = { ...data, timestamp: 123456789 }; return new Response(JSON.stringify(transformed), { @@ -1092,7 +1091,7 @@ describe('createMiddleware', () => { await enhancedFetch('https://api.example.com/data'); const callArgs = mockFetch.mock.calls[0]; - const headers = callArgs![1]?.headers as Headers; + const headers = callArgs[1]?.headers as Headers; expect(headers.get('Authorization')).toBe('Custom token'); }); diff --git a/packages/client/test/client/sse.test.ts b/test/client/sse.test.ts similarity index 98% rename from packages/client/test/client/sse.test.ts rename to test/client/sse.test.ts index 94e12c652f..6574b60b8b 100644 --- a/packages/client/test/client/sse.test.ts +++ b/test/client/sse.test.ts @@ -1,15 +1,12 @@ -import type { IncomingMessage, Server, ServerResponse } from 'node:http'; -import { createServer } from 'node:http'; -import type { AddressInfo } from 'node:net'; - -import type { JSONRPCMessage, OAuthTokens } from '@modelcontextprotocol/core'; -import { InvalidClientError, InvalidGrantError, UnauthorizedClientError } from '@modelcontextprotocol/core'; -import { listenOnRandomPort } from '@modelcontextprotocol/test-helpers'; -import type { Mock, Mocked, MockedFunction, MockInstance } from 'vitest'; - -import type { OAuthClientProvider } from '../../src/client/auth.js'; -import { UnauthorizedError } from '../../src/client/auth.js'; +import { createServer, ServerResponse, type IncomingMessage, type Server } from 'node:http'; +import { JSONRPCMessage } from '../../src/types.js'; import { SSEClientTransport } from '../../src/client/sse.js'; +import { OAuthClientProvider, UnauthorizedError } from '../../src/client/auth.js'; +import { OAuthTokens } from '../../src/shared/auth.js'; +import { InvalidClientError, InvalidGrantError, UnauthorizedClientError } from '../../src/server/auth/errors.js'; +import { Mock, Mocked, MockedFunction, MockInstance } from 'vitest'; +import { listenOnRandomPort } from '../helpers/http.js'; +import { AddressInfo } from 'node:net'; describe('SSEClientTransport', () => { let resourceServer: Server; @@ -172,7 +169,7 @@ describe('SSEClientTransport', () => { await new Promise(resolve => setTimeout(resolve, 50)); expect(errors).toHaveLength(1); - expect(errors[0]!.message).toMatch(/JSON/); + expect(errors[0].message).toMatch(/JSON/); }); it('handles messages via POST requests', async () => { @@ -313,7 +310,7 @@ describe('SSEClientTransport', () => { await transport.send(message); - const calledHeaders = (global.fetch as Mock).mock.calls[0]![1].headers; + const calledHeaders = (global.fetch as Mock).mock.calls[0][1].headers; expect(calledHeaders.get('Authorization')).toBe('Bearer test-token'); expect(calledHeaders.get('X-Custom-Header')).toBe('custom-value'); expect(calledHeaders.get('content-type')).toBe('application/json'); @@ -322,7 +319,7 @@ describe('SSEClientTransport', () => { await transport.send(message); - const updatedHeaders = (global.fetch as Mock).mock.calls[1]![1].headers; + const updatedHeaders = (global.fetch as Mock).mock.calls[1][1].headers; expect(updatedHeaders.get('X-Custom-Header')).toBe('updated-value'); } finally { global.fetch = originalFetch; @@ -356,7 +353,7 @@ describe('SSEClientTransport', () => { await transport.send(message); - const calledHeaders = (global.fetch as Mock).mock.calls[0]![1].headers; + const calledHeaders = (global.fetch as Mock).mock.calls[0][1].headers; expect(calledHeaders.get('Authorization')).toBe('Bearer test-token'); expect(calledHeaders.get('X-Custom-Header')).toBe('custom-value'); expect(calledHeaders.get('content-type')).toBe('application/json'); @@ -365,7 +362,7 @@ describe('SSEClientTransport', () => { await transport.send(message); - const updatedHeaders = (global.fetch as Mock).mock.calls[1]![1].headers; + const updatedHeaders = (global.fetch as Mock).mock.calls[1][1].headers; expect(updatedHeaders.get('X-Custom-Header')).toBe('updated-value'); } finally { global.fetch = originalFetch; @@ -390,7 +387,7 @@ describe('SSEClientTransport', () => { await transport.send({ jsonrpc: '2.0', id: '1', method: 'test', params: {} }); - const calledHeaders = (global.fetch as Mock).mock.calls[0]![1].headers; + const calledHeaders = (global.fetch as Mock).mock.calls[0][1].headers; expect(calledHeaders.get('Authorization')).toBe('Bearer test-token'); expect(calledHeaders.get('X-Custom-Header')).toBe('custom-value'); expect(calledHeaders.get('content-type')).toBe('application/json'); diff --git a/packages/client/test/client/stdio.test.ts b/test/client/stdio.test.ts similarity index 86% rename from packages/client/test/client/stdio.test.ts rename to test/client/stdio.test.ts index 28a7834bcb..52a871ee1c 100644 --- a/packages/client/test/client/stdio.test.ts +++ b/test/client/stdio.test.ts @@ -1,7 +1,5 @@ -import type { JSONRPCMessage } from '@modelcontextprotocol/core'; - -import type { StdioServerParameters } from '../../src/client/stdio.js'; -import { StdioClientTransport } from '../../src/client/stdio.js'; +import { JSONRPCMessage } from '../../src/types.js'; +import { StdioClientTransport, StdioServerParameters } from '../../src/client/stdio.js'; // Configure default server parameters based on OS // Uses 'more' command for Windows and 'tee' command for Unix/Linux @@ -61,8 +59,8 @@ test('should read messages', async () => { }); await client.start(); - await client.send(messages[0]!); - await client.send(messages[1]!); + await client.send(messages[0]); + await client.send(messages[1]); await finished; expect(readMessages).toEqual(messages); diff --git a/packages/client/test/client/streamableHttp.test.ts b/test/client/streamableHttp.test.ts similarity index 98% rename from packages/client/test/client/streamableHttp.test.ts rename to test/client/streamableHttp.test.ts index 0c5d2dc018..52c8f10748 100644 --- a/packages/client/test/client/streamableHttp.test.ts +++ b/test/client/streamableHttp.test.ts @@ -1,12 +1,9 @@ -import type { JSONRPCMessage, JSONRPCRequest } from '@modelcontextprotocol/core'; -import { InvalidClientError, InvalidGrantError, UnauthorizedClientError } from '@modelcontextprotocol/core'; +import { StartSSEOptions, StreamableHTTPClientTransport, StreamableHTTPReconnectionOptions } from '../../src/client/streamableHttp.js'; +import { OAuthClientProvider, UnauthorizedError } from '../../src/client/auth.js'; +import { JSONRPCMessage, JSONRPCRequest } from '../../src/types.js'; +import { InvalidClientError, InvalidGrantError, UnauthorizedClientError } from '../../src/server/auth/errors.js'; import { type Mock, type Mocked } from 'vitest'; -import type { OAuthClientProvider } from '../../src/client/auth.js'; -import { UnauthorizedError } from '../../src/client/auth.js'; -import type { StartSSEOptions, StreamableHTTPReconnectionOptions } from '../../src/client/streamableHttp.js'; -import { StreamableHTTPClientTransport } from '../../src/client/streamableHttp.js'; - describe('StreamableHTTPClientTransport', () => { let transport: StreamableHTTPClientTransport; let mockAuthProvider: Mocked; @@ -117,7 +114,7 @@ describe('StreamableHTTPClientTransport', () => { // Check that second request included session ID header const calls = (global.fetch as Mock).mock.calls; - const lastCall = calls[calls.length - 1]!; + const lastCall = calls[calls.length - 1]; expect(lastCall[1].headers).toBeDefined(); expect(lastCall[1].headers.get('mcp-session-id')).toBe('test-session-id'); }); @@ -154,7 +151,7 @@ describe('StreamableHTTPClientTransport', () => { // Verify the DELETE request was sent with the session ID const calls = (global.fetch as Mock).mock.calls; - const lastCall = calls[calls.length - 1]!; + const lastCall = calls[calls.length - 1]; expect(lastCall[1].method).toBe('DELETE'); expect(lastCall[1].headers.get('mcp-session-id')).toBe('test-session-id'); @@ -415,7 +412,7 @@ describe('StreamableHTTPClientTransport', () => { // Verify fetch was called with the lastEventId header expect(fetchSpy).toHaveBeenCalled(); - const fetchCall = fetchSpy.mock.calls[0]!; + const fetchCall = fetchSpy.mock.calls[0]; const headers = fetchCall[1].headers; expect(headers.get('last-event-id')).toBe('test-event-id'); }); @@ -775,8 +772,8 @@ describe('StreamableHTTPClientTransport', () => { ); // THE KEY ASSERTION: A second fetch call proves reconnection was attempted. expect(fetchMock).toHaveBeenCalledTimes(2); - expect(fetchMock.mock.calls[0]![1]?.method).toBe('GET'); - expect(fetchMock.mock.calls[1]![1]?.method).toBe('GET'); + expect(fetchMock.mock.calls[0][1]?.method).toBe('GET'); + expect(fetchMock.mock.calls[1][1]?.method).toBe('GET'); }); it('should NOT reconnect a POST-initiated stream that fails', async () => { @@ -825,7 +822,7 @@ describe('StreamableHTTPClientTransport', () => { // ASSERT // THE KEY ASSERTION: Fetch was only called ONCE. No reconnection was attempted. expect(fetchMock).toHaveBeenCalledTimes(1); - expect(fetchMock.mock.calls[0]![1]?.method).toBe('POST'); + expect(fetchMock.mock.calls[0][1]?.method).toBe('POST'); }); it('should reconnect a POST-initiated stream after receiving a priming event', async () => { @@ -941,7 +938,7 @@ describe('StreamableHTTPClientTransport', () => { // THE KEY ASSERTION: Fetch was called ONCE only - no reconnection! // The response was received, so no need to reconnect. expect(fetchMock).toHaveBeenCalledTimes(1); - expect(fetchMock.mock.calls[0]![1]?.method).toBe('POST'); + expect(fetchMock.mock.calls[0][1]?.method).toBe('POST'); }); it('should not attempt reconnection after close() is called', async () => { @@ -992,7 +989,7 @@ describe('StreamableHTTPClientTransport', () => { // ASSERT // Only 1 call: the initial POST. No reconnection attempts after close(). expect(fetchMock).toHaveBeenCalledTimes(1); - expect(fetchMock.mock.calls[0]![1]?.method).toBe('POST'); + expect(fetchMock.mock.calls[0][1]?.method).toBe('POST'); }); it('should not throw JSON parse error on priming events with empty data', async () => { @@ -1490,11 +1487,11 @@ describe('StreamableHTTPClientTransport', () => { // Should have attempted reconnection expect(fetchMock).toHaveBeenCalledTimes(2); - expect(fetchMock.mock.calls[0]![1]?.method).toBe('GET'); - expect(fetchMock.mock.calls[1]![1]?.method).toBe('GET'); + expect(fetchMock.mock.calls[0][1]?.method).toBe('GET'); + expect(fetchMock.mock.calls[1][1]?.method).toBe('GET'); // Second call should include Last-Event-ID - const secondCallHeaders = fetchMock.mock.calls[1]![1]?.headers; + const secondCallHeaders = fetchMock.mock.calls[1][1]?.headers; expect(secondCallHeaders?.get('last-event-id')).toBe('evt-1'); }); }); diff --git a/examples/shared/test/demoInMemoryOAuthProvider.test.ts b/test/examples/server/demoInMemoryOAuthProvider.test.ts similarity index 96% rename from examples/shared/test/demoInMemoryOAuthProvider.test.ts rename to test/examples/server/demoInMemoryOAuthProvider.test.ts index 4018dddbe9..a49a8b426a 100644 --- a/examples/shared/test/demoInMemoryOAuthProvider.test.ts +++ b/test/examples/server/demoInMemoryOAuthProvider.test.ts @@ -1,11 +1,10 @@ -import type { OAuthClientInformationFull } from '@modelcontextprotocol/core'; -import type { AuthorizationParams } from '@modelcontextprotocol/server'; -import { InvalidRequestError } from '@modelcontextprotocol/server'; -import { createExpressResponseMock } from '@modelcontextprotocol/test-helpers'; -import type { Response } from 'express'; -import { beforeEach, describe, expect, it } from 'vitest'; - -import { DemoInMemoryAuthProvider, DemoInMemoryClientsStore } from '../src/demoInMemoryOAuthProvider.js'; +import { Response } from 'express'; +import { DemoInMemoryAuthProvider, DemoInMemoryClientsStore } from '../../../src/examples/server/demoInMemoryOAuthProvider.js'; +import { AuthorizationParams } from '../../../src/server/auth/provider.js'; +import { OAuthClientInformationFull } from '../../../src/shared/auth.js'; +import { InvalidRequestError } from '../../../src/server/auth/errors.js'; + +import { createExpressResponseMock } from '../../helpers/http.js'; describe('DemoInMemoryAuthProvider', () => { let provider: DemoInMemoryAuthProvider; diff --git a/packages/core/test/experimental/in-memory.test.ts b/test/experimental/tasks/stores/in-memory.test.ts similarity index 95% rename from packages/core/test/experimental/in-memory.test.ts rename to test/experimental/tasks/stores/in-memory.test.ts index 6520efcec6..ceef6c6d84 100644 --- a/packages/core/test/experimental/in-memory.test.ts +++ b/test/experimental/tasks/stores/in-memory.test.ts @@ -1,8 +1,7 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; - -import type { QueuedMessage } from '../../src/experimental/tasks/interfaces.js'; -import { InMemoryTaskMessageQueue, InMemoryTaskStore } from '../../src/experimental/tasks/stores/in-memory.js'; -import type { Request, TaskCreationParams } from '../../src/types/types.js'; +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { InMemoryTaskStore, InMemoryTaskMessageQueue } from '../../../../src/experimental/tasks/stores/in-memory.js'; +import { TaskCreationParams, Request } from '../../../../src/types.js'; +import { QueuedMessage } from '../../../../src/experimental/tasks/interfaces.js'; describe('InMemoryTaskStore', () => { let store: InMemoryTaskStore; @@ -241,7 +240,7 @@ describe('InMemoryTaskStore', () => { expect(task?.status).toBe('completed'); const storedResult = await store.getTaskResult(taskId); - expect(storedResult).toStrictEqual(result); + expect(storedResult).toEqual(result); }); it('should throw if task not found', async () => { @@ -275,7 +274,7 @@ describe('InMemoryTaskStore', () => { expect(task?.status).toBe('failed'); const storedResult = await store.getTaskResult(taskId); - expect(storedResult).toStrictEqual(result); + expect(storedResult).toEqual(result); }); it('should reject storing result for task already in failed status', async () => { @@ -349,7 +348,7 @@ describe('InMemoryTaskStore', () => { await store.storeTaskResult(createdTask.taskId, 'completed', result); const retrieved = await store.getTaskResult(createdTask.taskId); - expect(retrieved).toStrictEqual(result); + expect(retrieved).toEqual(result); }); }); @@ -570,14 +569,14 @@ describe('InMemoryTaskStore', () => { it('should return empty array when no tasks', () => { const tasks = store.getAllTasks(); - expect(tasks).toStrictEqual([]); + expect(tasks).toEqual([]); }); }); describe('listTasks', () => { it('should return empty list when no tasks', async () => { const result = await store.listTasks(); - expect(result.tasks).toStrictEqual([]); + expect(result.tasks).toEqual([]); expect(result.nextCursor).toBeUndefined(); }); @@ -690,7 +689,7 @@ describe('InMemoryTaskMessageQueue', () => { await queue.enqueue('task-1', requestMessage); const dequeued = await queue.dequeue('task-1'); - expect(dequeued).toStrictEqual(requestMessage); + expect(dequeued).toEqual(requestMessage); }); it('should enqueue and dequeue notification messages', async () => { @@ -707,7 +706,7 @@ describe('InMemoryTaskMessageQueue', () => { await queue.enqueue('task-2', notificationMessage); const dequeued = await queue.dequeue('task-2'); - expect(dequeued).toStrictEqual(notificationMessage); + expect(dequeued).toEqual(notificationMessage); }); it('should enqueue and dequeue response messages', async () => { @@ -724,7 +723,7 @@ describe('InMemoryTaskMessageQueue', () => { await queue.enqueue('task-3', responseMessage); const dequeued = await queue.dequeue('task-3'); - expect(dequeued).toStrictEqual(responseMessage); + expect(dequeued).toEqual(responseMessage); }); it('should return undefined when dequeuing from empty queue', async () => { @@ -768,9 +767,9 @@ describe('InMemoryTaskMessageQueue', () => { await queue.enqueue('task-fifo', notification); await queue.enqueue('task-fifo', response); - expect(await queue.dequeue('task-fifo')).toStrictEqual(request); - expect(await queue.dequeue('task-fifo')).toStrictEqual(notification); - expect(await queue.dequeue('task-fifo')).toStrictEqual(response); + expect(await queue.dequeue('task-fifo')).toEqual(request); + expect(await queue.dequeue('task-fifo')).toEqual(notification); + expect(await queue.dequeue('task-fifo')).toEqual(response); expect(await queue.dequeue('task-fifo')).toBeUndefined(); }); }); @@ -815,14 +814,14 @@ describe('InMemoryTaskMessageQueue', () => { const all = await queue.dequeueAll('task-all'); expect(all).toHaveLength(3); - expect(all[0]).toStrictEqual(request); - expect(all[1]).toStrictEqual(response); - expect(all[2]).toStrictEqual(notification); + expect(all[0]).toEqual(request); + expect(all[1]).toEqual(response); + expect(all[2]).toEqual(notification); }); it('should return empty array for non-existent task', async () => { const all = await queue.dequeueAll('non-existent'); - expect(all).toStrictEqual([]); + expect(all).toEqual([]); }); it('should clear the queue after dequeueAll', async () => { @@ -905,8 +904,8 @@ describe('InMemoryTaskMessageQueue', () => { await queue.enqueue('task-a', message1); await queue.enqueue('task-b', message2); - expect(await queue.dequeue('task-a')).toStrictEqual(message1); - expect(await queue.dequeue('task-b')).toStrictEqual(message2); + expect(await queue.dequeue('task-a')).toEqual(message1); + expect(await queue.dequeue('task-b')).toEqual(message2); expect(await queue.dequeue('task-a')).toBeUndefined(); expect(await queue.dequeue('task-b')).toBeUndefined(); }); @@ -930,7 +929,7 @@ describe('InMemoryTaskMessageQueue', () => { await queue.enqueue('task-error', errorResponse); const dequeued = await queue.dequeue('task-error'); - expect(dequeued).toStrictEqual(errorResponse); + expect(dequeued).toEqual(errorResponse); expect(dequeued?.type).toBe('error'); }); }); diff --git a/test/integration/test/experimental/tasks/task-listing.test.ts b/test/experimental/tasks/task-listing.test.ts similarity index 94% rename from test/integration/test/experimental/tasks/task-listing.test.ts rename to test/experimental/tasks/task-listing.test.ts index 28b39bb3b0..bf51f14048 100644 --- a/test/integration/test/experimental/tasks/task-listing.test.ts +++ b/test/experimental/tasks/task-listing.test.ts @@ -1,6 +1,5 @@ -import { ErrorCode, McpError } from '@modelcontextprotocol/core'; -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; - +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { ErrorCode, McpError } from '../../../src/types.js'; import { createInMemoryTaskEnvironment } from '../../helpers/mcp.js'; describe('Task Listing with Pagination', () => { @@ -74,7 +73,7 @@ describe('Task Listing with Pagination', () => { // Get all tasks to get a valid cursor const allTasks = taskStore.getAllTasks(); - const validCursor = allTasks[2]!.taskId; + const validCursor = allTasks[2].taskId; // Use the cursor - should work even though we don't know its internal structure const result = await client.experimental.tasks.listTasks(validCursor); @@ -110,7 +109,7 @@ describe('Task Listing with Pagination', () => { // Verify it's also accessible via tasks/list const listResult = await client.experimental.tasks.listTasks(); expect(listResult.tasks).toHaveLength(1); - expect(listResult.tasks[0]!.taskId).toBe(task.taskId); + expect(listResult.tasks[0].taskId).toBe(task.taskId); }); it('should not include related-task metadata in list response', async () => { diff --git a/test/integration/test/experimental/tasks/task.test.ts b/test/experimental/tasks/task.test.ts similarity index 95% rename from test/integration/test/experimental/tasks/task.test.ts rename to test/experimental/tasks/task.test.ts index 8a99fe513a..37e3938d28 100644 --- a/test/integration/test/experimental/tasks/task.test.ts +++ b/test/experimental/tasks/task.test.ts @@ -1,6 +1,6 @@ -import { isTerminal } from '@modelcontextprotocol/core'; -import type { Task } from '@modelcontextprotocol/server'; -import { describe, expect, it } from 'vitest'; +import { describe, it, expect } from 'vitest'; +import { isTerminal } from '../../../src/experimental/tasks/interfaces.js'; +import type { Task } from '../../../src/types.js'; describe('Task utility functions', () => { describe('isTerminal', () => { diff --git a/test/helpers/eslint.config.mjs b/test/helpers/eslint.config.mjs deleted file mode 100644 index 951c9f3a91..0000000000 --- a/test/helpers/eslint.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -// @ts-check - -import baseConfig from '@modelcontextprotocol/eslint-config'; - -export default baseConfig; diff --git a/test/helpers/src/helpers/http.ts b/test/helpers/http.ts similarity index 85% rename from test/helpers/src/helpers/http.ts rename to test/helpers/http.ts index 86252e10f3..291cc37fab 100644 --- a/test/helpers/src/helpers/http.ts +++ b/test/helpers/http.ts @@ -1,7 +1,7 @@ -import type { Server, ServerResponse } from 'node:http'; -import type { AddressInfo } from 'node:net'; - +import type http from 'node:http'; +import { type Server } from 'node:http'; import type { Response } from 'express'; +import { AddressInfo } from 'node:net'; import { vi } from 'vitest'; /** @@ -84,13 +84,13 @@ export function createExpressResponseMock(options: { trackRedirectUrl?: boolean * All core methods are jest/vitest fns returning `this` so that * tests can assert on writeHead/write/on/end calls. */ -export function createNodeServerResponseMock(): ServerResponse { +export function createNodeServerResponseMock(): http.ServerResponse { const res = { - writeHead: vi.fn().mockReturnThis(), - write: vi.fn().mockReturnThis(), - on: vi.fn().mockReturnThis(), - end: vi.fn().mockReturnThis() + writeHead: vi.fn().mockReturnThis(), + write: vi.fn().mockReturnThis(), + on: vi.fn().mockReturnThis(), + end: vi.fn().mockReturnThis() }; - return res as unknown as ServerResponse; + return res as unknown as http.ServerResponse; } diff --git a/test/integration/test/helpers/mcp.ts b/test/helpers/mcp.ts similarity index 82% rename from test/integration/test/helpers/mcp.ts rename to test/helpers/mcp.ts index 5c53c7a925..6cd08fdf00 100644 --- a/test/integration/test/helpers/mcp.ts +++ b/test/helpers/mcp.ts @@ -1,7 +1,8 @@ -import { Client } from '@modelcontextprotocol/client'; -import { InMemoryTransport } from '@modelcontextprotocol/core'; -import type { ClientCapabilities, ServerCapabilities } from '@modelcontextprotocol/server'; -import { InMemoryTaskMessageQueue, InMemoryTaskStore, Server } from '@modelcontextprotocol/server'; +import { InMemoryTransport } from '../../src/inMemory.js'; +import { Client } from '../../src/client/index.js'; +import { Server } from '../../src/server/index.js'; +import { InMemoryTaskStore, InMemoryTaskMessageQueue } from '../../src/experimental/tasks/stores/in-memory.js'; +import type { ClientCapabilities, ServerCapabilities } from '../../src/types.js'; export interface InMemoryTaskEnvironment { client: Client; diff --git a/test/helpers/src/helpers/oauth.ts b/test/helpers/oauth.ts similarity index 90% rename from test/helpers/src/helpers/oauth.ts rename to test/helpers/oauth.ts index 15780beeee..c08350efff 100644 --- a/test/helpers/src/helpers/oauth.ts +++ b/test/helpers/oauth.ts @@ -1,5 +1,4 @@ -import type { FetchLike } from '@modelcontextprotocol/core'; -import { vi } from 'vitest'; +import type { FetchLike } from '../../src/shared/transport.js'; export interface MockOAuthFetchOptions { resourceServerUrl: string; @@ -77,13 +76,12 @@ export function createMockOAuthFetch(options: MockOAuthFetchOptions): FetchLike }; } -type MockFetch = (...args: unknown[]) => unknown; - /** * Helper to install a vi.fn-based global.fetch mock for tests that rely on global fetch. */ -export function mockGlobalFetch(): MockFetch { - const mockFetch = vi.fn() as unknown as MockFetch; - (globalThis as { fetch?: MockFetch }).fetch = mockFetch; +export function mockGlobalFetch() { + const mockFetch = vi.fn(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (globalThis as any).fetch = mockFetch; return mockFetch; } diff --git a/test/helpers/package.json b/test/helpers/package.json deleted file mode 100644 index 3d17b9d85a..0000000000 --- a/test/helpers/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "@modelcontextprotocol/test-helpers", - "private": true, - "version": "2.0.0-alpha.0", - "description": "Model Context Protocol implementation for TypeScript", - "license": "MIT", - "author": "Anthropic, PBC (https://anthropic.com)", - "homepage": "https://modelcontextprotocol.io", - "bugs": "https://github.com/modelcontextprotocol/typescript-sdk/issues", - "type": "module", - "repository": { - "type": "git", - "url": "git+https://github.com/modelcontextprotocol/typescript-sdk.git" - }, - "engines": { - "node": ">=20", - "pnpm": ">=10.24.0" - }, - "packageManager": "pnpm@10.24.0", - "keywords": [ - "modelcontextprotocol", - "mcp" - ], - "scripts": { - "lint": "eslint src/ && prettier --ignore-path ../../.prettierignore --check .", - "lint:fix": "eslint src/ --fix && prettier --ignore-path ../../.prettierignore --write .", - "check": "npm run typecheck && npm run lint", - "start": "npm run server", - "server": "tsx watch --clear-screen=false scripts/cli.ts server", - "client": "tsx scripts/cli.ts client" - }, - "devDependencies": { - "@modelcontextprotocol/core": "workspace:^", - "@modelcontextprotocol/client": "workspace:^", - "@modelcontextprotocol/server": "workspace:^", - "zod": "catalog:runtimeShared", - "vitest": "catalog:devTools", - "@modelcontextprotocol/tsconfig": "workspace:^", - "@modelcontextprotocol/vitest-config": "workspace:^", - "@modelcontextprotocol/eslint-config": "workspace:^" - } -} diff --git a/test/helpers/src/fixtures/zodTestMatrix.ts b/test/helpers/src/fixtures/zodTestMatrix.ts deleted file mode 100644 index fc4ee63db1..0000000000 --- a/test/helpers/src/fixtures/zodTestMatrix.ts +++ /dev/null @@ -1,22 +0,0 @@ -import * as z3 from 'zod/v3'; -import * as z4 from 'zod/v4'; - -// Shared Zod namespace type that exposes the common surface area used in tests. -export type ZNamespace = typeof z3 & typeof z4; - -export const zodTestMatrix = [ - { - zodVersionLabel: 'Zod v3', - z: z3 as ZNamespace, - isV3: true as const, - isV4: false as const - }, - { - zodVersionLabel: 'Zod v4', - z: z4 as ZNamespace, - isV3: false as const, - isV4: true as const - } -] as const; - -export type ZodMatrixEntry = (typeof zodTestMatrix)[number]; diff --git a/test/helpers/src/index.ts b/test/helpers/src/index.ts deleted file mode 100644 index 2154c889cd..0000000000 --- a/test/helpers/src/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from './fixtures/zodTestMatrix.js'; -export * from './helpers/http.js'; -export * from './helpers/oauth.js'; -export * from './helpers/tasks.js'; diff --git a/test/helpers/src/helpers/tasks.ts b/test/helpers/tasks.ts similarity index 94% rename from test/helpers/src/helpers/tasks.ts rename to test/helpers/tasks.ts index 4db3231a67..d2fed9f5da 100644 --- a/test/helpers/src/helpers/tasks.ts +++ b/test/helpers/tasks.ts @@ -1,4 +1,4 @@ -import type { Task } from '@modelcontextprotocol/core'; +import type { Task } from '../../src/types.js'; /** * Polls the provided getTask function until the task reaches the desired status or times out. diff --git a/test/helpers/tsconfig.json b/test/helpers/tsconfig.json deleted file mode 100644 index b5c57f756e..0000000000 --- a/test/helpers/tsconfig.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": "@modelcontextprotocol/tsconfig", - "include": ["./", "../integration/test/helpers/mcp.ts"], - "exclude": ["node_modules", "dist"], - "compilerOptions": { - "paths": { - "*": ["./*"], - "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], - "@modelcontextprotocol/client": ["./node_modules/@modelcontextprotocol/client/src/index.ts"], - "@modelcontextprotocol/server": ["./node_modules/@modelcontextprotocol/server/src/index.ts"], - "@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"] - } - } -} diff --git a/test/helpers/vitest.config.js b/test/helpers/vitest.config.js deleted file mode 100644 index 38f030fdd6..0000000000 --- a/test/helpers/vitest.config.js +++ /dev/null @@ -1,3 +0,0 @@ -import baseConfig from '../../common/vitest-config/vitest.config.js'; - -export default baseConfig; diff --git a/packages/core/test/inMemory.test.ts b/test/inMemory.test.ts similarity index 95% rename from packages/core/test/inMemory.test.ts rename to test/inMemory.test.ts index 72f28240b3..f42420067b 100644 --- a/packages/core/test/inMemory.test.ts +++ b/test/inMemory.test.ts @@ -1,5 +1,6 @@ -import type { AuthInfo, JSONRPCMessage } from '../src/types/types.js'; -import { InMemoryTransport } from '../src/util/inMemory.js'; +import { InMemoryTransport } from '../src/inMemory.js'; +import { JSONRPCMessage } from '../src/types.js'; +import { AuthInfo } from '../src/server/auth/types.js'; describe('InMemoryTransport', () => { let clientTransport: InMemoryTransport; diff --git a/test/integration/test/processCleanup.test.ts b/test/integration-tests/processCleanup.test.ts similarity index 89% rename from test/integration/test/processCleanup.test.ts rename to test/integration-tests/processCleanup.test.ts index aa991501e1..11940697b9 100644 --- a/test/integration/test/processCleanup.test.ts +++ b/test/integration-tests/processCleanup.test.ts @@ -1,11 +1,12 @@ import path from 'node:path'; import { Readable, Writable } from 'node:stream'; +import { Client } from '../../src/client/index.js'; +import { StdioClientTransport } from '../../src/client/stdio.js'; +import { Server } from '../../src/server/index.js'; +import { StdioServerTransport } from '../../src/server/stdio.js'; +import { LoggingMessageNotificationSchema } from '../../src/types.js'; -import { Client, StdioClientTransport } from '@modelcontextprotocol/client'; -import { LoggingMessageNotificationSchema, Server, StdioServerTransport } from '@modelcontextprotocol/server'; - -// Use the local fixtures directory alongside this test file -const FIXTURES_DIR = path.resolve(__dirname, './__fixtures__'); +const FIXTURES_DIR = path.resolve(__dirname, '../../src/__fixtures__'); describe('Process cleanup', () => { vi.setConfig({ testTimeout: 5000 }); // 5 second timeout diff --git a/test/integration/test/stateManagementStreamableHttp.test.ts b/test/integration-tests/stateManagementStreamableHttp.test.ts similarity index 96% rename from test/integration/test/stateManagementStreamableHttp.test.ts rename to test/integration-tests/stateManagementStreamableHttp.test.ts index c33100efad..d79d95c757 100644 --- a/test/integration/test/stateManagementStreamableHttp.test.ts +++ b/test/integration-tests/stateManagementStreamableHttp.test.ts @@ -1,18 +1,18 @@ -import { randomUUID } from 'node:crypto'; import { createServer, type Server } from 'node:http'; - -import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'; +import { randomUUID } from 'node:crypto'; +import { Client } from '../../src/client/index.js'; +import { StreamableHTTPClientTransport } from '../../src/client/streamableHttp.js'; +import { McpServer } from '../../src/server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../src/server/streamableHttp.js'; import { CallToolResultSchema, - LATEST_PROTOCOL_VERSION, - ListPromptsResultSchema, - ListResourcesResultSchema, ListToolsResultSchema, - McpServer, - StreamableHTTPServerTransport -} from '@modelcontextprotocol/server'; -import { listenOnRandomPort } from '@modelcontextprotocol/test-helpers'; -import { type ZodMatrixEntry, zodTestMatrix } from '@modelcontextprotocol/test-helpers'; + ListResourcesResultSchema, + ListPromptsResultSchema, + LATEST_PROTOCOL_VERSION +} from '../../src/types.js'; +import { zodTestMatrix, type ZodMatrixEntry } from '../../src/__fixtures__/zodTestMatrix.js'; +import { listenOnRandomPort } from '../helpers/http.js'; describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const { z } = entry; diff --git a/test/integration/test/taskLifecycle.test.ts b/test/integration-tests/taskLifecycle.test.ts similarity index 97% rename from test/integration/test/taskLifecycle.test.ts rename to test/integration-tests/taskLifecycle.test.ts index 216479e938..629a61b669 100644 --- a/test/integration/test/taskLifecycle.test.ts +++ b/test/integration-tests/taskLifecycle.test.ts @@ -1,24 +1,24 @@ -import { randomUUID } from 'node:crypto'; import { createServer, type Server } from 'node:http'; - -import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'; -import type { TaskRequestOptions } from '@modelcontextprotocol/server'; +import { randomUUID } from 'node:crypto'; +import { Client } from '../../src/client/index.js'; +import { StreamableHTTPClientTransport } from '../../src/client/streamableHttp.js'; +import { McpServer } from '../../src/server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../src/server/streamableHttp.js'; import { CallToolResultSchema, CreateTaskResultSchema, ElicitRequestSchema, ElicitResultSchema, ErrorCode, - InMemoryTaskMessageQueue, - InMemoryTaskStore, McpError, - McpServer, RELATED_TASK_META_KEY, - StreamableHTTPServerTransport, TaskSchema -} from '@modelcontextprotocol/server'; -import { listenOnRandomPort, waitForTaskStatus } from '@modelcontextprotocol/test-helpers'; +} from '../../src/types.js'; import { z } from 'zod'; +import { InMemoryTaskStore, InMemoryTaskMessageQueue } from '../../src/experimental/tasks/stores/in-memory.js'; +import type { TaskRequestOptions } from '../../src/shared/protocol.js'; +import { listenOnRandomPort } from '../helpers/http.js'; +import { waitForTaskStatus } from '../helpers/tasks.js'; describe('Task Lifecycle Integration Tests', () => { let server: Server; @@ -556,9 +556,9 @@ describe('Task Lifecycle Integration Tests', () => { // Verify all messages were delivered in order expect(receivedMessages.length).toBe(3); - expect(receivedMessages[0]!.message).toBe('Request 1 of 3'); - expect(receivedMessages[1]!.message).toBe('Request 2 of 3'); - expect(receivedMessages[2]!.message).toBe('Request 3 of 3'); + expect(receivedMessages[0].message).toBe('Request 1 of 3'); + expect(receivedMessages[1].message).toBe('Request 2 of 3'); + expect(receivedMessages[2].message).toBe('Request 3 of 3'); // Verify final result includes all responses expect(result.content).toEqual([{ type: 'text', text: 'Received responses: Response 1, Response 2, Response 3' }]); @@ -1274,14 +1274,14 @@ describe('Task Lifecycle Integration Tests', () => { // Verify all 3 messages were delivered expect(receivedMessages.length).toBe(3); - expect(receivedMessages[0]!.message).toBe('Streaming message 1 of 3'); - expect(receivedMessages[1]!.message).toBe('Streaming message 2 of 3'); - expect(receivedMessages[2]!.message).toBe('Streaming message 3 of 3'); + expect(receivedMessages[0].message).toBe('Streaming message 1 of 3'); + expect(receivedMessages[1].message).toBe('Streaming message 2 of 3'); + expect(receivedMessages[2].message).toBe('Streaming message 3 of 3'); // Verify messages were delivered over time (not all at once) // The delay between messages should be approximately 300ms - const timeBetweenFirstAndSecond = receivedMessages[1]!.timestamp - receivedMessages[0]!.timestamp; - const timeBetweenSecondAndThird = receivedMessages[2]!.timestamp - receivedMessages[1]!.timestamp; + const timeBetweenFirstAndSecond = receivedMessages[1].timestamp - receivedMessages[0].timestamp; + const timeBetweenSecondAndThird = receivedMessages[2].timestamp - receivedMessages[1].timestamp; // Allow some tolerance for timing (messages should be at least 200ms apart) expect(timeBetweenFirstAndSecond).toBeGreaterThan(200); @@ -1470,8 +1470,8 @@ describe('Task Lifecycle Integration Tests', () => { // Verify all queued messages were delivered before the final result expect(receivedMessages.length).toBe(2); - expect(receivedMessages[0]!.message).toBe('Quick message 1 of 2'); - expect(receivedMessages[1]!.message).toBe('Quick message 2 of 2'); + expect(receivedMessages[0].message).toBe('Quick message 1 of 2'); + expect(receivedMessages[1].message).toBe('Quick message 2 of 2'); // Verify final result is correct expect(result.content).toEqual([{ type: 'text', text: 'Task completed quickly' }]); @@ -1638,15 +1638,15 @@ describe('Task Lifecycle Integration Tests', () => { expect(messages.length).toBeGreaterThanOrEqual(2); // First message should be taskCreated - expect(messages[0]!.type).toBe('taskCreated'); - expect(messages[0]!.task).toBeDefined(); + expect(messages[0].type).toBe('taskCreated'); + expect(messages[0].task).toBeDefined(); // Should have a taskStatus message const statusMessages = messages.filter(m => m.type === 'taskStatus'); expect(statusMessages.length).toBeGreaterThanOrEqual(1); // Last message should be result - const lastMessage = messages[messages.length - 1]!; + const lastMessage = messages[messages.length - 1]; expect(lastMessage.type).toBe('result'); expect(lastMessage.result).toBeDefined(); diff --git a/test/integration/test/taskResumability.test.ts b/test/integration-tests/taskResumability.test.ts similarity index 85% rename from test/integration/test/taskResumability.test.ts rename to test/integration-tests/taskResumability.test.ts index 1e4d8a0fd7..187a3d2ff7 100644 --- a/test/integration/test/taskResumability.test.ts +++ b/test/integration-tests/taskResumability.test.ts @@ -1,50 +1,13 @@ -import { randomUUID } from 'node:crypto'; import { createServer, type Server } from 'node:http'; - -import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'; -import { - CallToolResultSchema, - LoggingMessageNotificationSchema, - McpServer, - StreamableHTTPServerTransport -} from '@modelcontextprotocol/server'; -import type { EventStore, JSONRPCMessage } from '@modelcontextprotocol/server'; -import type { ZodMatrixEntry } from '@modelcontextprotocol/test-helpers'; -import { listenOnRandomPort, zodTestMatrix } from '@modelcontextprotocol/test-helpers'; - -/** - * Simple in-memory EventStore for testing resumability. - */ -class InMemoryEventStore implements EventStore { - private events = new Map(); - - async storeEvent(streamId: string, message: JSONRPCMessage): Promise { - const eventId = `${streamId}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`; - this.events.set(eventId, { streamId, message }); - return eventId; - } - - async replayEventsAfter( - lastEventId: string, - { send }: { send: (eventId: string, message: JSONRPCMessage) => Promise } - ): Promise { - if (!lastEventId || !this.events.has(lastEventId)) return ''; - const streamId = lastEventId.split('_')[0] ?? ''; - if (!streamId) return ''; - - let found = false; - const sorted = [...this.events.entries()].sort((a, b) => a[0].localeCompare(b[0])); - for (const [eventId, { streamId: sid, message }] of sorted) { - if (sid !== streamId) continue; - if (eventId === lastEventId) { - found = true; - continue; - } - if (found) await send(eventId, message); - } - return streamId; - } -} +import { randomUUID } from 'node:crypto'; +import { Client } from '../../src/client/index.js'; +import { StreamableHTTPClientTransport } from '../../src/client/streamableHttp.js'; +import { McpServer } from '../../src/server/mcp.js'; +import { StreamableHTTPServerTransport } from '../../src/server/streamableHttp.js'; +import { CallToolResultSchema, LoggingMessageNotificationSchema } from '../../src/types.js'; +import { InMemoryEventStore } from '../../src/examples/shared/inMemoryEventStore.js'; +import { zodTestMatrix, type ZodMatrixEntry } from '../../src/__fixtures__/zodTestMatrix.js'; +import { listenOnRandomPort } from '../helpers/http.js'; describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const { z } = entry; diff --git a/test/integration/eslint.config.mjs b/test/integration/eslint.config.mjs deleted file mode 100644 index 951c9f3a91..0000000000 --- a/test/integration/eslint.config.mjs +++ /dev/null @@ -1,5 +0,0 @@ -// @ts-check - -import baseConfig from '@modelcontextprotocol/eslint-config'; - -export default baseConfig; diff --git a/test/integration/package.json b/test/integration/package.json deleted file mode 100644 index e709e431af..0000000000 --- a/test/integration/package.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "@modelcontextprotocol/test-integration", - "private": true, - "version": "2.0.0-alpha.0", - "description": "Model Context Protocol implementation for TypeScript", - "license": "MIT", - "author": "Anthropic, PBC (https://anthropic.com)", - "homepage": "https://modelcontextprotocol.io", - "bugs": "https://github.com/modelcontextprotocol/typescript-sdk/issues", - "type": "module", - "repository": { - "type": "git", - "url": "git+https://github.com/modelcontextprotocol/typescript-sdk.git" - }, - "engines": { - "node": ">=20", - "pnpm": ">=10.24.0" - }, - "packageManager": "pnpm@10.24.0", - "keywords": [ - "modelcontextprotocol", - "mcp" - ], - "scripts": { - "lint": "eslint test/ && prettier --ignore-path ../../.prettierignore --check .", - "lint:fix": "eslint test/ --fix && prettier --ignore-path ../../.prettierignore --write .", - "check": "npm run typecheck && npm run lint", - "test": "vitest run", - "test:watch": "vitest", - "start": "npm run server", - "server": "tsx watch --clear-screen=false scripts/cli.ts server", - "client": "tsx scripts/cli.ts client" - }, - "devDependencies": { - "@modelcontextprotocol/core": "workspace:^", - "@modelcontextprotocol/client": "workspace:^", - "@modelcontextprotocol/server": "workspace:^", - "zod": "catalog:runtimeShared", - "vitest": "catalog:devTools", - "supertest": "catalog:devTools", - "@modelcontextprotocol/tsconfig": "workspace:^", - "@modelcontextprotocol/vitest-config": "workspace:^", - "@modelcontextprotocol/eslint-config": "workspace:^", - "@modelcontextprotocol/test-helpers": "workspace:^" - } -} diff --git a/test/integration/test/issues/test_1277_zod_v4_description.test.ts b/test/integration/test/issues/test_1277_zod_v4_description.test.ts deleted file mode 100644 index fe58cfcd50..0000000000 --- a/test/integration/test/issues/test_1277_zod_v4_description.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -/** - * Regression test for https://github.com/modelcontextprotocol/typescript-sdk/issues/1277 - * - * Zod v4 stores `.describe()` descriptions directly on the schema object, - * not in `._zod.def.description`. This test verifies that descriptions are - * correctly extracted for prompt arguments. - */ - -import { Client } from '@modelcontextprotocol/client'; -import { InMemoryTransport, ListPromptsResultSchema } from '@modelcontextprotocol/core'; -import { McpServer } from '@modelcontextprotocol/server'; -import { type ZodMatrixEntry, zodTestMatrix } from '@modelcontextprotocol/test-helpers'; - -describe.each(zodTestMatrix)('Issue #1277: $zodVersionLabel', (entry: ZodMatrixEntry) => { - const { z } = entry; - - test('should preserve argument descriptions from .describe()', async () => { - const mcpServer = new McpServer({ - name: 'test server', - version: '1.0' - }); - const client = new Client({ - name: 'test client', - version: '1.0' - }); - - mcpServer.prompt( - 'test', - { - name: z.string().describe('The user name'), - value: z.string().describe('The value to set') - }, - async ({ name, value }) => ({ - messages: [ - { - role: 'assistant', - content: { - type: 'text', - text: `${name}: ${value}` - } - } - ] - }) - ); - - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - - await Promise.all([client.connect(clientTransport), mcpServer.server.connect(serverTransport)]); - - const result = await client.request( - { - method: 'prompts/list' - }, - ListPromptsResultSchema - ); - - expect(result.prompts).toHaveLength(1); - expect(result.prompts[0]!.name).toBe('test'); - expect(result.prompts[0]!.arguments).toEqual([ - { name: 'name', required: true, description: 'The user name' }, - { name: 'value', required: true, description: 'The value to set' } - ]); - }); -}); diff --git a/test/integration/tsconfig.json b/test/integration/tsconfig.json deleted file mode 100644 index f69a602fd1..0000000000 --- a/test/integration/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "extends": "@modelcontextprotocol/tsconfig", - "include": ["./"], - "exclude": ["node_modules", "dist"], - "compilerOptions": { - "paths": { - "*": ["./*"], - "@modelcontextprotocol/core": ["./node_modules/@modelcontextprotocol/core/src/index.ts"], - "@modelcontextprotocol/client": ["./node_modules/@modelcontextprotocol/client/src/index.ts"], - "@modelcontextprotocol/server": ["./node_modules/@modelcontextprotocol/server/src/index.ts"], - "@modelcontextprotocol/vitest-config": ["./node_modules/@modelcontextprotocol/vitest-config/tsconfig.json"], - "@modelcontextprotocol/test-helpers": ["./node_modules/@modelcontextprotocol/test-helpers/src/index.ts"] - } - } -} diff --git a/test/integration/vitest.config.js b/test/integration/vitest.config.js deleted file mode 100644 index 38f030fdd6..0000000000 --- a/test/integration/vitest.config.js +++ /dev/null @@ -1,3 +0,0 @@ -import baseConfig from '../../common/vitest-config/vitest.config.js'; - -export default baseConfig; diff --git a/packages/server/test/server/auth/handlers/authorize.test.ts b/test/server/auth/handlers/authorize.test.ts similarity index 90% rename from packages/server/test/server/auth/handlers/authorize.test.ts rename to test/server/auth/handlers/authorize.test.ts index b84de3bc3f..0f831ae7de 100644 --- a/packages/server/test/server/auth/handlers/authorize.test.ts +++ b/test/server/auth/handlers/authorize.test.ts @@ -1,13 +1,11 @@ -import type { AuthInfo, OAuthClientInformationFull, OAuthTokens } from '@modelcontextprotocol/core'; -import { InvalidTokenError } from '@modelcontextprotocol/core'; -import type { Response } from 'express'; -import express from 'express'; +import { authorizationHandler, AuthorizationHandlerOptions } from '../../../../src/server/auth/handlers/authorize.js'; +import { OAuthServerProvider, AuthorizationParams } from '../../../../src/server/auth/provider.js'; +import { OAuthRegisteredClientsStore } from '../../../../src/server/auth/clients.js'; +import { OAuthClientInformationFull, OAuthTokens } from '../../../../src/shared/auth.js'; +import express, { Response } from 'express'; import supertest from 'supertest'; - -import type { OAuthRegisteredClientsStore } from '../../../../src/server/auth/clients.js'; -import type { AuthorizationHandlerOptions } from '../../../../src/server/auth/handlers/authorize.js'; -import { authorizationHandler } from '../../../../src/server/auth/handlers/authorize.js'; -import type { AuthorizationParams, OAuthServerProvider } from '../../../../src/server/auth/provider.js'; +import { AuthInfo } from '../../../../src/server/auth/types.js'; +import { InvalidTokenError } from '../../../../src/server/auth/errors.js'; describe('Authorization Handler', () => { // Mock client data @@ -134,7 +132,7 @@ describe('Authorization Handler', () => { }); expect(response.status).toBe(302); - const location = new URL(response.header.location!); + const location = new URL(response.header.location); expect(location.origin + location.pathname).toBe('https://example.com/callback'); }); @@ -171,7 +169,7 @@ describe('Authorization Handler', () => { }); expect(response.status).toBe(302); - const location = new URL(response.header.location!); + const location = new URL(response.header.location); expect(location.origin + location.pathname).toBe('https://example.com/callback'); }); }); @@ -187,7 +185,7 @@ describe('Authorization Handler', () => { }); expect(response.status).toBe(302); - const location = new URL(response.header.location!); + const location = new URL(response.header.location); expect(location.searchParams.get('error')).toBe('invalid_request'); }); @@ -201,7 +199,7 @@ describe('Authorization Handler', () => { }); expect(response.status).toBe(302); - const location = new URL(response.header.location!); + const location = new URL(response.header.location); expect(location.searchParams.get('error')).toBe('invalid_request'); }); @@ -215,7 +213,7 @@ describe('Authorization Handler', () => { }); expect(response.status).toBe(302); - const location = new URL(response.header.location!); + const location = new URL(response.header.location); expect(location.searchParams.get('error')).toBe('invalid_request'); }); }); @@ -259,7 +257,7 @@ describe('Authorization Handler', () => { }); expect(response.status).toBe(302); - const location = new URL(response.header.location!); + const location = new URL(response.header.location); expect(location.origin + location.pathname).toBe('https://example.com/callback'); expect(location.searchParams.get('code')).toBe('mock_auth_code'); expect(location.searchParams.get('state')).toBe('xyz789'); @@ -276,7 +274,7 @@ describe('Authorization Handler', () => { }); expect(response.status).toBe(302); - const location = new URL(response.header.location!); + const location = new URL(response.header.location); expect(location.searchParams.get('state')).toBe('state-value-123'); }); @@ -289,7 +287,7 @@ describe('Authorization Handler', () => { }); expect(response.status).toBe(302); - const location = new URL(response.header.location!); + const location = new URL(response.header.location); expect(location.searchParams.has('code')).toBe(true); }); }); diff --git a/packages/server/test/server/auth/handlers/metadata.test.ts b/test/server/auth/handlers/metadata.test.ts similarity index 97% rename from packages/server/test/server/auth/handlers/metadata.test.ts rename to test/server/auth/handlers/metadata.test.ts index 0dc51e51d7..2eb7693f2f 100644 --- a/packages/server/test/server/auth/handlers/metadata.test.ts +++ b/test/server/auth/handlers/metadata.test.ts @@ -1,9 +1,8 @@ -import type { OAuthMetadata } from '@modelcontextprotocol/core'; +import { metadataHandler } from '../../../../src/server/auth/handlers/metadata.js'; +import { OAuthMetadata } from '../../../../src/shared/auth.js'; import express from 'express'; import supertest from 'supertest'; -import { metadataHandler } from '../../../../src/server/auth/handlers/metadata.js'; - describe('Metadata Handler', () => { const exampleMetadata: OAuthMetadata = { issuer: 'https://auth.example.com', diff --git a/packages/server/test/server/auth/handlers/register.test.ts b/test/server/auth/handlers/register.test.ts similarity index 96% rename from packages/server/test/server/auth/handlers/register.test.ts rename to test/server/auth/handlers/register.test.ts index b10e048eda..03fde46d23 100644 --- a/packages/server/test/server/auth/handlers/register.test.ts +++ b/test/server/auth/handlers/register.test.ts @@ -1,11 +1,9 @@ -import type { OAuthClientInformationFull, OAuthClientMetadata } from '@modelcontextprotocol/core'; +import { clientRegistrationHandler, ClientRegistrationHandlerOptions } from '../../../../src/server/auth/handlers/register.js'; +import { OAuthRegisteredClientsStore } from '../../../../src/server/auth/clients.js'; +import { OAuthClientInformationFull, OAuthClientMetadata } from '../../../../src/shared/auth.js'; import express from 'express'; import supertest from 'supertest'; -import type { MockInstance } from 'vitest'; - -import type { OAuthRegisteredClientsStore } from '../../../../src/server/auth/clients.js'; -import type { ClientRegistrationHandlerOptions } from '../../../../src/server/auth/handlers/register.js'; -import { clientRegistrationHandler } from '../../../../src/server/auth/handlers/register.js'; +import { MockInstance } from 'vitest'; describe('Client Registration Handler', () => { // Mock client store with registration support diff --git a/packages/server/test/server/auth/handlers/revoke.test.ts b/test/server/auth/handlers/revoke.test.ts similarity index 92% rename from packages/server/test/server/auth/handlers/revoke.test.ts rename to test/server/auth/handlers/revoke.test.ts index 61ff51b246..69cac83d94 100644 --- a/packages/server/test/server/auth/handlers/revoke.test.ts +++ b/test/server/auth/handlers/revoke.test.ts @@ -1,14 +1,12 @@ -import type { AuthInfo, OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '@modelcontextprotocol/core'; -import { InvalidTokenError } from '@modelcontextprotocol/core'; -import type { Response } from 'express'; -import express from 'express'; +import { revocationHandler, RevocationHandlerOptions } from '../../../../src/server/auth/handlers/revoke.js'; +import { OAuthServerProvider, AuthorizationParams } from '../../../../src/server/auth/provider.js'; +import { OAuthRegisteredClientsStore } from '../../../../src/server/auth/clients.js'; +import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../../../src/shared/auth.js'; +import express, { Response } from 'express'; import supertest from 'supertest'; -import type { MockInstance } from 'vitest'; - -import type { OAuthRegisteredClientsStore } from '../../../../src/server/auth/clients.js'; -import type { RevocationHandlerOptions } from '../../../../src/server/auth/handlers/revoke.js'; -import { revocationHandler } from '../../../../src/server/auth/handlers/revoke.js'; -import type { AuthorizationParams, OAuthServerProvider } from '../../../../src/server/auth/provider.js'; +import { AuthInfo } from '../../../../src/server/auth/types.js'; +import { InvalidTokenError } from '../../../../src/server/auth/errors.js'; +import { MockInstance } from 'vitest'; describe('Revocation Handler', () => { // Mock client data diff --git a/packages/server/test/server/auth/handlers/token.test.ts b/test/server/auth/handlers/token.test.ts similarity index 96% rename from packages/server/test/server/auth/handlers/token.test.ts rename to test/server/auth/handlers/token.test.ts index 02eab891f8..658142b4b5 100644 --- a/packages/server/test/server/auth/handlers/token.test.ts +++ b/test/server/auth/handlers/token.test.ts @@ -1,16 +1,14 @@ -import type { AuthInfo, OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '@modelcontextprotocol/core'; -import { InvalidGrantError, InvalidTokenError } from '@modelcontextprotocol/core'; -import type { Response } from 'express'; -import express from 'express'; -import * as pkceChallenge from 'pkce-challenge'; +import { tokenHandler, TokenHandlerOptions } from '../../../../src/server/auth/handlers/token.js'; +import { OAuthServerProvider, AuthorizationParams } from '../../../../src/server/auth/provider.js'; +import { OAuthRegisteredClientsStore } from '../../../../src/server/auth/clients.js'; +import { OAuthClientInformationFull, OAuthTokenRevocationRequest, OAuthTokens } from '../../../../src/shared/auth.js'; +import express, { Response } from 'express'; import supertest from 'supertest'; -import { type Mock } from 'vitest'; - -import type { OAuthRegisteredClientsStore } from '../../../../src/server/auth/clients.js'; -import type { TokenHandlerOptions } from '../../../../src/server/auth/handlers/token.js'; -import { tokenHandler } from '../../../../src/server/auth/handlers/token.js'; -import type { AuthorizationParams, OAuthServerProvider } from '../../../../src/server/auth/provider.js'; +import * as pkceChallenge from 'pkce-challenge'; +import { InvalidGrantError, InvalidTokenError } from '../../../../src/server/auth/errors.js'; +import { AuthInfo } from '../../../../src/server/auth/types.js'; import { ProxyOAuthServerProvider } from '../../../../src/server/auth/providers/proxyProvider.js'; +import { type Mock } from 'vitest'; // Mock pkce-challenge vi.mock('pkce-challenge', () => ({ diff --git a/packages/server/test/server/auth/middleware/allowedMethods.test.ts b/test/server/auth/middleware/allowedMethods.test.ts similarity index 96% rename from packages/server/test/server/auth/middleware/allowedMethods.test.ts rename to test/server/auth/middleware/allowedMethods.test.ts index 40e9c3b1fa..7c939de6aa 100644 --- a/packages/server/test/server/auth/middleware/allowedMethods.test.ts +++ b/test/server/auth/middleware/allowedMethods.test.ts @@ -1,8 +1,6 @@ -import type { Request, Response } from 'express'; -import express from 'express'; -import request from 'supertest'; - import { allowedMethods } from '../../../../src/server/auth/middleware/allowedMethods.js'; +import express, { Request, Response } from 'express'; +import request from 'supertest'; describe('allowedMethods', () => { let app: express.Express; diff --git a/packages/server/test/server/auth/middleware/bearerAuth.test.ts b/test/server/auth/middleware/bearerAuth.test.ts similarity index 98% rename from packages/server/test/server/auth/middleware/bearerAuth.test.ts rename to test/server/auth/middleware/bearerAuth.test.ts index 7b464bbff6..68162be9b4 100644 --- a/packages/server/test/server/auth/middleware/bearerAuth.test.ts +++ b/test/server/auth/middleware/bearerAuth.test.ts @@ -1,11 +1,10 @@ -import type { AuthInfo } from '@modelcontextprotocol/core'; -import { CustomOAuthError, InsufficientScopeError, InvalidTokenError, ServerError } from '@modelcontextprotocol/core'; -import { createExpressResponseMock } from '@modelcontextprotocol/test-helpers'; -import type { Request, Response } from 'express'; -import type { Mock } from 'vitest'; - +import { Request, Response } from 'express'; +import { Mock } from 'vitest'; import { requireBearerAuth } from '../../../../src/server/auth/middleware/bearerAuth.js'; -import type { OAuthTokenVerifier } from '../../../../src/server/auth/provider.js'; +import { AuthInfo } from '../../../../src/server/auth/types.js'; +import { InsufficientScopeError, InvalidTokenError, CustomOAuthError, ServerError } from '../../../../src/server/auth/errors.js'; +import { OAuthTokenVerifier } from '../../../../src/server/auth/provider.js'; +import { createExpressResponseMock } from '../../../helpers/http.js'; // Mock verifier const mockVerifyAccessToken = vi.fn(); diff --git a/packages/server/test/server/auth/middleware/clientAuth.test.ts b/test/server/auth/middleware/clientAuth.test.ts similarity index 92% rename from packages/server/test/server/auth/middleware/clientAuth.test.ts rename to test/server/auth/middleware/clientAuth.test.ts index 55a00f0c25..50cc1d9076 100644 --- a/packages/server/test/server/auth/middleware/clientAuth.test.ts +++ b/test/server/auth/middleware/clientAuth.test.ts @@ -1,11 +1,9 @@ -import type { OAuthClientInformationFull } from '@modelcontextprotocol/core'; +import { authenticateClient, ClientAuthenticationMiddlewareOptions } from '../../../../src/server/auth/middleware/clientAuth.js'; +import { OAuthRegisteredClientsStore } from '../../../../src/server/auth/clients.js'; +import { OAuthClientInformationFull } from '../../../../src/shared/auth.js'; import express from 'express'; import supertest from 'supertest'; -import type { OAuthRegisteredClientsStore } from '../../../../src/server/auth/clients.js'; -import type { ClientAuthenticationMiddlewareOptions } from '../../../../src/server/auth/middleware/clientAuth.js'; -import { authenticateClient } from '../../../../src/server/auth/middleware/clientAuth.js'; - describe('clientAuth middleware', () => { // Mock client store const mockClientStore: OAuthRegisteredClientsStore = { diff --git a/packages/server/test/server/auth/providers/proxyProvider.test.ts b/test/server/auth/providers/proxyProvider.test.ts similarity index 95% rename from packages/server/test/server/auth/providers/proxyProvider.test.ts rename to test/server/auth/providers/proxyProvider.test.ts index 375179e5b5..40fb55d572 100644 --- a/packages/server/test/server/auth/providers/proxyProvider.test.ts +++ b/test/server/auth/providers/proxyProvider.test.ts @@ -1,11 +1,12 @@ -import type { AuthInfo, OAuthClientInformationFull, OAuthTokens } from '@modelcontextprotocol/core'; -import { InsufficientScopeError, InvalidTokenError, ServerError } from '@modelcontextprotocol/core'; -import type { Response } from 'express'; +import { Response } from 'express'; +import { ProxyOAuthServerProvider, ProxyOptions } from '../../../../src/server/auth/providers/proxyProvider.js'; +import { AuthInfo } from '../../../../src/server/auth/types.js'; +import { OAuthClientInformationFull, OAuthTokens } from '../../../../src/shared/auth.js'; +import { ServerError } from '../../../../src/server/auth/errors.js'; +import { InvalidTokenError } from '../../../../src/server/auth/errors.js'; +import { InsufficientScopeError } from '../../../../src/server/auth/errors.js'; import { type Mock } from 'vitest'; -import type { ProxyOptions } from '../../../../src/server/auth/providers/proxyProvider.js'; -import { ProxyOAuthServerProvider } from '../../../../src/server/auth/providers/proxyProvider.js'; - describe('Proxy OAuth Server Provider', () => { // Mock client data const validClient: OAuthClientInformationFull = { @@ -183,7 +184,7 @@ describe('Proxy OAuth Server Provider', () => { const tokens = await provider.exchangeAuthorizationCode(validClient, 'test-code', 'test-verifier'); const fetchCall = (global.fetch as Mock).mock.calls[0]; - const body = fetchCall![1].body as string; + const body = fetchCall[1].body as string; expect(body).not.toContain('resource='); expect(tokens).toEqual(mockTokenResponse); }); diff --git a/packages/server/test/server/auth/router.test.ts b/test/server/auth/router.test.ts similarity index 96% rename from packages/server/test/server/auth/router.test.ts rename to test/server/auth/router.test.ts index 250fca4c46..521c650c4d 100644 --- a/packages/server/test/server/auth/router.test.ts +++ b/test/server/auth/router.test.ts @@ -1,14 +1,11 @@ -import type { OAuthClientInformationFull, OAuthMetadata, OAuthTokenRevocationRequest, OAuthTokens } from '@modelcontextprotocol/core'; -import type { AuthInfo } from '@modelcontextprotocol/core'; -import { InvalidTokenError } from '@modelcontextprotocol/core'; -import type { Response } from 'express'; -import express from 'express'; +import { mcpAuthRouter, AuthRouterOptions, mcpAuthMetadataRouter, AuthMetadataOptions } from '../../../src/server/auth/router.js'; +import { OAuthServerProvider, AuthorizationParams } from '../../../src/server/auth/provider.js'; +import { OAuthRegisteredClientsStore } from '../../../src/server/auth/clients.js'; +import { OAuthClientInformationFull, OAuthMetadata, OAuthTokenRevocationRequest, OAuthTokens } from '../../../src/shared/auth.js'; +import express, { Response } from 'express'; import supertest from 'supertest'; - -import type { OAuthRegisteredClientsStore } from '../../../src/server/auth/clients.js'; -import type { AuthorizationParams, OAuthServerProvider } from '../../../src/server/auth/provider.js'; -import type { AuthMetadataOptions, AuthRouterOptions } from '../../../src/server/auth/router.js'; -import { mcpAuthMetadataRouter, mcpAuthRouter } from '../../../src/server/auth/router.js'; +import { AuthInfo } from '../../../src/server/auth/types.js'; +import { InvalidTokenError } from '../../../src/server/auth/errors.js'; describe('MCP Auth Router', () => { // Setup mock provider with full capabilities @@ -298,7 +295,7 @@ describe('MCP Auth Router', () => { }); expect(response.status).toBe(302); - const location = new URL(response.header.location!); + const location = new URL(response.header.location); expect(location.searchParams.has('code')).toBe(true); }); diff --git a/packages/server/test/server/completable.test.ts b/test/server/completable.test.ts similarity index 93% rename from packages/server/test/server/completable.test.ts rename to test/server/completable.test.ts index ff94b641bd..3f917a492c 100644 --- a/packages/server/test/server/completable.test.ts +++ b/test/server/completable.test.ts @@ -1,6 +1,5 @@ import { completable, getCompleter } from '../../src/server/completable.js'; -import type { ZodMatrixEntry } from './__fixtures__/zodTestMatrix.js'; -import { zodTestMatrix } from './__fixtures__/zodTestMatrix.js'; +import { zodTestMatrix, type ZodMatrixEntry } from '../../src/__fixtures__/zodTestMatrix.js'; describe.each(zodTestMatrix)('completable with $zodVersionLabel', (entry: ZodMatrixEntry) => { const { z } = entry; diff --git a/test/integration/test/server/elicitation.test.ts b/test/server/elicitation.test.ts similarity index 98% rename from test/integration/test/server/elicitation.test.ts rename to test/server/elicitation.test.ts index 6cf6d53953..c6f297b462 100644 --- a/test/integration/test/server/elicitation.test.ts +++ b/test/server/elicitation.test.ts @@ -7,10 +7,12 @@ * Per the MCP spec, elicitation only supports object schemas, not primitives. */ -import { Client } from '@modelcontextprotocol/client'; -import type { ElicitRequestFormParams } from '@modelcontextprotocol/core'; -import { AjvJsonSchemaValidator, CfWorkerJsonSchemaValidator, ElicitRequestSchema, InMemoryTransport } from '@modelcontextprotocol/core'; -import { Server } from '@modelcontextprotocol/server'; +import { Client } from '../../src/client/index.js'; +import { InMemoryTransport } from '../../src/inMemory.js'; +import { ElicitRequestFormParams, ElicitRequestSchema } from '../../src/types.js'; +import { AjvJsonSchemaValidator } from '../../src/validation/ajv-provider.js'; +import { CfWorkerJsonSchemaValidator } from '../../src/validation/cfworker-provider.js'; +import { Server } from '../../src/server/index.js'; const ajvProvider = new AjvJsonSchemaValidator(); const cfWorkerProvider = new CfWorkerJsonSchemaValidator(); diff --git a/test/integration/test/server.test.ts b/test/server/index.test.ts similarity index 98% rename from test/integration/test/server.test.ts rename to test/server/index.test.ts index fcac6cc451..a32aa03327 100644 --- a/test/integration/test/server.test.ts +++ b/test/server/index.test.ts @@ -1,39 +1,37 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ -import { Client } from '@modelcontextprotocol/client'; -import type { - AnyObjectSchema, - JsonSchemaType, - JsonSchemaValidator, - jsonSchemaValidator, - LoggingMessageNotification, - Transport -} from '@modelcontextprotocol/core'; +import supertest from 'supertest'; +import { Client } from '../../src/client/index.js'; +import { InMemoryTransport } from '../../src/inMemory.js'; +import type { Transport } from '../../src/shared/transport.js'; import { - CallToolRequestSchema, - CallToolResultSchema, CreateMessageRequestSchema, CreateMessageResultSchema, - CreateTaskResultSchema, - ElicitationCompleteNotificationSchema, ElicitRequestSchema, ElicitResultSchema, + ElicitationCompleteNotificationSchema, ErrorCode, - InMemoryTransport, LATEST_PROTOCOL_VERSION, ListPromptsRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, + type LoggingMessageNotification, McpError, NotificationSchema, RequestSchema, ResultSchema, SetLevelRequestSchema, - SUPPORTED_PROTOCOL_VERSIONS -} from '@modelcontextprotocol/core'; -import { createMcpExpressApp, InMemoryTaskMessageQueue, InMemoryTaskStore, McpServer, Server } from '@modelcontextprotocol/server'; -import supertest from 'supertest'; + SUPPORTED_PROTOCOL_VERSIONS, + CreateTaskResultSchema +} from '../../src/types.js'; +import { Server } from '../../src/server/index.js'; +import { McpServer } from '../../src/server/mcp.js'; +import { InMemoryTaskStore, InMemoryTaskMessageQueue } from '../../src/experimental/tasks/stores/in-memory.js'; +import { CallToolRequestSchema, CallToolResultSchema } from '../../src/types.js'; +import type { JsonSchemaType, JsonSchemaValidator, jsonSchemaValidator } from '../../src/validation/types.js'; +import type { AnyObjectSchema } from '../../src/server/zod-compat.js'; import * as z3 from 'zod/v3'; import * as z4 from 'zod/v4'; +import { createMcpExpressApp } from '../../src/server/express.js'; describe('Zod v3', () => { /* @@ -1984,8 +1982,11 @@ describe('createMessage backwards compatibility', () => { // Verify result is returned correctly expect(result.model).toBe('test-model'); - expect(result.content).toMatchObject({ type: 'text', text: 'I will use the weather tool' }); - expect(result.content).not.toBeInstanceOf(Array); + expect(result.content.type).toBe('text'); + // With tools param, result.content can be array (CreateMessageResultWithTools type) + // This would fail type-check if we used CreateMessageResult which doesn't allow arrays + const contentArray = Array.isArray(result.content) ? result.content : [result.content]; + expect(contentArray.length).toBe(1); }); }); @@ -3023,11 +3024,11 @@ describe('Task-based execution', () => { // Verify all tasks completed successfully for (let i = 0; i < taskIds.length; i++) { - const task = await client.experimental.tasks.getTask(taskIds[i]!); + const task = await client.experimental.tasks.getTask(taskIds[i]); expect(task.status).toBe('completed'); - expect(task.taskId).toBe(taskIds[i]!); + expect(task.taskId).toBe(taskIds[i]); - const result = await client.experimental.tasks.getTaskResult(taskIds[i]!, CallToolResultSchema); + const result = await client.experimental.tasks.getTaskResult(taskIds[i], CallToolResultSchema); expect(result.content).toEqual([{ type: 'text', text: `Completed task ${i + 1}` }]); } diff --git a/test/integration/test/server/mcp.test.ts b/test/server/mcp.test.ts similarity index 97% rename from test/integration/test/server/mcp.test.ts rename to test/server/mcp.test.ts index c5d831feb7..3464bb2527 100644 --- a/test/integration/test/server/mcp.test.ts +++ b/test/server/mcp.test.ts @@ -1,11 +1,12 @@ -import { Client } from '@modelcontextprotocol/client'; -import { getDisplayName, InMemoryTaskStore, InMemoryTransport, UriTemplate } from '@modelcontextprotocol/core'; +import { Client } from '../../src/client/index.js'; +import { InMemoryTransport } from '../../src/inMemory.js'; +import { getDisplayName } from '../../src/shared/metadataUtils.js'; +import { UriTemplate } from '../../src/shared/uriTemplate.js'; import { - type CallToolResult, CallToolResultSchema, + type CallToolResult, CompleteResultSchema, ElicitRequestSchema, - ErrorCode, GetPromptResultSchema, ListPromptsResultSchema, ListResourcesResultSchema, @@ -15,12 +16,13 @@ import { type Notification, ReadResourceResultSchema, type TextContent, - UrlElicitationRequiredError -} from '@modelcontextprotocol/core'; - -import { completable } from '../../../../packages/server/src/server/completable.js'; -import { McpServer, ResourceTemplate } from '../../../../packages/server/src/server/mcp.js'; -import { type ZodMatrixEntry, zodTestMatrix } from '../../../../packages/server/test/server/__fixtures__/zodTestMatrix.js'; + UrlElicitationRequiredError, + ErrorCode +} from '../../src/types.js'; +import { completable } from '../../src/server/completable.js'; +import { McpServer, ResourceTemplate } from '../../src/server/mcp.js'; +import { InMemoryTaskStore } from '../../src/experimental/tasks/stores/in-memory.js'; +import { zodTestMatrix, type ZodMatrixEntry } from '../../src/__fixtures__/zodTestMatrix.js'; function createLatch() { let latch = false; @@ -290,8 +292,8 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ); expect(result.tools).toHaveLength(1); - expect(result.tools[0]!.name).toBe('test'); - expect(result.tools[0]!.inputSchema).toEqual({ + expect(result.tools[0].name).toBe('test'); + expect(result.tools[0].inputSchema).toEqual({ type: 'object', properties: {} }); @@ -445,7 +447,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ListToolsResultSchema ); - expect(listResult.tools[0]!.inputSchema).toMatchObject({ + expect(listResult.tools[0].inputSchema).toMatchObject({ properties: { name: { type: 'string' }, value: { type: 'number' } @@ -538,7 +540,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ListToolsResultSchema ); - expect(listResult.tools[0]!.outputSchema).toMatchObject({ + expect(listResult.tools[0].outputSchema).toMatchObject({ type: 'object', properties: { result: { type: 'number' }, @@ -682,16 +684,16 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ); expect(result.tools).toHaveLength(2); - expect(result.tools[0]!.name).toBe('test'); - expect(result.tools[0]!.inputSchema).toMatchObject({ + expect(result.tools[0].name).toBe('test'); + expect(result.tools[0].inputSchema).toMatchObject({ type: 'object', properties: { name: { type: 'string' }, value: { type: 'number' } } }); - expect(result.tools[1]!.name).toBe('test (new api)'); - expect(result.tools[1]!.inputSchema).toEqual(result.tools[0]!.inputSchema); + expect(result.tools[1].name).toBe('test (new api)'); + expect(result.tools[1].inputSchema).toEqual(result.tools[0].inputSchema); }); /*** @@ -745,10 +747,10 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ); expect(result.tools).toHaveLength(2); - expect(result.tools[0]!.name).toBe('test'); - expect(result.tools[0]!.description).toBe('Test description'); - expect(result.tools[1]!.name).toBe('test (new api)'); - expect(result.tools[1]!.description).toBe('Test description'); + expect(result.tools[0].name).toBe('test'); + expect(result.tools[0].description).toBe('Test description'); + expect(result.tools[1].name).toBe('test (new api)'); + expect(result.tools[1].description).toBe('Test description'); }); /*** @@ -800,13 +802,13 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ); expect(result.tools).toHaveLength(2); - expect(result.tools[0]!.name).toBe('test'); - expect(result.tools[0]!.annotations).toEqual({ + expect(result.tools[0].name).toBe('test'); + expect(result.tools[0].annotations).toEqual({ title: 'Test Tool', readOnlyHint: true }); - expect(result.tools[1]!.name).toBe('test (new api)'); - expect(result.tools[1]!.annotations).toEqual({ + expect(result.tools[1].name).toBe('test (new api)'); + expect(result.tools[1].annotations).toEqual({ title: 'Test Tool', readOnlyHint: true }); @@ -891,18 +893,18 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const result = await client.request({ method: 'tools/list' }, ListToolsResultSchema); expect(result.tools).toHaveLength(2); - expect(result.tools[0]!.name).toBe('test'); - expect(result.tools[0]!.inputSchema).toMatchObject({ + expect(result.tools[0].name).toBe('test'); + expect(result.tools[0].inputSchema).toMatchObject({ type: 'object', properties: { name: { type: 'string' } } }); - expect(result.tools[0]!.annotations).toEqual({ + expect(result.tools[0].annotations).toEqual({ title: 'Test Tool', readOnlyHint: true }); - expect(result.tools[1]!.name).toBe('test (new api)'); - expect(result.tools[1]!.inputSchema).toEqual(result.tools[0]!.inputSchema); - expect(result.tools[1]!.annotations).toEqual(result.tools[0]!.annotations); + expect(result.tools[1].name).toBe('test (new api)'); + expect(result.tools[1].inputSchema).toEqual(result.tools[0].inputSchema); + expect(result.tools[1].annotations).toEqual(result.tools[0].annotations); }); /*** @@ -951,21 +953,21 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const result = await client.request({ method: 'tools/list' }, ListToolsResultSchema); expect(result.tools).toHaveLength(2); - expect(result.tools[0]!.name).toBe('test'); - expect(result.tools[0]!.description).toBe('A tool with everything'); - expect(result.tools[0]!.inputSchema).toMatchObject({ + expect(result.tools[0].name).toBe('test'); + expect(result.tools[0].description).toBe('A tool with everything'); + expect(result.tools[0].inputSchema).toMatchObject({ type: 'object', properties: { name: { type: 'string' } } }); - expect(result.tools[0]!.annotations).toEqual({ + expect(result.tools[0].annotations).toEqual({ title: 'Complete Test Tool', readOnlyHint: true, openWorldHint: false }); - expect(result.tools[1]!.name).toBe('test (new api)'); - expect(result.tools[1]!.description).toBe('A tool with everything'); - expect(result.tools[1]!.inputSchema).toEqual(result.tools[0]!.inputSchema); - expect(result.tools[1]!.annotations).toEqual(result.tools[0]!.annotations); + expect(result.tools[1].name).toBe('test (new api)'); + expect(result.tools[1].description).toBe('A tool with everything'); + expect(result.tools[1].inputSchema).toEqual(result.tools[0].inputSchema); + expect(result.tools[1].annotations).toEqual(result.tools[0].annotations); }); /*** @@ -1018,21 +1020,21 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const result = await client.request({ method: 'tools/list' }, ListToolsResultSchema); expect(result.tools).toHaveLength(2); - expect(result.tools[0]!.name).toBe('test'); - expect(result.tools[0]!.description).toBe('A tool with everything but empty params'); - expect(result.tools[0]!.inputSchema).toMatchObject({ + expect(result.tools[0].name).toBe('test'); + expect(result.tools[0].description).toBe('A tool with everything but empty params'); + expect(result.tools[0].inputSchema).toMatchObject({ type: 'object', properties: {} }); - expect(result.tools[0]!.annotations).toEqual({ + expect(result.tools[0].annotations).toEqual({ title: 'Complete Test Tool with empty params', readOnlyHint: true, openWorldHint: false }); - expect(result.tools[1]!.name).toBe('test (new api)'); - expect(result.tools[1]!.description).toBe('A tool with everything but empty params'); - expect(result.tools[1]!.inputSchema).toEqual(result.tools[0]!.inputSchema); - expect(result.tools[1]!.annotations).toEqual(result.tools[0]!.annotations); + expect(result.tools[1].name).toBe('test (new api)'); + expect(result.tools[1].description).toBe('A tool with everything but empty params'); + expect(result.tools[1].inputSchema).toEqual(result.tools[0].inputSchema); + expect(result.tools[1].annotations).toEqual(result.tools[0].annotations); }); /*** @@ -1241,7 +1243,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ); expect(listResult.tools).toHaveLength(1); - expect(listResult.tools[0]!.outputSchema).toMatchObject({ + expect(listResult.tools[0].outputSchema).toMatchObject({ type: 'object', properties: { processedInput: { type: 'string' }, @@ -1865,9 +1867,9 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const result = await client.request({ method: 'tools/list' }, ListToolsResultSchema); expect(result.tools).toHaveLength(1); - expect(result.tools[0]!.name).toBe('test-with-meta'); - expect(result.tools[0]!.description).toBe('A tool with _meta field'); - expect(result.tools[0]!._meta).toEqual(metaData); + expect(result.tools[0].name).toBe('test-with-meta'); + expect(result.tools[0].description).toBe('A tool with _meta field'); + expect(result.tools[0]._meta).toEqual(metaData); }); /*** @@ -1901,8 +1903,8 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const result = await client.request({ method: 'tools/list' }, ListToolsResultSchema); expect(result.tools).toHaveLength(1); - expect(result.tools[0]!.name).toBe('test-without-meta'); - expect(result.tools[0]!._meta).toBeUndefined(); + expect(result.tools[0].name).toBe('test-without-meta'); + expect(result.tools[0]._meta).toBeUndefined(); }); test('should include execution field in listTools response when tool has execution settings', async () => { @@ -1966,8 +1968,8 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const result = await client.request({ method: 'tools/list' }, ListToolsResultSchema); expect(result.tools).toHaveLength(1); - expect(result.tools[0]!.name).toBe('task-tool'); - expect(result.tools[0]!.execution).toEqual({ + expect(result.tools[0].name).toBe('task-tool'); + expect(result.tools[0].execution).toEqual({ taskSupport: 'required' }); @@ -2035,8 +2037,8 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const result = await client.request({ method: 'tools/list' }, ListToolsResultSchema); expect(result.tools).toHaveLength(1); - expect(result.tools[0]!.name).toBe('optional-task-tool'); - expect(result.tools[0]!.execution).toEqual({ + expect(result.tools[0].name).toBe('optional-task-tool'); + expect(result.tools[0].execution).toEqual({ taskSupport: 'optional' }); @@ -2129,8 +2131,8 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ); expect(result.resources).toHaveLength(1); - expect(result.resources[0]!.name).toBe('test'); - expect(result.resources[0]!.uri).toBe('test://resource'); + expect(result.resources[0].name).toBe('test'); + expect(result.resources[0].uri).toBe('test://resource'); }); /*** @@ -2374,7 +2376,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { result = await client.request({ method: 'resources/list' }, ListResourcesResultSchema); expect(result.resources).toHaveLength(1); - expect(result.resources[0]!.uri).toBe('test://resource2'); + expect(result.resources[0].uri).toBe('test://resource2'); }); /*** @@ -2481,9 +2483,9 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ); expect(result.resources).toHaveLength(1); - expect(result.resources[0]!.description).toBe('Test resource'); - expect(result.resources[0]!.mimeType).toBe('text/plain'); - expect(result.resources[0]!.annotations).toEqual({ + expect(result.resources[0].description).toBe('Test resource'); + expect(result.resources[0].mimeType).toBe('text/plain'); + expect(result.resources[0].annotations).toEqual({ audience: ['user'], priority: 0.5, lastModified: mockDate @@ -2524,8 +2526,8 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ); expect(result.resourceTemplates).toHaveLength(1); - expect(result.resourceTemplates[0]!.name).toBe('test'); - expect(result.resourceTemplates[0]!.uriTemplate).toBe('test://resource/{id}'); + expect(result.resourceTemplates[0].name).toBe('test'); + expect(result.resourceTemplates[0].uriTemplate).toBe('test://resource/{id}'); }); /*** @@ -2579,10 +2581,10 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ); expect(result.resources).toHaveLength(2); - expect(result.resources[0]!.name).toBe('Resource 1'); - expect(result.resources[0]!.uri).toBe('test://resource/1'); - expect(result.resources[1]!.name).toBe('Resource 2'); - expect(result.resources[1]!.uri).toBe('test://resource/2'); + expect(result.resources[0].name).toBe('Resource 1'); + expect(result.resources[0].uri).toBe('test://resource/1'); + expect(result.resources[1].name).toBe('Resource 2'); + expect(result.resources[1].uri).toBe('test://resource/2'); }); /*** @@ -3079,8 +3081,8 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ); expect(result.prompts).toHaveLength(1); - expect(result.prompts[0]!.name).toBe('test'); - expect(result.prompts[0]!.arguments).toBeUndefined(); + expect(result.prompts[0].name).toBe('test'); + expect(result.prompts[0].arguments).toBeUndefined(); }); /*** * Test: Updating Existing Prompt @@ -3226,8 +3228,8 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ListPromptsResultSchema ); - expect(listResult.prompts[0]!.arguments).toHaveLength(2); - expect(listResult.prompts[0]!.arguments!.map(a => a.name).sort()).toEqual(['name', 'value']); + expect(listResult.prompts[0].arguments).toHaveLength(2); + expect(listResult.prompts[0].arguments?.map(a => a.name).sort()).toEqual(['name', 'value']); // Call the prompt with the new schema const getResult = await client.request( @@ -3385,7 +3387,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { result = await client.request({ method: 'prompts/list' }, ListPromptsResultSchema); expect(result.prompts).toHaveLength(1); - expect(result.prompts[0]!.name).toBe('prompt2'); + expect(result.prompts[0].name).toBe('prompt2'); }); /*** @@ -3432,8 +3434,8 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ); expect(result.prompts).toHaveLength(1); - expect(result.prompts[0]!.name).toBe('test'); - expect(result.prompts[0]!.arguments).toEqual([ + expect(result.prompts[0].name).toBe('test'); + expect(result.prompts[0].arguments).toEqual([ { name: 'name', required: true }, { name: 'value', required: true } ]); @@ -3476,8 +3478,8 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ); expect(result.prompts).toHaveLength(1); - expect(result.prompts[0]!.name).toBe('test'); - expect(result.prompts[0]!.description).toBe('Test description'); + expect(result.prompts[0].name).toBe('test'); + expect(result.prompts[0].description).toBe('Test description'); }); /*** @@ -4025,14 +4027,14 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { expect(result.resources).toHaveLength(2); // Resource 1 should have its own metadata - expect(result.resources[0]!.name).toBe('Resource 1'); - expect(result.resources[0]!.description).toBe('Individual resource description'); - expect(result.resources[0]!.mimeType).toBe('text/plain'); + expect(result.resources[0].name).toBe('Resource 1'); + expect(result.resources[0].description).toBe('Individual resource description'); + expect(result.resources[0].mimeType).toBe('text/plain'); // Resource 2 should inherit template metadata - expect(result.resources[1]!.name).toBe('Resource 2'); - expect(result.resources[1]!.description).toBe('Template description'); - expect(result.resources[1]!.mimeType).toBe('application/json'); + expect(result.resources[1].name).toBe('Resource 2'); + expect(result.resources[1].description).toBe('Template description'); + expect(result.resources[1].mimeType).toBe('application/json'); }); /*** @@ -4092,9 +4094,9 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { expect(result.resources).toHaveLength(1); // All fields should be from the individual resource, not the template - expect(result.resources[0]!.name).toBe('Overridden Name'); - expect(result.resources[0]!.description).toBe('Overridden description'); - expect(result.resources[0]!.mimeType).toBe('text/markdown'); + expect(result.resources[0].name).toBe('Overridden Name'); + expect(result.resources[0].description).toBe('Overridden description'); + expect(result.resources[0].mimeType).toBe('text/markdown'); }); test('should support optional prompt arguments', async () => { @@ -4132,8 +4134,8 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ); expect(result.prompts).toHaveLength(1); - expect(result.prompts[0]!.name).toBe('test-prompt'); - expect(result.prompts[0]!.arguments).toEqual([ + expect(result.prompts[0].name).toBe('test-prompt'); + expect(result.prompts[0].arguments).toEqual([ { name: 'name', description: undefined, @@ -5212,8 +5214,8 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { ); expect(result.resources).toHaveLength(1); - expect(result.resources[0]!.name).toBe('test'); - expect(result.resources[0]!.uri).toBe('test://resource'); + expect(result.resources[0].name).toBe('test'); + expect(result.resources[0].uri).toBe('test://resource'); }); /*** @@ -5357,14 +5359,14 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { expect(result.resources).toHaveLength(2); // Resource 1 should have its own metadata - expect(result.resources[0]!.name).toBe('Resource 1'); - expect(result.resources[0]!.description).toBe('Individual resource description'); - expect(result.resources[0]!.mimeType).toBe('text/plain'); + expect(result.resources[0].name).toBe('Resource 1'); + expect(result.resources[0].description).toBe('Individual resource description'); + expect(result.resources[0].mimeType).toBe('text/plain'); // Resource 2 should inherit template metadata - expect(result.resources[1]!.name).toBe('Resource 2'); - expect(result.resources[1]!.description).toBe('Template description'); - expect(result.resources[1]!.mimeType).toBe('application/json'); + expect(result.resources[1].name).toBe('Resource 2'); + expect(result.resources[1].description).toBe('Template description'); + expect(result.resources[1].mimeType).toBe('application/json'); }); /*** @@ -5424,9 +5426,9 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { expect(result.resources).toHaveLength(1); // All fields should be from the individual resource, not the template - expect(result.resources[0]!.name).toBe('Overridden Name'); - expect(result.resources[0]!.description).toBe('Overridden description'); - expect(result.resources[0]!.mimeType).toBe('text/markdown'); + expect(result.resources[0].name).toBe('Overridden Name'); + expect(result.resources[0].description).toBe('Overridden description'); + expect(result.resources[0].mimeType).toBe('text/markdown'); }); }); @@ -6388,7 +6390,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { // Should receive error result expect(result.isError).toBe(true); const content = result.content as TextContent[]; - expect(content[0]!.text).toContain('requires task augmentation'); + expect(content[0].text).toContain('requires task augmentation'); taskStore.cleanup(); }); diff --git a/packages/server/test/server/sse.test.ts b/test/server/sse.test.ts similarity index 98% rename from packages/server/test/server/sse.test.ts rename to test/server/sse.test.ts index 0fc9eebc81..4686f2ba9d 100644 --- a/packages/server/test/server/sse.test.ts +++ b/test/server/sse.test.ts @@ -1,13 +1,12 @@ -import type http from 'node:http'; -import { createServer, type Server } from 'node:http'; - -import type { CallToolResult, JSONRPCMessage } from '@modelcontextprotocol/core'; -import type { ZodMatrixEntry } from '@modelcontextprotocol/test-helpers'; -import { listenOnRandomPort, zodTestMatrix } from '@modelcontextprotocol/test-helpers'; +import http from 'node:http'; import { type Mocked } from 'vitest'; -import { McpServer } from '../../src/server/mcp.js'; import { SSEServerTransport } from '../../src/server/sse.js'; +import { McpServer } from '../../src/server/mcp.js'; +import { createServer, type Server } from 'node:http'; +import { CallToolResult, JSONRPCMessage } from '../../src/types.js'; +import { zodTestMatrix, type ZodMatrixEntry } from '../../src/__fixtures__/zodTestMatrix.js'; +import { listenOnRandomPort } from '../helpers/http.js'; const createMockResponse = () => { const res = { @@ -143,7 +142,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const baseUrl = await listenOnRandomPort(server); const addr = server.address(); - const port = typeof addr === 'string' ? new URL(baseUrl).port : (addr as unknown as { port: number }).port; + const port = typeof addr === 'string' ? new URL(baseUrl).port : (addr as any).port; return { server, transport, mcpServer, baseUrl, sessionId, serverPort: Number(port) }; } diff --git a/packages/server/test/server/stdio.test.ts b/test/server/stdio.test.ts similarity index 90% rename from packages/server/test/server/stdio.test.ts rename to test/server/stdio.test.ts index f1c9e038cd..86379c8a61 100644 --- a/packages/server/test/server/stdio.test.ts +++ b/test/server/stdio.test.ts @@ -1,8 +1,6 @@ import { Readable, Writable } from 'node:stream'; - -import type { JSONRPCMessage } from '@modelcontextprotocol/core'; -import { ReadBuffer, serializeMessage } from '@modelcontextprotocol/core'; - +import { ReadBuffer, serializeMessage } from '../../src/shared/stdio.js'; +import { JSONRPCMessage } from '../../src/types.js'; import { StdioServerTransport } from '../../src/server/stdio.js'; let input: Readable; @@ -95,8 +93,8 @@ test('should read multiple messages', async () => { }; }); - input.push(serializeMessage(messages[0]!)); - input.push(serializeMessage(messages[1]!)); + input.push(serializeMessage(messages[0])); + input.push(serializeMessage(messages[1])); await server.start(); await finished; diff --git a/packages/server/test/server/streamableHttp.test.ts b/test/server/streamableHttp.test.ts similarity index 95% rename from packages/server/test/server/streamableHttp.test.ts rename to test/server/streamableHttp.test.ts index d8c6388e47..8d94b272e4 100644 --- a/packages/server/test/server/streamableHttp.test.ts +++ b/test/server/streamableHttp.test.ts @@ -1,23 +1,12 @@ +import { createServer, type Server, IncomingMessage, ServerResponse } from 'node:http'; +import { AddressInfo, createServer as netCreateServer } from 'node:net'; import { randomUUID } from 'node:crypto'; -import type { IncomingMessage, Server, ServerResponse } from 'node:http'; -import { createServer } from 'node:http'; -import type { AddressInfo } from 'node:net'; -import { createServer as netCreateServer } from 'node:net'; - -import type { - AuthInfo, - CallToolResult, - JSONRPCErrorResponse, - JSONRPCMessage, - JSONRPCResultResponse, - RequestId -} from '@modelcontextprotocol/core'; -import { listenOnRandomPort } from '@modelcontextprotocol/test-helpers'; - +import { EventStore, StreamableHTTPServerTransport, EventId, StreamId } from '../../src/server/streamableHttp.js'; import { McpServer } from '../../src/server/mcp.js'; -import { StreamableHTTPServerTransport } from '../../src/server/streamableHttp.js'; -import type { EventId, EventStore, StreamId } from '../../src/server/webStandardStreamableHttp.js'; -import { type ZodMatrixEntry, zodTestMatrix } from './__fixtures__/zodTestMatrix.js'; +import { CallToolResult, JSONRPCMessage } from '../../src/types.js'; +import { AuthInfo } from '../../src/server/auth/types.js'; +import { zodTestMatrix, type ZodMatrixEntry } from '../../src/__fixtures__/zodTestMatrix.js'; +import { listenOnRandomPort } from '../helpers/http.js'; async function getFreePort() { return new Promise(res => { @@ -66,21 +55,10 @@ const TEST_MESSAGES = { method: 'initialize', params: { clientInfo: { name: 'test-client', version: '1.0' }, - protocolVersion: '2025-11-25', + protocolVersion: '2025-03-26', capabilities: {} }, - id: 'init-1' - } as JSONRPCMessage, - // Initialize message with an older protocol version for backward compatibility tests - initializeOldVersion: { - jsonrpc: '2.0', - method: 'initialize', - params: { - clientInfo: { name: 'test-client', version: '1.0' }, - protocolVersion: '2025-06-18', - capabilities: {} - }, id: 'init-1' } as JSONRPCMessage, @@ -120,7 +98,8 @@ async function sendPostRequest( if (sessionId) { headers['mcp-session-id'] = sessionId; - headers['mcp-protocol-version'] = '2025-11-25'; + // After initialization, include the protocol version header + headers['mcp-protocol-version'] = '2025-03-26'; } return fetch(baseUrl, { @@ -130,12 +109,7 @@ async function sendPostRequest( }); } -function expectErrorResponse( - data: unknown, - expectedCode: number, - expectedMessagePattern: RegExp, - options?: { expectData?: boolean } -): void { +function expectErrorResponse(data: unknown, expectedCode: number, expectedMessagePattern: RegExp): void { expect(data).toMatchObject({ jsonrpc: '2.0', error: expect.objectContaining({ @@ -143,9 +117,6 @@ function expectErrorResponse( message: expect.stringMatching(expectedMessagePattern) }) }); - if (options?.expectData) { - expect((data as { error: { data?: string } }).error.data).toBeDefined(); - } } describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { /** @@ -462,7 +433,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const response = await sendPostRequest(baseUrl, TEST_MESSAGES.toolsList); expect(response.status).toBe(400); - const errorData = (await response.json()) as JSONRPCErrorResponse; + const errorData = await response.json(); expectErrorResponse(errorData, -32000, /Bad Request/); expect(errorData.id).toBeNull(); }); @@ -489,7 +460,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { headers: { Accept: 'text/event-stream', 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -530,7 +501,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { headers: { Accept: 'text/event-stream', 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -562,7 +533,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { headers: { Accept: 'text/event-stream', 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -574,7 +545,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { headers: { Accept: 'text/event-stream', 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -593,7 +564,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { headers: { Accept: 'application/json', 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -698,28 +669,6 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { expectErrorResponse(errorData, -32700, /Parse error/); }); - it('should include error data in parse error response for unexpected errors', async () => { - sessionId = await initializeServer(); - - // We can't easily trigger the catch-all error handler, but we can verify - // that the JSON parse error includes useful information - const response = await fetch(baseUrl, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Accept: 'application/json, text/event-stream', - 'mcp-session-id': sessionId - }, - body: '{ invalid json }' - }); - - expect(response.status).toBe(400); - const errorData = (await response.json()) as JSONRPCErrorResponse; - expectErrorResponse(errorData, -32700, /Parse error/); - // The error message should contain details about what went wrong - expect(errorData.error.message).toContain('Invalid JSON'); - }); - it('should return 400 error for invalid JSON-RPC messages', async () => { sessionId = await initializeServer(); @@ -809,7 +758,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { headers: { Accept: 'text/event-stream', 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -847,7 +796,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { method: 'DELETE', headers: { 'mcp-session-id': tempSessionId || '', - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -866,7 +815,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { method: 'DELETE', headers: { 'mcp-session-id': 'invalid-session-id', - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -920,12 +869,15 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { expect(response.status).toBe(400); const errorData = await response.json(); - expectErrorResponse(errorData, -32000, /Bad Request: Unsupported protocol version: .+ \(supported versions: .+\)/); + expectErrorResponse(errorData, -32000, /Bad Request: Unsupported protocol version \(supported versions: .+\)/); }); it('should accept when protocol version differs from negotiated version', async () => { sessionId = await initializeServer(); + // Spy on console.warn to verify warning is logged + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + // Send request with different but supported protocol version const response = await fetch(baseUrl, { method: 'POST', @@ -940,9 +892,11 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { // Request should still succeed expect(response.status).toBe(200); + + warnSpy.mockRestore(); }); - it('should reject unsupported protocol version on GET requests', async () => { + it('should handle protocol version validation for GET requests', async () => { sessionId = await initializeServer(); // GET request with unsupported protocol version @@ -951,16 +905,16 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { headers: { Accept: 'text/event-stream', 'mcp-session-id': sessionId, - 'mcp-protocol-version': '1999-01-01' // Unsupported version + 'mcp-protocol-version': 'invalid-version' } }); expect(response.status).toBe(400); const errorData = await response.json(); - expectErrorResponse(errorData, -32000, /Bad Request: Unsupported protocol version/); + expectErrorResponse(errorData, -32000, /Bad Request: Unsupported protocol version \(supported versions: .+\)/); }); - it('should reject unsupported protocol version on DELETE requests', async () => { + it('should handle protocol version validation for DELETE requests', async () => { sessionId = await initializeServer(); // DELETE request with unsupported protocol version @@ -968,13 +922,13 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { method: 'DELETE', headers: { 'mcp-session-id': sessionId, - 'mcp-protocol-version': '1999-01-01' // Unsupported version + 'mcp-protocol-version': 'invalid-version' } }); expect(response.status).toBe(400); const errorData = await response.json(); - expectErrorResponse(errorData, -32000, /Bad Request: Unsupported protocol version/); + expectErrorResponse(errorData, -32000, /Bad Request: Unsupported protocol version \(supported versions: .+\)/); }); }); }); @@ -1135,13 +1089,13 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { expect(response.status).toBe(200); expect(response.headers.get('content-type')).toBe('application/json'); - const results = (await response.json()) as JSONRPCResultResponse[]; + const results = await response.json(); expect(Array.isArray(results)).toBe(true); expect(results).toHaveLength(2); // Batch responses can come in any order - const listResponse = results.find((r: { id?: RequestId }) => r.id === 'batch-1'); - const callResponse = results.find((r: { id?: RequestId }) => r.id === 'batch-2'); + const listResponse = results.find((r: { id?: string }) => r.id === 'batch-1'); + const callResponse = results.find((r: { id?: string }) => r.id === 'batch-2'); expect(listResponse).toEqual( expect.objectContaining({ @@ -1326,7 +1280,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { send: (eventId: EventId, message: JSONRPCMessage) => Promise; } ): Promise { - const streamId = lastEventId.split('_')[0]!; + const streamId = lastEventId.split('_')[0]; // Extract stream ID from the event ID // For test simplicity, just return all events with matching streamId that aren't the lastEventId for (const [eventId, { message }] of storedEvents.entries()) { @@ -1350,6 +1304,9 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { baseUrl = result.baseUrl; mcpServer = result.mcpServer; + // Verify resumability is enabled on the transport + expect(transport['_eventStore']).toBeDefined(); + // Initialize the server const initResponse = await sendPostRequest(baseUrl, TEST_MESSAGES.initialize); sessionId = initResponse.headers.get('mcp-session-id') as string; @@ -1368,7 +1325,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { headers: { Accept: 'text/event-stream', 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -1399,7 +1356,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { expect(idMatch).toBeTruthy(); // Verify the event was stored - const eventId = idMatch![1]!; + const eventId = idMatch![1]; expect(storedEvents.has(eventId)).toBe(true); const storedEvent = storedEvents.get(eventId); expect(eventId.startsWith('_GET_stream')).toBe(true); @@ -1413,7 +1370,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { headers: { Accept: 'text/event-stream', 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); expect(sseResponse.status).toBe(200); @@ -1433,7 +1390,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { // Extract the event ID const idMatch = text.match(/id: ([^\n]+)/); expect(idMatch).toBeTruthy(); - const firstEventId = idMatch![1]!; + const firstEventId = idMatch![1]; // Send a second notification await mcpServer.server.sendLoggingMessage({ level: 'info', data: 'Second notification from MCP server' }); @@ -1447,7 +1404,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { headers: { Accept: 'text/event-stream', 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-11-25', + 'mcp-protocol-version': '2025-03-26', 'last-event-id': firstEventId } }); @@ -1471,7 +1428,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { headers: { Accept: 'text/event-stream', 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); expect(sseResponse.status).toBe(200); @@ -1488,7 +1445,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { // Extract the event ID const idMatch = text.match(/id: ([^\n]+)/); expect(idMatch).toBeTruthy(); - const lastEventId = idMatch![1]!; + const lastEventId = idMatch![1]; // Close the SSE stream to simulate a disconnect await reader!.cancel(); @@ -1504,7 +1461,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { headers: { Accept: 'text/event-stream', 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-11-25', + 'mcp-protocol-version': '2025-03-26', 'last-event-id': lastEventId } }); @@ -1608,7 +1565,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { method: 'GET', headers: { Accept: 'text/event-stream', - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); expect(stream1.status).toBe(200); @@ -1618,7 +1575,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { method: 'GET', headers: { Accept: 'text/event-stream', - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); expect(stream2.status).toBe(409); // Conflict - only one stream allowed @@ -1651,7 +1608,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { { send }: { send: (eventId: EventId, message: JSONRPCMessage) => Promise } ): Promise { const event = storedEvents.get(lastEventId); - const streamId = event?.streamId || lastEventId.split('::')[0]!; + const streamId = event?.streamId || lastEventId.split('::')[0]; const eventsToReplay: Array<[string, { message: JSONRPCMessage }]> = []; for (const [eventId, data] of storedEvents.entries()) { if (data.streamId === streamId && eventId > lastEventId) { @@ -1735,12 +1692,12 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { baseUrl = result.baseUrl; mcpServer = result.mcpServer; - // Initialize with OLD protocol version to get session ID - const initResponse = await sendPostRequest(baseUrl, TEST_MESSAGES.initializeOldVersion); + // Initialize to get session ID + const initResponse = await sendPostRequest(baseUrl, TEST_MESSAGES.initialize); sessionId = initResponse.headers.get('mcp-session-id') as string; expect(sessionId).toBeDefined(); - // Send a tool call request with the same OLD protocol version + // Send a tool call request with OLD protocol version const toolCallRequest: JSONRPCMessage = { jsonrpc: '2.0', id: 100, @@ -1975,12 +1932,12 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { return { content: [{ type: 'text', text: 'Done' }] }; }); - // Initialize with OLD protocol version to get session ID - const initResponse = await sendPostRequest(baseUrl, TEST_MESSAGES.initializeOldVersion); + // Initialize to get session ID + const initResponse = await sendPostRequest(baseUrl, TEST_MESSAGES.initialize); sessionId = initResponse.headers.get('mcp-session-id') as string; expect(sessionId).toBeDefined(); - // Call the tool with the same OLD protocol version + // Call the tool with OLD protocol version const toolCallRequest: JSONRPCMessage = { jsonrpc: '2.0', id: 200, @@ -2052,7 +2009,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { 'Content-Type': 'application/json', Accept: 'text/event-stream, application/json', 'mcp-session-id': sessionId, - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' }, body: JSON.stringify(toolCallRequest) }); @@ -2252,7 +2209,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const text = new TextDecoder().decode(value); const idMatch = text.match(/id: ([^\n]+)/); expect(idMatch).toBeTruthy(); - const lastEventId = idMatch![1]!; + const lastEventId = idMatch![1]; // Call the tool to close the standalone SSE stream const toolCallRequest: JSONRPCMessage = { @@ -2323,8 +2280,8 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { // Verify we received the notification that was sent while disconnected expect(allText).toContain('Missed while disconnected'); - }, 15000); - }); + }); + }, 10000); // Test onsessionclosed callback describe('StreamableHTTPServerTransport onsessionclosed callback', () => { @@ -2350,7 +2307,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { method: 'DELETE', headers: { 'mcp-session-id': tempSessionId || '', - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -2410,7 +2367,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { method: 'DELETE', headers: { 'mcp-session-id': 'invalid-session-id', - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -2458,7 +2415,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { method: 'DELETE', headers: { 'mcp-session-id': sessionId1 || '', - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -2471,7 +2428,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { method: 'DELETE', headers: { 'mcp-session-id': sessionId2 || '', - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -2570,7 +2527,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { method: 'DELETE', headers: { 'mcp-session-id': tempSessionId || '', - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -2631,7 +2588,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { method: 'DELETE', headers: { 'mcp-session-id': tempSessionId || '', - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -2675,7 +2632,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { method: 'DELETE', headers: { 'mcp-session-id': tempSessionId || '', - 'mcp-protocol-version': '2025-11-25' + 'mcp-protocol-version': '2025-03-26' } }); @@ -2751,7 +2708,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { }); expect(response.status).toBe(403); - const body = (await response.json()) as JSONRPCErrorResponse; + const body = await response.json(); expect(body.error.message).toContain('Invalid Host header:'); }); @@ -2821,7 +2778,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { }); expect(response.status).toBe(403); - const body = (await response.json()) as JSONRPCErrorResponse; + const body = await response.json(); expect(body.error.message).toBe('Invalid Origin header: http://evil.com'); }); @@ -2901,7 +2858,7 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { }); expect(response1.status).toBe(403); - const body1 = (await response1.json()) as JSONRPCErrorResponse; + const body1 = await response1.json(); expect(body1.error.message).toBe('Invalid Origin header: http://evil.com'); // Test with valid origin diff --git a/test/integration/test/title.test.ts b/test/server/title.test.ts similarity index 80% rename from test/integration/test/title.test.ts rename to test/server/title.test.ts index 4eec82335d..de353af306 100644 --- a/test/integration/test/title.test.ts +++ b/test/server/title.test.ts @@ -1,7 +1,8 @@ -import { Client } from '@modelcontextprotocol/client'; -import { InMemoryTransport } from '@modelcontextprotocol/core'; -import { McpServer, ResourceTemplate, Server } from '@modelcontextprotocol/server'; -import { type ZodMatrixEntry, zodTestMatrix } from '@modelcontextprotocol/test-helpers'; +import { Server } from '../../src/server/index.js'; +import { Client } from '../../src/client/index.js'; +import { InMemoryTransport } from '../../src/inMemory.js'; +import { McpServer, ResourceTemplate } from '../../src/server/mcp.js'; +import { zodTestMatrix, type ZodMatrixEntry } from '../../src/__fixtures__/zodTestMatrix.js'; describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const { z } = entry; @@ -32,9 +33,9 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const tools = await client.listTools(); expect(tools.tools).toHaveLength(1); - expect(tools.tools[0]!.name).toBe('test-tool'); - expect(tools.tools[0]!.title).toBe('Test Tool Display Name'); - expect(tools.tools[0]!.description).toBe('A test tool'); + expect(tools.tools[0].name).toBe('test-tool'); + expect(tools.tools[0].title).toBe('Test Tool Display Name'); + expect(tools.tools[0].description).toBe('A test tool'); }); it('should work with tools without title', async () => { @@ -52,9 +53,9 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const tools = await client.listTools(); expect(tools.tools).toHaveLength(1); - expect(tools.tools[0]!.name).toBe('test-tool'); - expect(tools.tools[0]!.title).toBeUndefined(); - expect(tools.tools[0]!.description).toBe('A test tool'); + expect(tools.tools[0].name).toBe('test-tool'); + expect(tools.tools[0].title).toBeUndefined(); + expect(tools.tools[0].description).toBe('A test tool'); }); it('should work with prompts that have title using update', async () => { @@ -75,9 +76,9 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const prompts = await client.listPrompts(); expect(prompts.prompts).toHaveLength(1); - expect(prompts.prompts[0]!.name).toBe('test-prompt'); - expect(prompts.prompts[0]!.title).toBe('Test Prompt Display Name'); - expect(prompts.prompts[0]!.description).toBe('A test prompt'); + expect(prompts.prompts[0].name).toBe('test-prompt'); + expect(prompts.prompts[0].title).toBe('Test Prompt Display Name'); + expect(prompts.prompts[0].description).toBe('A test prompt'); }); it('should work with prompts using registerPrompt', async () => { @@ -110,10 +111,10 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const prompts = await client.listPrompts(); expect(prompts.prompts).toHaveLength(1); - expect(prompts.prompts[0]!.name).toBe('test-prompt'); - expect(prompts.prompts[0]!.title).toBe('Test Prompt Display Name'); - expect(prompts.prompts[0]!.description).toBe('A test prompt'); - expect(prompts.prompts[0]!.arguments).toHaveLength(1); + expect(prompts.prompts[0].name).toBe('test-prompt'); + expect(prompts.prompts[0].title).toBe('Test Prompt Display Name'); + expect(prompts.prompts[0].description).toBe('A test prompt'); + expect(prompts.prompts[0].arguments).toHaveLength(1); }); it('should work with resources using registerResource', async () => { @@ -147,10 +148,10 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const resources = await client.listResources(); expect(resources.resources).toHaveLength(1); - expect(resources.resources[0]!.name).toBe('test-resource'); - expect(resources.resources[0]!.title).toBe('Test Resource Display Name'); - expect(resources.resources[0]!.description).toBe('A test resource'); - expect(resources.resources[0]!.mimeType).toBe('text/plain'); + expect(resources.resources[0].name).toBe('test-resource'); + expect(resources.resources[0].title).toBe('Test Resource Display Name'); + expect(resources.resources[0].description).toBe('A test resource'); + expect(resources.resources[0].mimeType).toBe('text/plain'); }); it('should work with dynamic resources using registerResource', async () => { @@ -183,10 +184,10 @@ describe.each(zodTestMatrix)('$zodVersionLabel', (entry: ZodMatrixEntry) => { const resourceTemplates = await client.listResourceTemplates(); expect(resourceTemplates.resourceTemplates).toHaveLength(1); - expect(resourceTemplates.resourceTemplates[0]!.name).toBe('user-profile'); - expect(resourceTemplates.resourceTemplates[0]!.title).toBe('User Profile'); - expect(resourceTemplates.resourceTemplates[0]!.description).toBe('User profile information'); - expect(resourceTemplates.resourceTemplates[0]!.uriTemplate).toBe('users://{userId}/profile'); + expect(resourceTemplates.resourceTemplates[0].name).toBe('user-profile'); + expect(resourceTemplates.resourceTemplates[0].title).toBe('User Profile'); + expect(resourceTemplates.resourceTemplates[0].description).toBe('User profile information'); + expect(resourceTemplates.resourceTemplates[0].uriTemplate).toBe('users://{userId}/profile'); // Test reading the resource const readResult = await client.readResource({ uri: 'users://123/profile' }); diff --git a/packages/core/test/shared/auth-utils.test.ts b/test/shared/auth-utils.test.ts similarity index 98% rename from packages/core/test/shared/auth-utils.test.ts rename to test/shared/auth-utils.test.ts index 64cb5a1634..b3b13a2f60 100644 --- a/packages/core/test/shared/auth-utils.test.ts +++ b/test/shared/auth-utils.test.ts @@ -1,4 +1,4 @@ -import { checkResourceAllowed, resourceUrlFromServerUrl } from '../../src/shared/auth-utils.js'; +import { resourceUrlFromServerUrl, checkResourceAllowed } from '../../src/shared/auth-utils.js'; describe('auth-utils', () => { describe('resourceUrlFromServerUrl', () => { diff --git a/packages/core/test/shared/auth.test.ts b/test/shared/auth.test.ts similarity index 99% rename from packages/core/test/shared/auth.test.ts rename to test/shared/auth.test.ts index 770e0c4d48..c4ecab59d5 100644 --- a/packages/core/test/shared/auth.test.ts +++ b/test/shared/auth.test.ts @@ -1,9 +1,9 @@ import { - OAuthClientMetadataSchema, + SafeUrlSchema, OAuthMetadataSchema, OpenIdProviderMetadataSchema, - OptionalSafeUrlSchema, - SafeUrlSchema + OAuthClientMetadataSchema, + OptionalSafeUrlSchema } from '../../src/shared/auth.js'; describe('SafeUrlSchema', () => { diff --git a/packages/core/test/shared/protocol-transport-handling.test.ts b/test/shared/protocol-transport-handling.test.ts similarity index 96% rename from packages/core/test/shared/protocol-transport-handling.test.ts rename to test/shared/protocol-transport-handling.test.ts index 0e1b9b5c9b..60eff5c2e0 100644 --- a/packages/core/test/shared/protocol-transport-handling.test.ts +++ b/test/shared/protocol-transport-handling.test.ts @@ -1,9 +1,8 @@ -import { beforeEach, describe, expect, test } from 'vitest'; -import * as z from 'zod/v4'; - +import { describe, expect, test, beforeEach } from 'vitest'; import { Protocol } from '../../src/shared/protocol.js'; -import type { Transport } from '../../src/shared/transport.js'; -import type { JSONRPCMessage, Notification, Request, Result } from '../../src/types/types.js'; +import { Transport } from '../../src/shared/transport.js'; +import { Request, Notification, Result, JSONRPCMessage } from '../../src/types.js'; +import * as z from 'zod/v4'; // Mock Transport class class MockTransport implements Transport { diff --git a/packages/core/test/shared/protocol.test.ts b/test/shared/protocol.test.ts similarity index 97% rename from packages/core/test/shared/protocol.test.ts rename to test/shared/protocol.test.ts index b16a4453d5..6681cfd17f 100644 --- a/packages/core/test/shared/protocol.test.ts +++ b/test/shared/protocol.test.ts @@ -1,41 +1,32 @@ -import type { MockInstance } from 'vitest'; -import { vi } from 'vitest'; -import type { ZodType } from 'zod'; -import { z } from 'zod'; - -import type { - QueuedMessage, - QueuedNotification, - QueuedRequest, - TaskMessageQueue, - TaskStore -} from '../../src/experimental/tasks/interfaces.js'; -import { InMemoryTaskMessageQueue } from '../../src/experimental/tasks/stores/in-memory.js'; -import { mergeCapabilities, Protocol } from '../../src/shared/protocol.js'; -import type { ErrorMessage, ResponseMessage } from '../../src/shared/responseMessage.js'; -import { toArrayAsync } from '../../src/shared/responseMessage.js'; -import type { Transport, TransportSendOptions } from '../../src/shared/transport.js'; -import type { +import { ZodType, z } from 'zod'; +import { + CallToolRequestSchema, ClientCapabilities, - JSONRPCErrorResponse, + ErrorCode, JSONRPCMessage, - JSONRPCRequest, - JSONRPCResultResponse, + McpError, Notification, + RELATED_TASK_META_KEY, Request, RequestId, Result, ServerCapabilities, Task, TaskCreationParams -} from '../../src/types/types.js'; -import { CallToolRequestSchema, ErrorCode, McpError, RELATED_TASK_META_KEY } from '../../src/types/types.js'; +} from '../../src/types.js'; +import { Protocol, mergeCapabilities } from '../../src/shared/protocol.js'; +import { Transport, TransportSendOptions } from '../../src/shared/transport.js'; +import { TaskStore, TaskMessageQueue, QueuedMessage, QueuedNotification, QueuedRequest } from '../../src/experimental/tasks/interfaces.js'; +import { MockInstance, vi } from 'vitest'; +import { JSONRPCResponse, JSONRPCRequest, JSONRPCError } from '../../src/types.js'; +import { ErrorMessage, ResponseMessage, toArrayAsync } from '../../src/shared/responseMessage.js'; +import { InMemoryTaskMessageQueue } from '../../src/experimental/tasks/stores/in-memory.js'; // Type helper for accessing private/protected Protocol properties in tests interface TestProtocol { _taskMessageQueue?: TaskMessageQueue; - _requestResolvers: Map void>; - _responseHandlers: Map void>; + _requestResolvers: Map void>; + _responseHandlers: Map void>; _taskProgressTokens: Map; _clearTaskQueue: (taskId: string, sessionId?: string) => Promise; requestTaskStore: (request: Request, authInfo: unknown) => TaskStore; @@ -721,7 +712,7 @@ describe('protocol tests', () => { expect(sendSpy).toHaveBeenCalledTimes(1); // The final sent object might not even have the `params` key, which is fine. // We can check that it was called and that the params are "falsy". - const sentNotification = sendSpy.mock.calls[0]![0]; + const sentNotification = sendSpy.mock.calls[0][0]; expect(sentNotification.method).toBe('test/debounced'); expect(sentNotification.params).toBeUndefined(); }); @@ -1346,7 +1337,7 @@ describe('Task-based execution', () => { await listedTasks.waitForLatch(); expect(mockTaskStore.listTasks).toHaveBeenCalledWith(undefined, undefined); - const sentMessage = sendSpy.mock.calls[0]![0]; + const sentMessage = sendSpy.mock.calls[0][0]; expect(sentMessage.jsonrpc).toBe('2.0'); expect(sentMessage.id).toBe(3); expect(sentMessage.result.tasks).toEqual([ @@ -1409,7 +1400,7 @@ describe('Task-based execution', () => { await listedTasks.waitForLatch(); expect(mockTaskStore.listTasks).toHaveBeenCalledWith('task-2', undefined); - const sentMessage = sendSpy.mock.calls[0]![0]; + const sentMessage = sendSpy.mock.calls[0][0]; expect(sentMessage.jsonrpc).toBe('2.0'); expect(sentMessage.id).toBe(2); expect(sentMessage.result.tasks).toEqual([ @@ -1453,7 +1444,7 @@ describe('Task-based execution', () => { await listedTasks.waitForLatch(); expect(mockTaskStore.listTasks).toHaveBeenCalledWith(undefined, undefined); - const sentMessage = sendSpy.mock.calls[0]![0]; + const sentMessage = sendSpy.mock.calls[0][0]; expect(sentMessage.jsonrpc).toBe('2.0'); expect(sentMessage.id).toBe(3); expect(sentMessage.result.tasks).toEqual([]); @@ -1488,7 +1479,7 @@ describe('Task-based execution', () => { await new Promise(resolve => setTimeout(resolve, 10)); expect(mockTaskStore.listTasks).toHaveBeenCalledWith('bad-cursor', undefined); - const sentMessage = sendSpy.mock.calls[0]![0]; + const sentMessage = sendSpy.mock.calls[0][0]; expect(sentMessage.jsonrpc).toBe('2.0'); expect(sentMessage.id).toBe(4); expect(sentMessage.error).toBeDefined(); @@ -1506,7 +1497,7 @@ describe('Task-based execution', () => { setTimeout(() => { transport.onmessage?.({ jsonrpc: '2.0', - id: sendSpy.mock.calls[0]![0].id, + id: sendSpy.mock.calls[0][0].id, result: { tasks: [ { @@ -1534,7 +1525,7 @@ describe('Task-based execution', () => { expect.any(Object) ); expect(result.tasks).toHaveLength(1); - expect(result.tasks[0]?.taskId).toBe('task-1'); + expect(result.tasks[0].taskId).toBe('task-1'); }); it('should call listTasks with cursor from client side', async () => { @@ -1546,7 +1537,7 @@ describe('Task-based execution', () => { setTimeout(() => { transport.onmessage?.({ jsonrpc: '2.0', - id: sendSpy.mock.calls[0]![0].id, + id: sendSpy.mock.calls[0][0].id, result: { tasks: [ { @@ -1576,7 +1567,7 @@ describe('Task-based execution', () => { expect.any(Object) ); expect(result.tasks).toHaveLength(1); - expect(result.tasks[0]?.taskId).toBe('task-11'); + expect(result.tasks[0].taskId).toBe('task-11'); expect(result.nextCursor).toBe('task-11'); }); }); @@ -1629,7 +1620,7 @@ describe('Task-based execution', () => { 'Client cancelled task execution.', undefined ); - const sentMessage = sendSpy.mock.calls[0]![0] as unknown as JSONRPCResultResponse; + const sentMessage = sendSpy.mock.calls[0][0] as unknown as JSONRPCResponse; expect(sentMessage.jsonrpc).toBe('2.0'); expect(sentMessage.id).toBe(5); expect(sentMessage.result._meta).toBeDefined(); @@ -1667,7 +1658,7 @@ describe('Task-based execution', () => { taskDeleted.releaseLatch(); expect(mockTaskStore.getTask).toHaveBeenCalledWith('non-existent', undefined); - const sentMessage = sendSpy.mock.calls[0]![0] as unknown as JSONRPCErrorResponse; + const sentMessage = sendSpy.mock.calls[0][0] as unknown as JSONRPCError; expect(sentMessage.jsonrpc).toBe('2.0'); expect(sentMessage.id).toBe(6); expect(sentMessage.error).toBeDefined(); @@ -1715,7 +1706,7 @@ describe('Task-based execution', () => { expect(mockTaskStore.getTask).toHaveBeenCalledWith(completedTask.taskId, undefined); expect(mockTaskStore.updateTaskStatus).not.toHaveBeenCalled(); - const sentMessage = sendSpy.mock.calls[0]![0] as unknown as JSONRPCErrorResponse; + const sentMessage = sendSpy.mock.calls[0][0] as unknown as JSONRPCError; expect(sentMessage.jsonrpc).toBe('2.0'); expect(sentMessage.id).toBe(7); expect(sentMessage.error).toBeDefined(); @@ -1732,7 +1723,7 @@ describe('Task-based execution', () => { setTimeout(() => { transport.onmessage?.({ jsonrpc: '2.0', - id: sendSpy.mock.calls[0]![0].id, + id: sendSpy.mock.calls[0][0].id, result: { _meta: {}, taskId: 'task-to-delete', @@ -1807,7 +1798,7 @@ describe('Task-based execution', () => { // This is done by the RequestTaskStore wrapper to get the updated task for the notification const getTaskCalls = mockTaskStore.getTask.mock.calls; const lastGetTaskCall = getTaskCalls[getTaskCalls.length - 1]; - expect(lastGetTaskCall?.[0]).toBe(task.taskId); + expect(lastGetTaskCall[0]).toBe(task.taskId); }); }); @@ -1857,7 +1848,7 @@ describe('Task-based execution', () => { ); // Verify _meta is not present or doesn't contain RELATED_TASK_META_KEY - const response = sendSpy.mock.calls[0]![0] as { result?: { _meta?: Record } }; + const response = sendSpy.mock.calls[0][0] as { result?: { _meta?: Record } }; expect(response.result?._meta?.[RELATED_TASK_META_KEY]).toBeUndefined(); }); @@ -1894,7 +1885,7 @@ describe('Task-based execution', () => { await new Promise(resolve => setTimeout(resolve, 50)); // Verify response does NOT include related-task metadata - const response = sendSpy.mock.calls[0]![0] as { result?: { _meta?: Record } }; + const response = sendSpy.mock.calls[0][0] as { result?: { _meta?: Record } }; expect(response.result?._meta).toEqual({}); }); @@ -1933,7 +1924,7 @@ describe('Task-based execution', () => { await new Promise(resolve => setTimeout(resolve, 50)); // Verify response does NOT include related-task metadata - const response = sendSpy.mock.calls[0]![0] as { result?: { _meta?: Record } }; + const response = sendSpy.mock.calls[0][0] as { result?: { _meta?: Record } }; expect(response.result?._meta).toEqual({}); }); @@ -2423,7 +2414,7 @@ describe('Progress notification support for tasks', () => { await new Promise(resolve => setTimeout(resolve, 10)); // Get the message ID from the sent request - const sentRequest = sendSpy.mock.calls[0]![0] as { id: number; params: { _meta: { progressToken: number } } }; + const sentRequest = sendSpy.mock.calls[0][0] as { id: number; params: { _meta: { progressToken: number } } }; const messageId = sentRequest.id; const progressToken = sentRequest.params._meta.progressToken; @@ -2532,7 +2523,7 @@ describe('Progress notification support for tasks', () => { // Wait a bit for the request to be sent await new Promise(resolve => setTimeout(resolve, 10)); - const sentRequest = sendSpy.mock.calls[0]![0] as { id: number; params: { _meta: { progressToken: number } } }; + const sentRequest = sendSpy.mock.calls[0][0] as { id: number; params: { _meta: { progressToken: number } } }; const messageId = sentRequest.id; const progressToken = sentRequest.params._meta.progressToken; @@ -2642,7 +2633,7 @@ describe('Progress notification support for tasks', () => { onprogress: progressCallback }); - const sentRequest = sendSpy.mock.calls[0]![0] as { id: number; params: { _meta: { progressToken: number } } }; + const sentRequest = sendSpy.mock.calls[0][0] as { id: number; params: { _meta: { progressToken: number } } }; const messageId = sentRequest.id; const progressToken = sentRequest.params._meta.progressToken; @@ -2740,7 +2731,7 @@ describe('Progress notification support for tasks', () => { onprogress: progressCallback }); - const sentRequest = sendSpy.mock.calls[0]![0] as { id: number; params: { _meta: { progressToken: number } } }; + const sentRequest = sendSpy.mock.calls[0][0] as { id: number; params: { _meta: { progressToken: number } } }; const messageId = sentRequest.id; const progressToken = sentRequest.params._meta.progressToken; @@ -2835,7 +2826,7 @@ describe('Progress notification support for tasks', () => { onprogress: progressCallback }); - const sentRequest = sendSpy.mock.calls[0]![0] as { id: number; params: { _meta: { progressToken: number } } }; + const sentRequest = sendSpy.mock.calls[0][0] as { id: number; params: { _meta: { progressToken: number } } }; const messageId = sentRequest.id; const progressToken = sentRequest.params._meta.progressToken; @@ -2908,7 +2899,7 @@ describe('Progress notification support for tasks', () => { onprogress: onProgressMock }); - const sentMessage = sendSpy.mock.calls[0]![0]; + const sentMessage = sendSpy.mock.calls[0][0]; expect(sentMessage.params._meta.progressToken).toBeDefined(); }); @@ -2933,7 +2924,7 @@ describe('Progress notification support for tasks', () => { onprogress: onProgressMock }); - const sentMessage = sendSpy.mock.calls[0]![0]; + const sentMessage = sendSpy.mock.calls[0][0]; const progressToken = sentMessage.params._meta.progressToken; // Simulate progress notification @@ -2983,7 +2974,7 @@ describe('Progress notification support for tasks', () => { onprogress: onProgressMock }); - const sentMessage = sendSpy.mock.calls[0]![0]; + const sentMessage = sendSpy.mock.calls[0][0]; const progressToken = sentMessage.params._meta.progressToken; // Simulate CreateTaskResult response @@ -3886,7 +3877,7 @@ describe('Message Interception', () => { expect(queue).toBeDefined(); // Clean up the pending request - const requestId = (sendSpy.mock.calls[0]![0] as JSONRPCResultResponse).id; + const requestId = (sendSpy.mock.calls[0][0] as JSONRPCResponse).id; transport.onmessage?.({ jsonrpc: '2.0', id: requestId, @@ -4496,7 +4487,7 @@ describe('requestStream() method', () => { // Should yield exactly one result message expect(messages).toHaveLength(1); - expect(messages[0]?.type).toBe('result'); + expect(messages[0].type).toBe('result'); expect(messages[0]).toHaveProperty('result'); }); @@ -4539,10 +4530,10 @@ describe('requestStream() method', () => { // Should yield exactly one error message expect(messages).toHaveLength(1); - expect(messages[0]?.type).toBe('error'); + expect(messages[0].type).toBe('error'); expect(messages[0]).toHaveProperty('error'); - if (messages[0]?.type === 'error') { - expect(messages[0]?.error?.message).toContain('Test error'); + if (messages[0].type === 'error') { + expect(messages[0].error.message).toContain('Test error'); } }); @@ -4577,9 +4568,9 @@ describe('requestStream() method', () => { // Should yield error message about cancellation expect(messages).toHaveLength(1); - expect(messages[0]?.type).toBe('error'); - if (messages[0]?.type === 'error') { - expect(messages[0]?.error?.message).toContain('cancelled'); + expect(messages[0].type).toBe('error'); + if (messages[0].type === 'error') { + expect(messages[0].error.message).toContain('cancelled'); } }); @@ -4619,7 +4610,7 @@ describe('requestStream() method', () => { // Verify error is terminal and last message expect(messages.length).toBeGreaterThan(0); const lastMessage = messages[messages.length - 1]; - assertErrorResponse(lastMessage!); + assertErrorResponse(lastMessage); expect(lastMessage.error).toBeDefined(); expect(lastMessage.error.message).toContain('Server error'); }); @@ -4656,7 +4647,7 @@ describe('requestStream() method', () => { // Verify error is terminal and last message expect(messages.length).toBeGreaterThan(0); const lastMessage = messages[messages.length - 1]; - assertErrorResponse(lastMessage!); + assertErrorResponse(lastMessage); expect(lastMessage.error).toBeDefined(); expect(lastMessage.error.code).toBe(ErrorCode.RequestTimeout); } finally { @@ -4692,7 +4683,7 @@ describe('requestStream() method', () => { // Verify error is terminal and last message expect(messages.length).toBeGreaterThan(0); const lastMessage = messages[messages.length - 1]; - assertErrorResponse(lastMessage!); + assertErrorResponse(lastMessage); expect(lastMessage.error).toBeDefined(); expect(lastMessage.error.message).toContain('cancelled'); }); @@ -4731,7 +4722,7 @@ describe('requestStream() method', () => { // Verify only one message (the error) was yielded expect(messages).toHaveLength(1); - expect(messages[0]?.type).toBe('error'); + expect(messages[0].type).toBe('error'); // Try to send another message (should be ignored) transport.onmessage?.({ @@ -4805,7 +4796,7 @@ describe('requestStream() method', () => { // Verify error is terminal and last message expect(messages.length).toBeGreaterThan(0); const lastMessage = messages[messages.length - 1]; - assertErrorResponse(lastMessage!); + assertErrorResponse(lastMessage); expect(lastMessage.error).toBeDefined(); }); @@ -4833,7 +4824,7 @@ describe('requestStream() method', () => { // Verify error is terminal and last message expect(messages.length).toBeGreaterThan(0); const lastMessage = messages[messages.length - 1]; - assertErrorResponse(lastMessage!); + assertErrorResponse(lastMessage); expect(lastMessage.error).toBeDefined(); }); @@ -4872,12 +4863,12 @@ describe('requestStream() method', () => { // Verify error is the last message expect(messages.length).toBeGreaterThan(0); const lastMessage = messages[messages.length - 1]; - expect(lastMessage?.type).toBe('error'); + expect(lastMessage.type).toBe('error'); // Verify all messages before the last are not terminal for (let i = 0; i < messages.length - 1; i++) { - expect(messages[i]?.type).not.toBe('error'); - expect(messages[i]?.type).not.toBe('result'); + expect(messages[i].type).not.toBe('error'); + expect(messages[i].type).not.toBe('result'); } }); }); @@ -4940,7 +4931,7 @@ describe('Error handling for missing resolvers', () => { // Manually trigger the response handling logic if (queuedMessage && queuedMessage.type === 'response') { - const responseMessage = queuedMessage.message as JSONRPCResultResponse; + const responseMessage = queuedMessage.message as JSONRPCResponse; const requestId = responseMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); @@ -5061,7 +5052,7 @@ describe('Error handling for missing resolvers', () => { expect(resolverMock).toHaveBeenCalledWith(expect.any(McpError)); // Verify the error has the correct properties - const calledError = resolverMock.mock.calls[0]![0]; + const calledError = resolverMock.mock.calls[0][0]; expect(calledError.code).toBe(ErrorCode.InternalError); expect(calledError.message).toContain('Task cancelled or completed'); @@ -5121,7 +5112,7 @@ describe('Error handling for missing resolvers', () => { expect(resolverMock).toHaveBeenCalledWith(expect.any(McpError)); // Verify the error has the correct properties - const calledError = resolverMock.mock.calls[0]![0]; + const calledError = resolverMock.mock.calls[0][0]; expect(calledError.code).toBe(ErrorCode.InternalError); expect(calledError.message).toContain('Task cancelled or completed'); @@ -5146,7 +5137,7 @@ describe('Error handling for missing resolvers', () => { const messageId = 123; // Create a response resolver without a corresponding response handler - const responseResolver = (response: JSONRPCResultResponse | Error) => { + const responseResolver = (response: JSONRPCResponse | Error) => { const handler = testProtocol._responseHandlers.get(messageId); if (handler) { handler(response); @@ -5156,7 +5147,7 @@ describe('Error handling for missing resolvers', () => { }; // Simulate the resolver being called without a handler - const mockResponse: JSONRPCResultResponse = { + const mockResponse: JSONRPCResponse = { jsonrpc: '2.0', id: messageId, result: { content: [] } @@ -5194,7 +5185,7 @@ describe('Error handling for missing resolvers', () => { const msg = await taskMessageQueue.dequeue(task.taskId); if (msg && msg.type === 'response') { const testProtocol = protocol as unknown as TestProtocol; - const responseMessage = msg.message as JSONRPCResultResponse; + const responseMessage = msg.message as JSONRPCResponse; const requestId = responseMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); if (!resolver) { @@ -5262,7 +5253,7 @@ describe('Error handling for missing resolvers', () => { // Manually trigger the error handling logic if (queuedMessage && queuedMessage.type === 'error') { - const errorMessage = queuedMessage.message as JSONRPCErrorResponse; + const errorMessage = queuedMessage.message as JSONRPCError; const reqId = errorMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(reqId); @@ -5275,7 +5266,7 @@ describe('Error handling for missing resolvers', () => { // Verify resolver was called with McpError expect(resolverMock).toHaveBeenCalledWith(expect.any(McpError)); - const calledError = resolverMock.mock.calls[0]![0]; + const calledError = resolverMock.mock.calls[0][0]; expect(calledError.code).toBe(ErrorCode.InvalidRequest); expect(calledError.message).toContain('Invalid request parameters'); @@ -5310,7 +5301,7 @@ describe('Error handling for missing resolvers', () => { // Manually trigger the error handling logic if (queuedMessage && queuedMessage.type === 'error') { const testProtocol = protocol as unknown as TestProtocol; - const errorMessage = queuedMessage.message as JSONRPCErrorResponse; + const errorMessage = queuedMessage.message as JSONRPCError; const requestId = errorMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); @@ -5357,7 +5348,7 @@ describe('Error handling for missing resolvers', () => { const queuedMessage = await taskMessageQueue.dequeue(task.taskId); if (queuedMessage && queuedMessage.type === 'error') { - const errorMessage = queuedMessage.message as JSONRPCErrorResponse; + const errorMessage = queuedMessage.message as JSONRPCError; const reqId = errorMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(reqId); @@ -5370,7 +5361,7 @@ describe('Error handling for missing resolvers', () => { // Verify resolver was called with McpError including data expect(resolverMock).toHaveBeenCalledWith(expect.any(McpError)); - const calledError = resolverMock.mock.calls[0]![0]; + const calledError = resolverMock.mock.calls[0][0]; expect(calledError.code).toBe(ErrorCode.InvalidParams); expect(calledError.message).toContain('Validation failed'); expect(calledError.data).toEqual({ field: 'userName', reason: 'required' }); @@ -5399,7 +5390,7 @@ describe('Error handling for missing resolvers', () => { const msg = await taskMessageQueue.dequeue(task.taskId); if (msg && msg.type === 'error') { const testProtocol = protocol as unknown as TestProtocol; - const errorMessage = msg.message as JSONRPCErrorResponse; + const errorMessage = msg.message as JSONRPCError; const requestId = errorMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); if (!resolver) { @@ -5466,7 +5457,7 @@ describe('Error handling for missing resolvers', () => { let msg; while ((msg = await taskMessageQueue.dequeue(task.taskId))) { if (msg.type === 'response') { - const responseMessage = msg.message as JSONRPCResultResponse; + const responseMessage = msg.message as JSONRPCResponse; const requestId = responseMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); if (resolver) { @@ -5474,7 +5465,7 @@ describe('Error handling for missing resolvers', () => { resolver(responseMessage); } } else if (msg.type === 'error') { - const errorMessage = msg.message as JSONRPCErrorResponse; + const errorMessage = msg.message as JSONRPCError; const requestId = errorMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); if (resolver) { @@ -5491,7 +5482,7 @@ describe('Error handling for missing resolvers', () => { expect(resolver3).toHaveBeenCalledWith(expect.objectContaining({ id: 3 })); // Verify error has correct properties - const error = resolver2.mock.calls[0]![0]; + const error = resolver2.mock.calls[0][0]; expect(error.code).toBe(ErrorCode.InvalidRequest); expect(error.message).toContain('Request failed'); @@ -5541,7 +5532,7 @@ describe('Error handling for missing resolvers', () => { let msg; while ((msg = await taskMessageQueue.dequeue(task.taskId))) { if (msg.type === 'response') { - const responseMessage = msg.message as JSONRPCResultResponse; + const responseMessage = msg.message as JSONRPCResponse; const requestId = responseMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); if (resolver) { @@ -5549,7 +5540,7 @@ describe('Error handling for missing resolvers', () => { resolver(responseMessage); } } else if (msg.type === 'error') { - const errorMessage = msg.message as JSONRPCErrorResponse; + const errorMessage = msg.message as JSONRPCError; const requestId = errorMessage.id as RequestId; const resolver = testProtocol._requestResolvers.get(requestId); if (resolver) { diff --git a/packages/core/test/shared/stdio.test.ts b/test/shared/stdio.test.ts similarity index 94% rename from packages/core/test/shared/stdio.test.ts rename to test/shared/stdio.test.ts index 455c8a6270..e8cbb5245a 100644 --- a/packages/core/test/shared/stdio.test.ts +++ b/test/shared/stdio.test.ts @@ -1,5 +1,5 @@ +import { JSONRPCMessage } from '../../src/types.js'; import { ReadBuffer } from '../../src/shared/stdio.js'; -import type { JSONRPCMessage } from '../../src/types/types.js'; const testMessage: JSONRPCMessage = { jsonrpc: '2.0', diff --git a/packages/core/test/shared/toolNameValidation.test.ts b/test/shared/toolNameValidation.test.ts similarity index 97% rename from packages/core/test/shared/toolNameValidation.test.ts rename to test/shared/toolNameValidation.test.ts index 131cbbc5f6..bd3c5ea4fb 100644 --- a/packages/core/test/shared/toolNameValidation.test.ts +++ b/test/shared/toolNameValidation.test.ts @@ -1,7 +1,5 @@ -import type { MockInstance } from 'vitest'; -import { vi } from 'vitest'; - -import { issueToolNameWarning, validateAndWarnToolName, validateToolName } from '../../src/shared/toolNameValidation.js'; +import { validateToolName, validateAndWarnToolName, issueToolNameWarning } from '../../src/shared/toolNameValidation.js'; +import { vi, MockInstance } from 'vitest'; // Spy on console.warn to capture output let warnSpy: MockInstance; diff --git a/packages/core/test/shared/uriTemplate.test.ts b/test/shared/uriTemplate.test.ts similarity index 100% rename from packages/core/test/shared/uriTemplate.test.ts rename to test/shared/uriTemplate.test.ts diff --git a/packages/core/test/spec.types.test.ts b/test/spec.types.test.ts similarity index 66% rename from packages/core/test/spec.types.test.ts rename to test/spec.types.test.ts index f7f99fe272..3b65d4d4f2 100644 --- a/packages/core/test/spec.types.test.ts +++ b/test/spec.types.test.ts @@ -5,15 +5,24 @@ * - Runtime checks to verify each Spec type has a static check * (note: a few don't have SDK types, see MISSING_SDK_TYPES below) */ +import * as SDKTypes from '../src/types.js'; +import * as SpecTypes from '../src/spec.types.js'; import fs from 'node:fs'; -import path from 'node:path'; - -import type * as SpecTypes from '../src/types/spec.types.js'; -import type * as SDKTypes from '../src/types/types.js'; /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-unsafe-function-type */ +// Removes index signatures added by ZodObject.passthrough(). +type RemovePassthrough = T extends object + ? T extends Array + ? Array> + : T extends Function + ? T + : { + [K in keyof T as string extends K ? never : K]: RemovePassthrough; + } + : T; + // Adds the `jsonrpc` property to a type, to match the on-wire format of notifications. type WithJSONRPC = T & { jsonrpc: '2.0' }; @@ -87,103 +96,112 @@ type FixSpecCreateMessageResult = T extends { content: infer C; role: infer R : T; const sdkTypeChecks = { - RequestParams: (sdk: SDKTypes.RequestParams, spec: SpecTypes.RequestParams) => { + RequestParams: (sdk: RemovePassthrough, spec: SpecTypes.RequestParams) => { sdk = spec; spec = sdk; }, - NotificationParams: (sdk: SDKTypes.NotificationParams, spec: SpecTypes.NotificationParams) => { + NotificationParams: (sdk: RemovePassthrough, spec: SpecTypes.NotificationParams) => { sdk = spec; spec = sdk; }, - CancelledNotificationParams: (sdk: SDKTypes.CancelledNotificationParams, spec: SpecTypes.CancelledNotificationParams) => { + CancelledNotificationParams: ( + sdk: RemovePassthrough, + spec: SpecTypes.CancelledNotificationParams + ) => { sdk = spec; spec = sdk; }, InitializeRequestParams: ( - sdk: SDKTypes.InitializeRequestParams, + sdk: RemovePassthrough, spec: FixSpecInitializeRequestParams ) => { sdk = spec; spec = sdk; }, - ProgressNotificationParams: (sdk: SDKTypes.ProgressNotificationParams, spec: SpecTypes.ProgressNotificationParams) => { + ProgressNotificationParams: ( + sdk: RemovePassthrough, + spec: SpecTypes.ProgressNotificationParams + ) => { sdk = spec; spec = sdk; }, - ResourceRequestParams: (sdk: SDKTypes.ResourceRequestParams, spec: SpecTypes.ResourceRequestParams) => { + ResourceRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.ResourceRequestParams) => { sdk = spec; spec = sdk; }, - ReadResourceRequestParams: (sdk: SDKTypes.ReadResourceRequestParams, spec: SpecTypes.ReadResourceRequestParams) => { + ReadResourceRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.ReadResourceRequestParams) => { sdk = spec; spec = sdk; }, - SubscribeRequestParams: (sdk: SDKTypes.SubscribeRequestParams, spec: SpecTypes.SubscribeRequestParams) => { + SubscribeRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.SubscribeRequestParams) => { sdk = spec; spec = sdk; }, - UnsubscribeRequestParams: (sdk: SDKTypes.UnsubscribeRequestParams, spec: SpecTypes.UnsubscribeRequestParams) => { + UnsubscribeRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.UnsubscribeRequestParams) => { sdk = spec; spec = sdk; }, ResourceUpdatedNotificationParams: ( - sdk: SDKTypes.ResourceUpdatedNotificationParams, + sdk: RemovePassthrough, spec: SpecTypes.ResourceUpdatedNotificationParams ) => { sdk = spec; spec = sdk; }, - GetPromptRequestParams: (sdk: SDKTypes.GetPromptRequestParams, spec: SpecTypes.GetPromptRequestParams) => { + GetPromptRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.GetPromptRequestParams) => { sdk = spec; spec = sdk; }, - CallToolRequestParams: (sdk: SDKTypes.CallToolRequestParams, spec: SpecTypes.CallToolRequestParams) => { + CallToolRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.CallToolRequestParams) => { sdk = spec; spec = sdk; }, - SetLevelRequestParams: (sdk: SDKTypes.SetLevelRequestParams, spec: SpecTypes.SetLevelRequestParams) => { + SetLevelRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.SetLevelRequestParams) => { sdk = spec; spec = sdk; }, LoggingMessageNotificationParams: ( - sdk: MakeUnknownsNotOptional, + sdk: MakeUnknownsNotOptional>, spec: SpecTypes.LoggingMessageNotificationParams ) => { sdk = spec; spec = sdk; }, - CreateMessageRequestParams: (sdk: SDKTypes.CreateMessageRequestParams, spec: SpecTypes.CreateMessageRequestParams) => { + CreateMessageRequestParams: ( + sdk: RemovePassthrough, + spec: SpecTypes.CreateMessageRequestParams + ) => { sdk = spec; spec = sdk; }, - CompleteRequestParams: (sdk: SDKTypes.CompleteRequestParams, spec: SpecTypes.CompleteRequestParams) => { + CompleteRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.CompleteRequestParams) => { sdk = spec; spec = sdk; }, - ElicitRequestParams: (sdk: SDKTypes.ElicitRequestParams, spec: SpecTypes.ElicitRequestParams) => { + ElicitRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.ElicitRequestParams) => { sdk = spec; spec = sdk; }, - ElicitRequestFormParams: (sdk: SDKTypes.ElicitRequestFormParams, spec: SpecTypes.ElicitRequestFormParams) => { + ElicitRequestFormParams: (sdk: RemovePassthrough, spec: SpecTypes.ElicitRequestFormParams) => { sdk = spec; spec = sdk; }, - ElicitRequestURLParams: (sdk: SDKTypes.ElicitRequestURLParams, spec: SpecTypes.ElicitRequestURLParams) => { + ElicitRequestURLParams: (sdk: RemovePassthrough, spec: SpecTypes.ElicitRequestURLParams) => { sdk = spec; spec = sdk; }, ElicitationCompleteNotification: ( - sdk: WithJSONRPC, + sdk: RemovePassthrough>, spec: SpecTypes.ElicitationCompleteNotification ) => { sdk = spec; spec = sdk; }, - PaginatedRequestParams: (sdk: SDKTypes.PaginatedRequestParams, spec: SpecTypes.PaginatedRequestParams) => { + PaginatedRequestParams: (sdk: RemovePassthrough, spec: SpecTypes.PaginatedRequestParams) => { sdk = spec; spec = sdk; }, - CancelledNotification: (sdk: WithJSONRPC, spec: SpecTypes.CancelledNotification) => { + CancelledNotification: (sdk: RemovePassthrough>, spec: SpecTypes.CancelledNotification) => { sdk = spec; spec = sdk; }, @@ -195,19 +213,19 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ProgressNotification: (sdk: WithJSONRPC, spec: SpecTypes.ProgressNotification) => { + ProgressNotification: (sdk: RemovePassthrough>, spec: SpecTypes.ProgressNotification) => { sdk = spec; spec = sdk; }, - SubscribeRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.SubscribeRequest) => { + SubscribeRequest: (sdk: RemovePassthrough>, spec: SpecTypes.SubscribeRequest) => { sdk = spec; spec = sdk; }, - UnsubscribeRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.UnsubscribeRequest) => { + UnsubscribeRequest: (sdk: RemovePassthrough>, spec: SpecTypes.UnsubscribeRequest) => { sdk = spec; spec = sdk; }, - PaginatedRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.PaginatedRequest) => { + PaginatedRequest: (sdk: RemovePassthrough>, spec: SpecTypes.PaginatedRequest) => { sdk = spec; spec = sdk; }, @@ -215,7 +233,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ListRootsRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListRootsRequest) => { + ListRootsRequest: (sdk: RemovePassthrough>, spec: SpecTypes.ListRootsRequest) => { sdk = spec; spec = sdk; }, @@ -227,7 +245,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ElicitRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ElicitRequest) => { + ElicitRequest: (sdk: RemovePassthrough>, spec: SpecTypes.ElicitRequest) => { sdk = spec; spec = sdk; }, @@ -235,7 +253,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - CompleteRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.CompleteRequest) => { + CompleteRequest: (sdk: RemovePassthrough>, spec: SpecTypes.CompleteRequest) => { sdk = spec; spec = sdk; }, @@ -287,7 +305,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ClientNotification: (sdk: WithJSONRPC, spec: SpecTypes.ClientNotification) => { + ClientNotification: (sdk: RemovePassthrough>, spec: SpecTypes.ClientNotification) => { sdk = spec; spec = sdk; }, @@ -311,7 +329,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ListToolsRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListToolsRequest) => { + ListToolsRequest: (sdk: RemovePassthrough>, spec: SpecTypes.ListToolsRequest) => { sdk = spec; spec = sdk; }, @@ -323,60 +341,75 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - CallToolRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.CallToolRequest) => { + CallToolRequest: (sdk: RemovePassthrough>, spec: SpecTypes.CallToolRequest) => { sdk = spec; spec = sdk; }, - ToolListChangedNotification: (sdk: WithJSONRPC, spec: SpecTypes.ToolListChangedNotification) => { + ToolListChangedNotification: ( + sdk: RemovePassthrough>, + spec: SpecTypes.ToolListChangedNotification + ) => { sdk = spec; spec = sdk; }, ResourceListChangedNotification: ( - sdk: WithJSONRPC, + sdk: RemovePassthrough>, spec: SpecTypes.ResourceListChangedNotification ) => { sdk = spec; spec = sdk; }, PromptListChangedNotification: ( - sdk: WithJSONRPC, + sdk: RemovePassthrough>, spec: SpecTypes.PromptListChangedNotification ) => { sdk = spec; spec = sdk; }, RootsListChangedNotification: ( - sdk: WithJSONRPC, + sdk: RemovePassthrough>, spec: SpecTypes.RootsListChangedNotification ) => { sdk = spec; spec = sdk; }, - ResourceUpdatedNotification: (sdk: WithJSONRPC, spec: SpecTypes.ResourceUpdatedNotification) => { + ResourceUpdatedNotification: ( + sdk: RemovePassthrough>, + spec: SpecTypes.ResourceUpdatedNotification + ) => { sdk = spec; spec = sdk; }, - SamplingMessage: (sdk: SDKTypes.SamplingMessage, spec: SpecTypes.SamplingMessage) => { + SamplingMessage: (sdk: RemovePassthrough, spec: SpecTypes.SamplingMessage) => { sdk = spec; spec = sdk; }, - CreateMessageResult: (sdk: SDKTypes.CreateMessageResult, spec: FixSpecCreateMessageResult) => { + CreateMessageResult: ( + sdk: RemovePassthrough, + spec: FixSpecCreateMessageResult + ) => { sdk = spec; spec = sdk; }, - SetLevelRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.SetLevelRequest) => { + SetLevelRequest: (sdk: RemovePassthrough>, spec: SpecTypes.SetLevelRequest) => { sdk = spec; spec = sdk; }, - PingRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.PingRequest) => { + PingRequest: (sdk: RemovePassthrough>, spec: SpecTypes.PingRequest) => { sdk = spec; spec = sdk; }, - InitializedNotification: (sdk: WithJSONRPC, spec: SpecTypes.InitializedNotification) => { + InitializedNotification: ( + sdk: RemovePassthrough>, + spec: SpecTypes.InitializedNotification + ) => { sdk = spec; spec = sdk; }, - ListResourcesRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListResourcesRequest) => { + ListResourcesRequest: ( + sdk: RemovePassthrough>, + spec: SpecTypes.ListResourcesRequest + ) => { sdk = spec; spec = sdk; }, @@ -385,7 +418,7 @@ const sdkTypeChecks = { spec = sdk; }, ListResourceTemplatesRequest: ( - sdk: WithJSONRPCRequest, + sdk: RemovePassthrough>, spec: SpecTypes.ListResourceTemplatesRequest ) => { sdk = spec; @@ -395,7 +428,10 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ReadResourceRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ReadResourceRequest) => { + ReadResourceRequest: ( + sdk: RemovePassthrough>, + spec: SpecTypes.ReadResourceRequest + ) => { sdk = spec; spec = sdk; }, @@ -419,7 +455,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ResourceTemplate: (sdk: SDKTypes.ResourceTemplateType, spec: SpecTypes.ResourceTemplate) => { + ResourceTemplate: (sdk: SDKTypes.ResourceTemplate, spec: SpecTypes.ResourceTemplate) => { sdk = spec; spec = sdk; }, @@ -431,7 +467,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ListPromptsRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListPromptsRequest) => { + ListPromptsRequest: (sdk: RemovePassthrough>, spec: SpecTypes.ListPromptsRequest) => { sdk = spec; spec = sdk; }, @@ -439,7 +475,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - GetPromptRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.GetPromptRequest) => { + GetPromptRequest: (sdk: RemovePassthrough>, spec: SpecTypes.GetPromptRequest) => { sdk = spec; spec = sdk; }, @@ -523,11 +559,7 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - JSONRPCErrorResponse: (sdk: SDKTypes.JSONRPCErrorResponse, spec: SpecTypes.JSONRPCErrorResponse) => { - sdk = spec; - spec = sdk; - }, - JSONRPCResultResponse: (sdk: SDKTypes.JSONRPCResultResponse, spec: SpecTypes.JSONRPCResultResponse) => { + JSONRPCError: (sdk: SDKTypes.JSONRPCError, spec: SpecTypes.JSONRPCError) => { sdk = spec; spec = sdk; }, @@ -535,12 +567,15 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - CreateMessageRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.CreateMessageRequest) => { + CreateMessageRequest: ( + sdk: RemovePassthrough>, + spec: SpecTypes.CreateMessageRequest + ) => { sdk = spec; spec = sdk; }, InitializeRequest: ( - sdk: WithJSONRPCRequest, + sdk: RemovePassthrough>, spec: FixSpecInitializeRequest ) => { sdk = spec; @@ -558,22 +593,28 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ClientRequest: (sdk: WithJSONRPCRequest, spec: FixSpecClientRequest) => { + ClientRequest: ( + sdk: RemovePassthrough>, + spec: FixSpecClientRequest + ) => { sdk = spec; spec = sdk; }, - ServerRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ServerRequest) => { + ServerRequest: (sdk: RemovePassthrough>, spec: SpecTypes.ServerRequest) => { sdk = spec; spec = sdk; }, LoggingMessageNotification: ( - sdk: MakeUnknownsNotOptional>, + sdk: RemovePassthrough>>, spec: SpecTypes.LoggingMessageNotification ) => { sdk = spec; spec = sdk; }, - ServerNotification: (sdk: MakeUnknownsNotOptional>, spec: SpecTypes.ServerNotification) => { + ServerNotification: ( + sdk: MakeUnknownsNotOptional>>, + spec: SpecTypes.ServerNotification + ) => { sdk = spec; spec = sdk; }, @@ -601,15 +642,18 @@ const sdkTypeChecks = { sdk = spec; spec = sdk; }, - ToolUseContent: (sdk: SDKTypes.ToolUseContent, spec: SpecTypes.ToolUseContent) => { + ToolUseContent: (sdk: RemovePassthrough, spec: SpecTypes.ToolUseContent) => { sdk = spec; spec = sdk; }, - ToolResultContent: (sdk: SDKTypes.ToolResultContent, spec: SpecTypes.ToolResultContent) => { + ToolResultContent: (sdk: RemovePassthrough, spec: SpecTypes.ToolResultContent) => { sdk = spec; spec = sdk; }, - SamplingMessageContentBlock: (sdk: SDKTypes.SamplingMessageContentBlock, spec: SpecTypes.SamplingMessageContentBlock) => { + SamplingMessageContentBlock: ( + sdk: RemovePassthrough, + spec: SpecTypes.SamplingMessageContentBlock + ) => { sdk = spec; spec = sdk; }, @@ -620,80 +664,12 @@ const sdkTypeChecks = { Role: (sdk: SDKTypes.Role, spec: SpecTypes.Role) => { sdk = spec; spec = sdk; - }, - TaskAugmentedRequestParams: (sdk: SDKTypes.TaskAugmentedRequestParams, spec: SpecTypes.TaskAugmentedRequestParams) => { - sdk = spec; - spec = sdk; - }, - ToolExecution: (sdk: SDKTypes.ToolExecution, spec: SpecTypes.ToolExecution) => { - sdk = spec; - spec = sdk; - }, - TaskStatus: (sdk: SDKTypes.TaskStatus, spec: SpecTypes.TaskStatus) => { - sdk = spec; - spec = sdk; - }, - TaskMetadata: (sdk: SDKTypes.TaskMetadata, spec: SpecTypes.TaskMetadata) => { - sdk = spec; - spec = sdk; - }, - RelatedTaskMetadata: (sdk: SDKTypes.RelatedTaskMetadata, spec: SpecTypes.RelatedTaskMetadata) => { - sdk = spec; - spec = sdk; - }, - Task: (sdk: SDKTypes.Task, spec: SpecTypes.Task) => { - sdk = spec; - spec = sdk; - }, - CreateTaskResult: (sdk: SDKTypes.CreateTaskResult, spec: SpecTypes.CreateTaskResult) => { - sdk = spec; - spec = sdk; - }, - GetTaskResult: (sdk: SDKTypes.GetTaskResult, spec: SpecTypes.GetTaskResult) => { - sdk = spec; - spec = sdk; - }, - GetTaskPayloadRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.GetTaskPayloadRequest) => { - sdk = spec; - spec = sdk; - }, - ListTasksRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.ListTasksRequest) => { - sdk = spec; - spec = sdk; - }, - ListTasksResult: (sdk: SDKTypes.ListTasksResult, spec: SpecTypes.ListTasksResult) => { - sdk = spec; - spec = sdk; - }, - CancelTaskRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.CancelTaskRequest) => { - sdk = spec; - spec = sdk; - }, - CancelTaskResult: (sdk: SDKTypes.CancelTaskResult, spec: SpecTypes.CancelTaskResult) => { - sdk = spec; - spec = sdk; - }, - GetTaskRequest: (sdk: WithJSONRPCRequest, spec: SpecTypes.GetTaskRequest) => { - sdk = spec; - spec = sdk; - }, - GetTaskPayloadResult: (sdk: SDKTypes.GetTaskPayloadResult, spec: SpecTypes.GetTaskPayloadResult) => { - sdk = spec; - spec = sdk; - }, - TaskStatusNotificationParams: (sdk: SDKTypes.TaskStatusNotificationParams, spec: SpecTypes.TaskStatusNotificationParams) => { - sdk = spec; - spec = sdk; - }, - TaskStatusNotification: (sdk: WithJSONRPC, spec: SpecTypes.TaskStatusNotification) => { - sdk = spec; - spec = sdk; } }; // This file is .gitignore'd, and fetched by `npm run fetch:spec-types` (called by `npm run test`) -const SPEC_TYPES_FILE = path.resolve(__dirname, '../src/types/spec.types.ts'); -const SDK_TYPES_FILE = path.resolve(__dirname, '../src/types/types.ts'); +const SPEC_TYPES_FILE = 'src/spec.types.ts'; +const SDK_TYPES_FILE = 'src/types.ts'; const MISSING_SDK_TYPES = [ // These are inlined in the SDK: @@ -702,8 +678,7 @@ const MISSING_SDK_TYPES = [ ]; function extractExportedTypes(source: string): string[] { - const matches = [...source.matchAll(/export\s+(?:interface|class|type)\s+(\w+)\b/g)]; - return matches.map(m => m[1]!); + return [...source.matchAll(/export\s+(?:interface|class|type)\s+(\w+)\b/g)].map(m => m[1]); } describe('Spec Types', () => { @@ -714,7 +689,7 @@ describe('Spec Types', () => { it('should define some expected types', () => { expect(specTypes).toContain('JSONRPCNotification'); expect(specTypes).toContain('ElicitResult'); - expect(specTypes).toHaveLength(145); + expect(specTypes).toHaveLength(127); }); it('should have up to date list of missing sdk types', () => { diff --git a/packages/core/test/types.capabilities.test.ts b/test/types.capabilities.test.ts similarity index 99% rename from packages/core/test/types.capabilities.test.ts rename to test/types.capabilities.test.ts index ed414d2db0..6d7c39dc76 100644 --- a/packages/core/test/types.capabilities.test.ts +++ b/test/types.capabilities.test.ts @@ -1,4 +1,4 @@ -import { ClientCapabilitiesSchema, InitializeRequestParamsSchema } from '../src/types/types.js'; +import { ClientCapabilitiesSchema, InitializeRequestParamsSchema } from '../src/types.js'; describe('ClientCapabilitiesSchema backwards compatibility', () => { describe('ElicitationCapabilitySchema preprocessing', () => { diff --git a/packages/core/test/types.test.ts b/test/types.test.ts similarity index 98% rename from packages/core/test/types.test.ts rename to test/types.test.ts index c14fe40603..64bb78a21d 100644 --- a/packages/core/test/types.test.ts +++ b/test/types.test.ts @@ -1,21 +1,21 @@ import { + LATEST_PROTOCOL_VERSION, + SUPPORTED_PROTOCOL_VERSIONS, + ResourceLinkSchema, + ContentBlockSchema, + PromptMessageSchema, CallToolResultSchema, - ClientCapabilitiesSchema, CompleteRequestSchema, - ContentBlockSchema, + ToolSchema, + ToolUseContentSchema, + ToolResultContentSchema, + ToolChoiceSchema, + SamplingMessageSchema, CreateMessageRequestSchema, CreateMessageResultSchema, CreateMessageResultWithToolsSchema, - LATEST_PROTOCOL_VERSION, - PromptMessageSchema, - ResourceLinkSchema, - SamplingMessageSchema, - SUPPORTED_PROTOCOL_VERSIONS, - ToolChoiceSchema, - ToolResultContentSchema, - ToolSchema, - ToolUseContentSchema -} from '../src/types/types.js'; + ClientCapabilitiesSchema +} from '../src/types.js'; describe('Types', () => { test('should have correct latest protocol version', () => { @@ -178,7 +178,7 @@ describe('Types', () => { annotations: { audience: ['user'], priority: 0.5, - lastModified: mockDate + lastModified: new Date().toISOString() } }; @@ -273,9 +273,9 @@ describe('Types', () => { expect(result.success).toBe(true); if (result.success) { expect(result.data.content).toHaveLength(3); - expect(result.data.content[0]?.type).toBe('text'); - expect(result.data.content[1]?.type).toBe('resource_link'); - expect(result.data.content[2]?.type).toBe('resource_link'); + expect(result.data.content[0].type).toBe('text'); + expect(result.data.content[1].type).toBe('resource_link'); + expect(result.data.content[2].type).toBe('resource_link'); } }); @@ -899,8 +899,8 @@ describe('Types', () => { expect(Array.isArray(content)).toBe(true); if (Array.isArray(content)) { expect(content).toHaveLength(2); - expect(content[0]?.type).toBe('text'); - expect(content[1]?.type).toBe('tool_use'); + expect(content[0].type).toBe('text'); + expect(content[1].type).toBe('tool_use'); } } diff --git a/packages/core/test/validation/validation.test.ts b/test/validation/validation.test.ts similarity index 100% rename from packages/core/test/validation/validation.test.ts rename to test/validation/validation.test.ts diff --git a/tsconfig.cjs.json b/tsconfig.cjs.json new file mode 100644 index 0000000000..4b712da77b --- /dev/null +++ b/tsconfig.cjs.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "commonjs", + "moduleResolution": "node", + "outDir": "./dist/cjs" + }, + "include": ["src/**/*"], + "exclude": ["**/*.test.ts", "src/__mocks__/**/*", "src/__fixtures__/**/*"] +} diff --git a/common/tsconfig/tsconfig.json b/tsconfig.json similarity index 51% rename from common/tsconfig/tsconfig.json rename to tsconfig.json index 6db7d705bf..c7346e4fee 100644 --- a/common/tsconfig/tsconfig.json +++ b/tsconfig.json @@ -1,24 +1,14 @@ { "compilerOptions": { - "target": "esnext", - "lib": ["esnext"], - "module": "NodeNext", - "moduleResolution": "NodeNext", - "noFallthroughCasesInSwitch": true, - "noUncheckedIndexedAccess": true, - "noImplicitOverride": true, - "experimentalDecorators": true, - "emitDecoratorMetadata": true, - "libReplacement": false, - "noImplicitReturns": true, - "incremental": true, + "target": "es2018", + "module": "Node16", + "moduleResolution": "Node16", "declaration": true, "declarationMap": true, "sourceMap": true, "outDir": "./dist", "strict": true, "esModuleInterop": true, - "allowSyntheticDefaultImports": true, "forceConsistentCasingInFileNames": true, "resolveJsonModule": true, "isolatedModules": true, @@ -27,5 +17,7 @@ "pkce-challenge": ["./node_modules/pkce-challenge/dist/index.node"] }, "types": ["node", "vitest/globals"] - } + }, + "include": ["src/**/*", "test/**/*"], + "exclude": ["node_modules", "dist"] } diff --git a/tsconfig.prod.json b/tsconfig.prod.json new file mode 100644 index 0000000000..82710bd6ab --- /dev/null +++ b/tsconfig.prod.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "./dist/esm" + }, + "include": ["src/**/*"], + "exclude": ["**/*.test.ts", "src/__mocks__/**/*", "src/__fixtures__/**/*"] +} diff --git a/vitest.config.ts b/vitest.config.ts new file mode 100644 index 0000000000..f283689f15 --- /dev/null +++ b/vitest.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + globals: true, + environment: 'node', + setupFiles: ['./vitest.setup.ts'], + include: ['test/**/*.test.ts'] + } +}); diff --git a/packages/client/vitest.setup.js b/vitest.setup.ts similarity index 70% rename from packages/client/vitest.setup.js rename to vitest.setup.ts index d6e9c6678c..820dcbd896 100644 --- a/packages/client/vitest.setup.js +++ b/vitest.setup.ts @@ -3,5 +3,6 @@ import { webcrypto } from 'node:crypto'; // Polyfill globalThis.crypto for environments (e.g. Node 18) where it is not defined. // This is necessary for the tests to run in Node 18, specifically for the jose library, which relies on the globalThis.crypto object. if (typeof globalThis.crypto === 'undefined') { - globalThis.crypto = webcrypto; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (globalThis as any).crypto = webcrypto as unknown as Crypto; } diff --git a/vitest.workspace.js b/vitest.workspace.js deleted file mode 100644 index b09f1f1fd4..0000000000 --- a/vitest.workspace.js +++ /dev/null @@ -1,3 +0,0 @@ -import { defineWorkspace } from 'vitest/config'; - -export default defineWorkspace(['packages/**/vitest.config.js']);