@modelcontextprotocol/server 2.0.0-alpha.2 → 2.0.0-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -3
- package/dist/{src-IKPjmxu7.mjs → ajvProvider-BQMcjynJ.mjs} +4147 -6749
- package/dist/ajvProvider-BQMcjynJ.mjs.map +1 -0
- package/dist/ajvProvider-Dzgk80kq.d.mts +1030 -0
- package/dist/ajvProvider-Dzgk80kq.d.mts.map +1 -0
- package/dist/cfWorkerProvider-BDC2rVl3.mjs +970 -0
- package/dist/cfWorkerProvider-BDC2rVl3.mjs.map +1 -0
- package/dist/cfWorkerProvider-DmvjVsvQ.d.mts +59 -0
- package/dist/cfWorkerProvider-DmvjVsvQ.d.mts.map +1 -0
- package/dist/chunk-BRhqBsOc.mjs +42 -0
- package/dist/{index-Bhfkexnj.d.mts → createMcpHandler-Du3hjXvf.d.mts} +4702 -2249
- package/dist/createMcpHandler-Du3hjXvf.d.mts.map +1 -0
- package/dist/index.d.mts +177 -833
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1349 -2067
- package/dist/index.mjs.map +1 -1
- package/dist/mcp-JttQJlI9.mjs +9998 -0
- package/dist/mcp-JttQJlI9.mjs.map +1 -0
- package/dist/shimsNode.d.mts +1 -1
- package/dist/shimsNode.mjs +1 -1
- package/dist/shimsWorkerd.d.mts +1 -1
- package/dist/shimsWorkerd.mjs +1 -1
- package/dist/shimsWorkerd.mjs.map +1 -1
- package/dist/stdio.d.mts +107 -0
- package/dist/stdio.d.mts.map +1 -0
- package/dist/stdio.mjs +561 -0
- package/dist/stdio.mjs.map +1 -0
- package/dist/types-DBYdVs-n.d.mts +1099 -0
- package/dist/types-DBYdVs-n.d.mts.map +1 -0
- package/dist/validators/ajv.d.mts +2 -0
- package/dist/validators/ajv.mjs +4 -0
- package/dist/validators/cfWorker.d.mts +2 -0
- package/dist/validators/cfWorker.mjs +3 -0
- package/package.json +33 -17
- package/dist/index-Bhfkexnj.d.mts.map +0 -1
- package/dist/src-IKPjmxu7.mjs.map +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
import {
|
|
1
|
+
import { $ as RequestOptions, $a as OAuthClientMetadata, $i as Task, $n as InputRequiredResult, $r as ProgressNotification, $t as CallToolResult, A as ResourceMetadata, Aa as LATEST_PROTOCOL_VERSION, Ai as Role, An as ElicitationCompleteNotification, Ar as LoggingLevel, At as InputResponseView, B as deserializeMessage, Ba as checkResourceAllowed, Bi as SetLevelRequest, Bn as GetTaskRequest, Br as MultiSelectEnumSchema, Bt as InboundLegacyRoute, C as PromptCallback, Ca as CLIENT_CAPABILITIES_META_KEY, Ci as ResourceRequestParams, Cn as DiscoverRequest, Cr as ListResourcesResult, Ct as MissingRequiredClientCapabilityError, D as RegisteredResource, Da as INVALID_PARAMS, Di as ResourceUpdatedNotificationParams, Dn as ElicitRequestParams, Dr as ListTasksResult, Dt as UrlElicitationRequiredError, E as RegisteredPrompt, Ea as INTERNAL_ERROR, Ei as ResourceUpdatedNotification, En as ElicitRequestFormParams, Er as ListTasksRequest, Et as UnsupportedProtocolVersionError, F as InMemoryTransport, Fa as RELATED_TASK_META_KEY, Fi as SamplingMessageContentBlock, Fn as GetPromptRequest, Fr as MetaObject, Ft as StandardSchemaV1Sync, G as getDisplayName, Ga as SdkHttpErrorData, Gi as SubscribeRequestParams, Gn as ImageContent, Gr as NumberSchema, Gt as Annotations, H as CacheHint, Ha as SdkError, Hi as SingleSelectEnumSchema, Hn as HandlerResultTypeMap, Hr as NotificationMethod, Ht as InboundModernRoute, I as UriTemplate, Ia as SUBSCRIPTION_ID_META_KEY, Ii as ServerCapabilities, In as GetPromptRequestParams, Ir as MethodNotFoundError, It as StandardSchemaWithJSON, J as DEFAULT_REQUEST_TIMEOUT_MSEC, Ja as AuthorizationServerMetadata, Ji as SubscriptionsAcknowledgedNotificationParams, Jn as InitializeRequestParams, Jr as PaginatedResult, Jt as BaseMetadata, K as BaseContext, Ka as OAuthError, Ki as SubscriptionFilter, Kn as Implementation, Kr as PaginatedRequest, Kt as AudioContent, L as Variables, La as SUPPORTED_PROTOCOL_VERSIONS, Li as ServerNotification, Ln as GetPromptResult, Lr as MissingRequiredClientCapabilityErrorData, Lt as InboundClassificationOutcome, M as ToolCallback, Ma as METHOD_NOT_FOUND, Mi as RootsListChangedNotification, Mn as EmbeddedResource, Mr as LoggingMessageNotificationParams, Mt as inputRequired, N as Server, Na as PARSE_ERROR, Ni as SamplingContent, Nn as EmptyResult, Nr as MessageClassification, Nt as inputResponse, O as RegisteredResourceTemplate, Oa as INVALID_REQUEST, Oi as Result, On as ElicitRequestURLParams, Or as ListToolsRequest, Ot as ProtocolErrorCode, P as ServerOptions, Pa as PROTOCOL_VERSION_META_KEY, Pi as SamplingMessage, Pn as EnumSchema, Pr as MessageExtraInfo, Pt as StandardSchemaV1, Q as RequestHandlerSchemas, Qa as OAuthClientInformationMixed, Qi as SubscriptionsListenResultMeta, Qn as InputRequests, Qr as Progress, Qt as CallToolRequestParams, R as ReadBuffer, Ra as TRACEPARENT_META_KEY, Ri as ServerRequest, Rn as GetTaskPayloadRequest, Rr as ModelHint, Rt as InboundHttpRequest, S as McpServer, Sa as BAGGAGE_META_KEY, Si as ResourceListChangedNotification, Sn as Cursor, Sr as ListResourcesRequest, St as parseJSONRPCMessage, T as ReadResourceTemplateCallback, Ta as DEFAULT_NEGOTIATED_PROTOCOL_VERSION, Ti as ResourceTemplateType, Tn as ElicitRequest, Tr as ListRootsResult, Tt as ResourceNotFoundError, U as CacheScope, Ua as SdkErrorCode, Ui as StringSchema, Un as Icon, Ur as NotificationParams, Ut as InboundValidationRung, V as serializeMessage, Va as resourceUrlFromServerUrl, Vi as SetLevelRequestParams, Vn as GetTaskResult, Vr as Notification, Vt as InboundLegacyRouteReason, W as ProtocolEra, Wa as SdkHttpError, Wi as SubscribeRequest, Wn as Icons, Wr as NotificationTypeMap, Wt as classifyInboundRequest, X as ProgressCallback, Xa as OAuthClientInformation, Xi as SubscriptionsListenRequestParams, Xn as InitializedNotification, Xr as PingRequest, Xt as BooleanSchema, Y as NotificationOptions, Ya as IdJagTokenExchangeResponse, Yi as SubscriptionsListenRequest, Yn as InitializeResult, Yr as ParseError, Yt as BlobResourceContents, Z as ProtocolOptions, Za as OAuthClientInformationFull, Zi as SubscriptionsListenResult, Zn as InputRequest, Zr as PrimitiveSchemaDefinition, Zt as CallToolRequest, _ as PerRequestResponseMode, _a as UnsubscribeRequest, _i as RequestParams, _n as CreateMessageRequestParamsBase, _r as ListChangedOptions, _t as isJSONRPCNotification, a as McpRequestContext, aa as TaskStatusNotificationParams, ai as PromptMessage, an as ClientNotification, ao as OAuthTokens, ar as JSONArray, at as createFetchWithInit, b as CompleteResourceTemplateCallback, ba as UntitledMultiSelectEnumSchema, bi as ResourceContents, bn as CreateMessageResultWithTools, br as ListResourceTemplatesRequest, bt as isJSONRPCResultResponse, c as isLegacyRequest, ca as TitledMultiSelectEnumSchema, ci as ReadResourceRequestParams, cn as CompatibilityCallToolResult, co as StoredOAuthClientInformation, cr as JSONRPCMessage, ct as isSpecType, d as ServerEvent, da as ToolAnnotations, di as Request$1, dn as CompleteRequestPrompt, dr as JSONRPCResponse, dt as assertCompleteRequestResourceTemplate, ea as TaskAugmentedRequestParams, ei as ProgressNotificationParams, en as CancelTaskRequest, eo as OAuthClientRegistrationError, er as InputResponse, et as RequestStateAccessor, f as ServerEventBus, fa as ToolChoice, fi as RequestId, fn as CompleteRequestResourceTemplate, fr as JSONRPCResultResponse, ft as isCallToolResult, g as PerRequestMessageExtra, ga as ToolUseContent, gi as RequestMethod, gn as CreateMessageRequestParams, gr as ListChangedHandlers, gt as isJSONRPCErrorResponse, h as PerRequestHTTPServerTransportOptions, ha as ToolResultContent, hi as RequestMetaObject, hn as CreateMessageRequest, hr as ListChangedCallback, ht as isInputRequiredResult, i as McpHttpHandler, ia as TaskStatusNotification, ii as PromptListChangedNotification, in as ClientCapabilities, io as OAuthTokenRevocationRequest, ir as InvalidRequestError, it as TransportSendOptions, j as ResourceTemplate, ja as LOG_LEVEL_META_KEY, ji as Root, jn as ElicitationCompleteNotificationParams, jr as LoggingMessageNotification, jt as acceptedContent, k as RegisteredTool, ka as JSONRPC_VERSION, ki as ResultTypeMap, kn as ElicitResult, kr as ListToolsResult, kt as InputRequiredSpec, l as legacyStatelessFallback, la as TitledSingleSelectEnumSchema, li as ReadResourceResult, ln as CompleteRequest, lo as StoredOAuthTokens, lr as JSONRPCNotification, lt as specTypeSchemas, m as PerRequestHTTPServerTransport, ma as ToolListChangedNotification, mi as RequestMetaEnvelope, mn as ContentBlock, mr as LegacyTitledEnumSchema, mt as isInitializedNotification, n as LegacyHttpHandler, na as TaskMetadata, ni as Prompt, nn as CancelledNotification, no as OAuthMetadata, nr as InternalError, nt as FetchLike, o as McpServerFactory, oa as TextContent, oi as PromptReference, on as ClientRequest, oo as OpenIdProviderDiscoveryMetadata, or as JSONObject, ot as SpecTypeName, p as ServerNotifier, pa as ToolExecution, pi as RequestMeta, pn as CompleteResult, pr as JSONValue, pt as isInitializeRequest, q as ClientContext, qa as OAuthErrorCode, qi as SubscriptionsAcknowledgedNotification, qn as InitializeRequest, qr as PaginatedRequestParams, qt as AuthInfo, r as McpHandlerRequestOptions, ra as TaskStatus, ri as PromptArgument, rn as CancelledNotificationParams, ro as OAuthProtectedResourceMetadata, rr as InvalidParamsError, rt as Transport, s as createMcpHandler, sa as TextResourceContents, si as ReadResourceRequest, sn as ClientResult, so as OpenIdProviderMetadata, sr as JSONRPCErrorResponse, st as SpecTypes, t as CreateMcpHandlerOptions, ta as TaskCreationParams, ti as ProgressToken, tn as CancelTaskResult, to as OAuthErrorResponse, tr as InputResponses, tt as ServerContext, u as InMemoryServerEventBus, ua as Tool, ui as RelatedTaskMetadata, un as CompleteRequestParams, ur as JSONRPCRequest, ut as assertCompleteRequestPrompt, v as AnyToolHandler, va as UnsubscribeRequestParams, vi as RequestTypeMap, vn as CreateMessageRequestParamsWithTools, vr as ListPromptsRequest, vt as isJSONRPCRequest, w as ReadResourceCallback, wa as CLIENT_INFO_META_KEY, wi as ResourceTemplateReference, wn as DiscoverResult, wr as ListRootsRequest, wt as ProtocolError, x as ListResourcesCallback, xa as UntitledSingleSelectEnumSchema, xi as ResourceLink, xn as CreateTaskResult, xr as ListResourceTemplatesResult, xt as isTaskAugmentedRequestParams, y as BaseToolCallback, ya as UnsupportedProtocolVersionErrorData, yi as Resource, yn as CreateMessageResult, yr as ListPromptsResult, yt as isJSONRPCResponse, z as STDIO_DEFAULT_MAX_BUFFER_SIZE, za as TRACESTATE_META_KEY, zi as ServerResult, zn as GetTaskPayloadResult, zr as ModelPreferences, zt as InboundLadderRejection } from "./createMcpHandler-Du3hjXvf.mjs";
|
|
2
|
+
import { t as AjvJsonSchemaValidator } from "./ajvProvider-Dzgk80kq.mjs";
|
|
3
|
+
import { i as jsonSchemaValidator, n as JsonSchemaValidator, r as JsonSchemaValidatorResult, t as JsonSchemaType } from "./types-DBYdVs-n.mjs";
|
|
4
|
+
import { n as CfWorkerSchemaDraft, t as CfWorkerJsonSchemaValidator } from "./cfWorkerProvider-DmvjVsvQ.mjs";
|
|
3
5
|
|
|
4
6
|
//#region src/server/completable.d.ts
|
|
5
7
|
declare const COMPLETABLE_SYMBOL: unique symbol;
|
|
6
|
-
type CompleteCallback<T extends
|
|
8
|
+
type CompleteCallback<T extends StandardSchemaV1 = StandardSchemaV1> = (value: StandardSchemaV1.InferInput<T>, context?: {
|
|
7
9
|
arguments?: Record<string, string>;
|
|
8
|
-
}) =>
|
|
9
|
-
type CompletableMeta<T extends
|
|
10
|
+
}) => StandardSchemaV1.InferInput<T>[] | Promise<StandardSchemaV1.InferInput<T>[]>;
|
|
11
|
+
type CompletableMeta<T extends StandardSchemaV1 = StandardSchemaV1> = {
|
|
10
12
|
complete: CompleteCallback<T>;
|
|
11
13
|
};
|
|
12
|
-
type CompletableSchema<T extends
|
|
14
|
+
type CompletableSchema<T extends StandardSchemaV1> = T & {
|
|
13
15
|
[COMPLETABLE_SYMBOL]: CompletableMeta<T>;
|
|
14
16
|
};
|
|
15
17
|
/**
|
|
@@ -43,877 +45,204 @@ type CompletableSchema<T extends StandardSchemaWithJSON> = T & {
|
|
|
43
45
|
*
|
|
44
46
|
* @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions
|
|
45
47
|
*/
|
|
46
|
-
declare function completable<T extends
|
|
48
|
+
declare function completable<T extends StandardSchemaV1>(schema: T, complete: CompleteCallback<T>): CompletableSchema<T>;
|
|
47
49
|
/**
|
|
48
50
|
* Checks if a schema is completable (has completion metadata).
|
|
49
51
|
*/
|
|
50
|
-
declare function isCompletable(schema: unknown): schema is CompletableSchema<
|
|
52
|
+
declare function isCompletable(schema: unknown): schema is CompletableSchema<StandardSchemaV1>;
|
|
51
53
|
//#endregion
|
|
52
|
-
//#region src/
|
|
54
|
+
//#region src/server/middleware/hostHeaderValidation.d.ts
|
|
55
|
+
type HostHeaderValidationResult = {
|
|
56
|
+
ok: true;
|
|
57
|
+
hostname: string;
|
|
58
|
+
} | {
|
|
59
|
+
ok: false;
|
|
60
|
+
errorCode: 'missing_host' | 'invalid_host_header' | 'invalid_host';
|
|
61
|
+
message: string;
|
|
62
|
+
hostHeader?: string;
|
|
63
|
+
hostname?: string;
|
|
64
|
+
};
|
|
53
65
|
/**
|
|
54
|
-
*
|
|
55
|
-
*
|
|
66
|
+
* Parse and validate a `Host` header against an allowlist of hostnames (port-agnostic).
|
|
67
|
+
*
|
|
68
|
+
* - Input host header may include a port (e.g. `localhost:3000`) or IPv6 brackets (e.g. `[::1]:3000`).
|
|
69
|
+
* - Allowlist items should be hostnames only (no ports). For IPv6, include brackets (e.g. `[::1]`).
|
|
56
70
|
*/
|
|
57
|
-
|
|
71
|
+
declare function validateHostHeader(hostHeader: string | null | undefined, allowedHostnames: string[]): HostHeaderValidationResult;
|
|
58
72
|
/**
|
|
59
|
-
*
|
|
60
|
-
* @experimental
|
|
73
|
+
* Convenience allowlist for `localhost` DNS rebinding protection.
|
|
61
74
|
*/
|
|
62
|
-
|
|
75
|
+
declare function localhostAllowedHostnames(): string[];
|
|
63
76
|
/**
|
|
64
|
-
*
|
|
65
|
-
*
|
|
66
|
-
*
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
* @see {@linkcode @modelcontextprotocol/server!experimental/tasks/mcpServer.ExperimentalMcpServerTasks#registerToolTask | registerToolTask} for registration.
|
|
70
|
-
* @experimental
|
|
77
|
+
* Web-standard `Request` helper for DNS rebinding protection.
|
|
78
|
+
* @example
|
|
79
|
+
* ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidationResponse_basicUsage"
|
|
80
|
+
* const result = validateHostHeader(req.headers.get('host'), ['localhost']);
|
|
81
|
+
* ```
|
|
71
82
|
*/
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* Called on the initial `tools/call` request.
|
|
75
|
-
*
|
|
76
|
-
* Creates a task via `ctx.task.store.createTask(...)`, starts any
|
|
77
|
-
* background work, and returns the task object.
|
|
78
|
-
*/
|
|
79
|
-
createTask: CreateTaskRequestHandler<CreateTaskResult, Args>;
|
|
80
|
-
/**
|
|
81
|
-
* Handler for `tasks/get` requests.
|
|
82
|
-
*/
|
|
83
|
-
getTask: TaskRequestHandler<GetTaskResult, Args>;
|
|
84
|
-
/**
|
|
85
|
-
* Handler for `tasks/result` requests.
|
|
86
|
-
*/
|
|
87
|
-
getTaskResult: TaskRequestHandler<CallToolResult, Args>;
|
|
88
|
-
}
|
|
83
|
+
declare function hostHeaderValidationResponse(req: Request, allowedHostnames: string[]): Response | undefined;
|
|
89
84
|
//#endregion
|
|
90
|
-
//#region src/
|
|
85
|
+
//#region src/server/middleware/originValidation.d.ts
|
|
91
86
|
/**
|
|
92
|
-
*
|
|
87
|
+
* Framework-agnostic Origin header validation helpers.
|
|
93
88
|
*
|
|
94
|
-
*
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
89
|
+
* Browsers attach an `Origin` header to cross-origin requests; validating it
|
|
90
|
+
* against an allowlist (alongside Host header validation) protects local and
|
|
91
|
+
* development MCP servers against DNS rebinding and cross-site request
|
|
92
|
+
* forgery. The framework middleware packages (`@modelcontextprotocol/express`,
|
|
93
|
+
* `@modelcontextprotocol/hono`, `@modelcontextprotocol/fastify`,
|
|
94
|
+
* `@modelcontextprotocol/node`) wrap these helpers; use them directly when
|
|
95
|
+
* mounting a handler bare on a fetch-native runtime.
|
|
98
96
|
*
|
|
99
|
-
*
|
|
97
|
+
* Validation is deny-on-failure: a present `Origin` value that cannot be
|
|
98
|
+
* parsed (including the opaque `null` origin) is rejected, never passed
|
|
99
|
+
* through. Requests without an `Origin` header pass — non-browser MCP clients
|
|
100
|
+
* do not send one.
|
|
100
101
|
*/
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
* ```typescript
|
|
113
|
-
* server.experimental.tasks.registerToolTask('long-computation', {
|
|
114
|
-
* description: 'Performs a long computation',
|
|
115
|
-
* inputSchema: z.object({ input: z.string() }),
|
|
116
|
-
* execution: { taskSupport: 'required' }
|
|
117
|
-
* }, {
|
|
118
|
-
* createTask: async (args, ctx) => {
|
|
119
|
-
* const task = await ctx.task.store.createTask({ ttl: 300000 });
|
|
120
|
-
* startBackgroundWork(task.taskId, args);
|
|
121
|
-
* return { task };
|
|
122
|
-
* },
|
|
123
|
-
* getTask: async (args, ctx) => {
|
|
124
|
-
* return ctx.task.store.getTask(ctx.task.id);
|
|
125
|
-
* },
|
|
126
|
-
* getTaskResult: async (args, ctx) => {
|
|
127
|
-
* return ctx.task.store.getTaskResult(ctx.task.id);
|
|
128
|
-
* }
|
|
129
|
-
* });
|
|
130
|
-
* ```
|
|
131
|
-
*
|
|
132
|
-
* @param name - The tool name
|
|
133
|
-
* @param config - Tool configuration (description, schemas, etc.)
|
|
134
|
-
* @param handler - Task handler with {@linkcode ToolTaskHandler.createTask | createTask}, {@linkcode ToolTaskHandler.getTask | getTask}, {@linkcode ToolTaskHandler.getTaskResult | getTaskResult} methods
|
|
135
|
-
* @returns {@linkcode server/mcp.RegisteredTool | RegisteredTool} for managing the tool's lifecycle
|
|
136
|
-
*
|
|
137
|
-
* @experimental
|
|
138
|
-
*/
|
|
139
|
-
registerToolTask<OutputArgs extends StandardSchemaWithJSON | undefined>(name: string, config: {
|
|
140
|
-
title?: string;
|
|
141
|
-
description?: string;
|
|
142
|
-
outputSchema?: OutputArgs;
|
|
143
|
-
annotations?: ToolAnnotations;
|
|
144
|
-
execution?: TaskToolExecution;
|
|
145
|
-
_meta?: Record<string, unknown>;
|
|
146
|
-
}, handler: ToolTaskHandler<undefined>): RegisteredTool;
|
|
147
|
-
registerToolTask<InputArgs extends StandardSchemaWithJSON, OutputArgs extends StandardSchemaWithJSON | undefined>(name: string, config: {
|
|
148
|
-
title?: string;
|
|
149
|
-
description?: string;
|
|
150
|
-
inputSchema: InputArgs;
|
|
151
|
-
outputSchema?: OutputArgs;
|
|
152
|
-
annotations?: ToolAnnotations;
|
|
153
|
-
execution?: TaskToolExecution;
|
|
154
|
-
_meta?: Record<string, unknown>;
|
|
155
|
-
}, handler: ToolTaskHandler<InputArgs>): RegisteredTool;
|
|
156
|
-
}
|
|
157
|
-
//#endregion
|
|
158
|
-
//#region src/experimental/tasks/server.d.ts
|
|
102
|
+
type OriginValidationResult = {
|
|
103
|
+
ok: true;
|
|
104
|
+
origin?: string;
|
|
105
|
+
hostname?: string;
|
|
106
|
+
} | {
|
|
107
|
+
ok: false;
|
|
108
|
+
errorCode: 'invalid_origin_header' | 'invalid_origin';
|
|
109
|
+
message: string;
|
|
110
|
+
originHeader?: string;
|
|
111
|
+
hostname?: string;
|
|
112
|
+
};
|
|
159
113
|
/**
|
|
160
|
-
*
|
|
161
|
-
*
|
|
162
|
-
* Access via `server.experimental.tasks`:
|
|
163
|
-
* ```typescript
|
|
164
|
-
* const stream = server.experimental.tasks.requestStream(request, options);
|
|
165
|
-
* ```
|
|
114
|
+
* Validate an `Origin` header against an allowlist of hostnames (port-agnostic).
|
|
166
115
|
*
|
|
167
|
-
*
|
|
168
|
-
*
|
|
169
|
-
*
|
|
116
|
+
* - A missing/empty `Origin` header passes: non-browser clients do not send one,
|
|
117
|
+
* and only browser-originated requests carry the header this check defends against.
|
|
118
|
+
* - Allowlist items are hostnames only (no scheme, no port), the same convention as
|
|
119
|
+
* `validateHostHeader`. For IPv6, include brackets (e.g. `[::1]`).
|
|
120
|
+
* - Any present value that cannot be parsed as an origin URL — including the literal
|
|
121
|
+
* `null` origin browsers send for opaque contexts — is rejected (deny on failure).
|
|
170
122
|
*/
|
|
171
|
-
declare
|
|
172
|
-
private readonly _server;
|
|
173
|
-
constructor(_server: Server);
|
|
174
|
-
private get _module();
|
|
175
|
-
/**
|
|
176
|
-
* Sends a request and returns an AsyncGenerator that yields response messages.
|
|
177
|
-
* The generator is guaranteed to end with either a `'result'` or `'error'` message.
|
|
178
|
-
*
|
|
179
|
-
* This method provides streaming access to request processing, allowing you to
|
|
180
|
-
* observe intermediate task status updates for task-augmented requests.
|
|
181
|
-
*
|
|
182
|
-
* @param request - The request to send (method name determines the result schema)
|
|
183
|
-
* @param options - Optional request options (timeout, signal, task creation params, etc.)
|
|
184
|
-
* @returns AsyncGenerator that yields {@linkcode ResponseMessage} objects
|
|
185
|
-
*
|
|
186
|
-
* @experimental
|
|
187
|
-
*/
|
|
188
|
-
requestStream<M extends RequestMethod>(request: {
|
|
189
|
-
method: M;
|
|
190
|
-
params?: Record<string, unknown>;
|
|
191
|
-
}, options?: RequestOptions): AsyncGenerator<ResponseMessage<ResultTypeMap[M]>, void, void>;
|
|
192
|
-
/**
|
|
193
|
-
* Sends a sampling request and returns an AsyncGenerator that yields response messages.
|
|
194
|
-
* The generator is guaranteed to end with either a 'result' or 'error' message.
|
|
195
|
-
*
|
|
196
|
-
* For task-augmented requests, yields 'taskCreated' and 'taskStatus' messages
|
|
197
|
-
* before the final result.
|
|
198
|
-
*
|
|
199
|
-
* @example
|
|
200
|
-
* ```typescript
|
|
201
|
-
* const stream = server.experimental.tasks.createMessageStream({
|
|
202
|
-
* messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }],
|
|
203
|
-
* maxTokens: 100
|
|
204
|
-
* }, {
|
|
205
|
-
* onprogress: (progress) => {
|
|
206
|
-
* // Handle streaming tokens via progress notifications
|
|
207
|
-
* console.log('Progress:', progress.message);
|
|
208
|
-
* }
|
|
209
|
-
* });
|
|
210
|
-
*
|
|
211
|
-
* for await (const message of stream) {
|
|
212
|
-
* switch (message.type) {
|
|
213
|
-
* case 'taskCreated':
|
|
214
|
-
* console.log('Task created:', message.task.taskId);
|
|
215
|
-
* break;
|
|
216
|
-
* case 'taskStatus':
|
|
217
|
-
* console.log('Task status:', message.task.status);
|
|
218
|
-
* break;
|
|
219
|
-
* case 'result':
|
|
220
|
-
* console.log('Final result:', message.result);
|
|
221
|
-
* break;
|
|
222
|
-
* case 'error':
|
|
223
|
-
* console.error('Error:', message.error);
|
|
224
|
-
* break;
|
|
225
|
-
* }
|
|
226
|
-
* }
|
|
227
|
-
* ```
|
|
228
|
-
*
|
|
229
|
-
* @param params - The sampling request parameters
|
|
230
|
-
* @param options - Optional request options (timeout, signal, task creation params, onprogress, etc.)
|
|
231
|
-
* @returns AsyncGenerator that yields ResponseMessage objects
|
|
232
|
-
*
|
|
233
|
-
* @experimental
|
|
234
|
-
*/
|
|
235
|
-
createMessageStream(params: CreateMessageRequestParams, options?: RequestOptions): AsyncGenerator<ResponseMessage<CreateMessageResult>, void, void>;
|
|
236
|
-
/**
|
|
237
|
-
* Sends an elicitation request and returns an AsyncGenerator that yields response messages.
|
|
238
|
-
* The generator is guaranteed to end with either a 'result' or 'error' message.
|
|
239
|
-
*
|
|
240
|
-
* For task-augmented requests (especially URL-based elicitation), yields 'taskCreated'
|
|
241
|
-
* and 'taskStatus' messages before the final result.
|
|
242
|
-
*
|
|
243
|
-
* @example
|
|
244
|
-
* ```typescript
|
|
245
|
-
* const stream = server.experimental.tasks.elicitInputStream({
|
|
246
|
-
* mode: 'url',
|
|
247
|
-
* message: 'Please authenticate',
|
|
248
|
-
* elicitationId: 'auth-123',
|
|
249
|
-
* url: 'https://example.com/auth'
|
|
250
|
-
* }, {
|
|
251
|
-
* task: { ttl: 300000 } // Task-augmented for long-running auth flow
|
|
252
|
-
* });
|
|
253
|
-
*
|
|
254
|
-
* for await (const message of stream) {
|
|
255
|
-
* switch (message.type) {
|
|
256
|
-
* case 'taskCreated':
|
|
257
|
-
* console.log('Task created:', message.task.taskId);
|
|
258
|
-
* break;
|
|
259
|
-
* case 'taskStatus':
|
|
260
|
-
* console.log('Task status:', message.task.status);
|
|
261
|
-
* break;
|
|
262
|
-
* case 'result':
|
|
263
|
-
* console.log('User action:', message.result.action);
|
|
264
|
-
* break;
|
|
265
|
-
* case 'error':
|
|
266
|
-
* console.error('Error:', message.error);
|
|
267
|
-
* break;
|
|
268
|
-
* }
|
|
269
|
-
* }
|
|
270
|
-
* ```
|
|
271
|
-
*
|
|
272
|
-
* @param params - The elicitation request parameters
|
|
273
|
-
* @param options - Optional request options (timeout, signal, task creation params, etc.)
|
|
274
|
-
* @returns AsyncGenerator that yields ResponseMessage objects
|
|
275
|
-
*
|
|
276
|
-
* @experimental
|
|
277
|
-
*/
|
|
278
|
-
elicitInputStream(params: ElicitRequestFormParams | ElicitRequestURLParams, options?: RequestOptions): AsyncGenerator<ResponseMessage<ElicitResult>, void, void>;
|
|
279
|
-
/**
|
|
280
|
-
* Gets the current status of a task.
|
|
281
|
-
*
|
|
282
|
-
* @param taskId - The task identifier
|
|
283
|
-
* @param options - Optional request options
|
|
284
|
-
* @returns The task status
|
|
285
|
-
*
|
|
286
|
-
* @experimental
|
|
287
|
-
*/
|
|
288
|
-
getTask(taskId: string, options?: RequestOptions): Promise<GetTaskResult>;
|
|
289
|
-
/**
|
|
290
|
-
* Retrieves the result of a completed task.
|
|
291
|
-
*
|
|
292
|
-
* @param taskId - The task identifier
|
|
293
|
-
* @param options - Optional request options
|
|
294
|
-
* @returns The task result. The payload structure matches the result type of the
|
|
295
|
-
* original request (e.g., a `tools/call` task returns a `CallToolResult`).
|
|
296
|
-
*
|
|
297
|
-
* @experimental
|
|
298
|
-
*/
|
|
299
|
-
getTaskResult(taskId: string, options?: RequestOptions): Promise<GetTaskPayloadResult>;
|
|
300
|
-
/**
|
|
301
|
-
* Lists tasks with optional pagination.
|
|
302
|
-
*
|
|
303
|
-
* @param cursor - Optional pagination cursor
|
|
304
|
-
* @param options - Optional request options
|
|
305
|
-
* @returns List of tasks with optional next cursor
|
|
306
|
-
*
|
|
307
|
-
* @experimental
|
|
308
|
-
*/
|
|
309
|
-
listTasks(cursor?: string, options?: RequestOptions): Promise<ListTasksResult>;
|
|
310
|
-
/**
|
|
311
|
-
* Cancels a running task.
|
|
312
|
-
*
|
|
313
|
-
* @param taskId - The task identifier
|
|
314
|
-
* @param options - Optional request options
|
|
315
|
-
*
|
|
316
|
-
* @experimental
|
|
317
|
-
*/
|
|
318
|
-
cancelTask(taskId: string, options?: RequestOptions): Promise<CancelTaskResult>;
|
|
319
|
-
}
|
|
320
|
-
//#endregion
|
|
321
|
-
//#region src/server/server.d.ts
|
|
123
|
+
declare function validateOriginHeader(originHeader: string | null | undefined, allowedOriginHostnames: string[]): OriginValidationResult;
|
|
322
124
|
/**
|
|
323
|
-
*
|
|
324
|
-
*
|
|
125
|
+
* Convenience allowlist of localhost-class origin hostnames, mirroring
|
|
126
|
+
* `localhostAllowedHostnames`.
|
|
325
127
|
*/
|
|
326
|
-
|
|
327
|
-
type ServerOptions = ProtocolOptions & {
|
|
328
|
-
/**
|
|
329
|
-
* Capabilities to advertise as being supported by this server.
|
|
330
|
-
*/
|
|
331
|
-
capabilities?: Omit<ServerCapabilities, 'tasks'> & {
|
|
332
|
-
tasks?: ServerTasksCapabilityWithRuntime;
|
|
333
|
-
};
|
|
334
|
-
/**
|
|
335
|
-
* Optional instructions describing how to use the server and its features.
|
|
336
|
-
*/
|
|
337
|
-
instructions?: string;
|
|
338
|
-
/**
|
|
339
|
-
* JSON Schema validator for elicitation response validation.
|
|
340
|
-
*
|
|
341
|
-
* The validator is used to validate user input returned from elicitation
|
|
342
|
-
* requests against the requested schema.
|
|
343
|
-
*
|
|
344
|
-
* @default {@linkcode DefaultJsonSchemaValidator} ({@linkcode index.AjvJsonSchemaValidator | AjvJsonSchemaValidator} on Node.js, {@linkcode index.CfWorkerJsonSchemaValidator | CfWorkerJsonSchemaValidator} on Cloudflare Workers)
|
|
345
|
-
*/
|
|
346
|
-
jsonSchemaValidator?: jsonSchemaValidator;
|
|
347
|
-
};
|
|
128
|
+
declare function localhostAllowedOrigins(): string[];
|
|
348
129
|
/**
|
|
349
|
-
*
|
|
350
|
-
*
|
|
351
|
-
*
|
|
130
|
+
* Web-standard `Request` helper for Origin validation: returns a `403` JSON-RPC
|
|
131
|
+
* error response when the request's `Origin` header is not allowed, and
|
|
132
|
+
* `undefined` when the request may proceed.
|
|
352
133
|
*
|
|
353
|
-
*
|
|
134
|
+
* ```ts
|
|
135
|
+
* const rejected = originValidationResponse(request, localhostAllowedOrigins());
|
|
136
|
+
* if (rejected) return rejected;
|
|
137
|
+
* ```
|
|
354
138
|
*/
|
|
355
|
-
declare
|
|
356
|
-
private _serverInfo;
|
|
357
|
-
private _clientCapabilities?;
|
|
358
|
-
private _clientVersion?;
|
|
359
|
-
private _capabilities;
|
|
360
|
-
private _instructions?;
|
|
361
|
-
private _jsonSchemaValidator;
|
|
362
|
-
private _experimental?;
|
|
363
|
-
/**
|
|
364
|
-
* Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification).
|
|
365
|
-
*/
|
|
366
|
-
oninitialized?: () => void;
|
|
367
|
-
/**
|
|
368
|
-
* Initializes this server with the given name and version information.
|
|
369
|
-
*/
|
|
370
|
-
constructor(_serverInfo: Implementation, options?: ServerOptions);
|
|
371
|
-
private _registerLoggingHandler;
|
|
372
|
-
protected buildContext(ctx: BaseContext, transportInfo?: MessageExtraInfo): ServerContext;
|
|
373
|
-
/**
|
|
374
|
-
* Access experimental features.
|
|
375
|
-
*
|
|
376
|
-
* WARNING: These APIs are experimental and may change without notice.
|
|
377
|
-
*
|
|
378
|
-
* @experimental
|
|
379
|
-
*/
|
|
380
|
-
get experimental(): {
|
|
381
|
-
tasks: ExperimentalServerTasks;
|
|
382
|
-
};
|
|
383
|
-
private _loggingLevels;
|
|
384
|
-
private readonly LOG_LEVEL_SEVERITY;
|
|
385
|
-
private isMessageIgnored;
|
|
386
|
-
/**
|
|
387
|
-
* Registers new capabilities. This can only be called before connecting to a transport.
|
|
388
|
-
*
|
|
389
|
-
* The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
|
|
390
|
-
*/
|
|
391
|
-
registerCapabilities(capabilities: ServerCapabilities): void;
|
|
392
|
-
/**
|
|
393
|
-
* Override request handler registration to enforce server-side validation for `tools/call`.
|
|
394
|
-
*/
|
|
395
|
-
setRequestHandler<M extends RequestMethod>(method: M, handler: (request: RequestTypeMap[M], ctx: ServerContext) => ResultTypeMap[M] | Promise<ResultTypeMap[M]>): void;
|
|
396
|
-
protected assertCapabilityForMethod(method: RequestMethod): void;
|
|
397
|
-
protected assertNotificationCapability(method: NotificationMethod): void;
|
|
398
|
-
protected assertRequestHandlerCapability(method: string): void;
|
|
399
|
-
protected assertTaskCapability(method: string): void;
|
|
400
|
-
protected assertTaskHandlerCapability(method: string): void;
|
|
401
|
-
private _oninitialize;
|
|
402
|
-
/**
|
|
403
|
-
* After initialization has completed, this will be populated with the client's reported capabilities.
|
|
404
|
-
*/
|
|
405
|
-
getClientCapabilities(): ClientCapabilities | undefined;
|
|
406
|
-
/**
|
|
407
|
-
* After initialization has completed, this will be populated with information about the client's name and version.
|
|
408
|
-
*/
|
|
409
|
-
getClientVersion(): Implementation | undefined;
|
|
410
|
-
/**
|
|
411
|
-
* Returns the current server capabilities.
|
|
412
|
-
*/
|
|
413
|
-
getCapabilities(): ServerCapabilities;
|
|
414
|
-
ping(): Promise<{
|
|
415
|
-
_meta?: {
|
|
416
|
-
[x: string]: unknown;
|
|
417
|
-
progressToken?: string | number | undefined;
|
|
418
|
-
"io.modelcontextprotocol/related-task"?: {
|
|
419
|
-
taskId: string;
|
|
420
|
-
} | undefined;
|
|
421
|
-
} | undefined;
|
|
422
|
-
}>;
|
|
423
|
-
/**
|
|
424
|
-
* Request LLM sampling from the client (without tools).
|
|
425
|
-
* Returns single content block for backwards compatibility.
|
|
426
|
-
*/
|
|
427
|
-
createMessage(params: CreateMessageRequestParamsBase, options?: RequestOptions): Promise<CreateMessageResult>;
|
|
428
|
-
/**
|
|
429
|
-
* Request LLM sampling from the client with tool support.
|
|
430
|
-
* Returns content that may be a single block or array (for parallel tool calls).
|
|
431
|
-
*/
|
|
432
|
-
createMessage(params: CreateMessageRequestParamsWithTools, options?: RequestOptions): Promise<CreateMessageResultWithTools>;
|
|
433
|
-
/**
|
|
434
|
-
* Request LLM sampling from the client.
|
|
435
|
-
* When tools may or may not be present, returns the union type.
|
|
436
|
-
*/
|
|
437
|
-
createMessage(params: CreateMessageRequest['params'], options?: RequestOptions): Promise<CreateMessageResult | CreateMessageResultWithTools>;
|
|
438
|
-
/**
|
|
439
|
-
* Creates an elicitation request for the given parameters.
|
|
440
|
-
* For backwards compatibility, `mode` may be omitted for form requests and will default to `"form"`.
|
|
441
|
-
* @param params The parameters for the elicitation request.
|
|
442
|
-
* @param options Optional request options.
|
|
443
|
-
* @returns The result of the elicitation request.
|
|
444
|
-
*/
|
|
445
|
-
elicitInput(params: ElicitRequestFormParams | ElicitRequestURLParams, options?: RequestOptions): Promise<ElicitResult>;
|
|
446
|
-
/**
|
|
447
|
-
* Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete`
|
|
448
|
-
* notification for the specified elicitation ID.
|
|
449
|
-
*
|
|
450
|
-
* @param elicitationId The ID of the elicitation to mark as complete.
|
|
451
|
-
* @param options Optional notification options. Useful when the completion notification should be related to a prior request.
|
|
452
|
-
* @returns A function that emits the completion notification when awaited.
|
|
453
|
-
*/
|
|
454
|
-
createElicitationCompletionNotifier(elicitationId: string, options?: NotificationOptions): () => Promise<void>;
|
|
455
|
-
listRoots(params?: ListRootsRequest['params'], options?: RequestOptions): Promise<{
|
|
456
|
-
[x: string]: unknown;
|
|
457
|
-
roots: {
|
|
458
|
-
uri: string;
|
|
459
|
-
name?: string | undefined;
|
|
460
|
-
_meta?: Record<string, unknown> | undefined;
|
|
461
|
-
}[];
|
|
462
|
-
_meta?: {
|
|
463
|
-
[x: string]: unknown;
|
|
464
|
-
progressToken?: string | number | undefined;
|
|
465
|
-
"io.modelcontextprotocol/related-task"?: {
|
|
466
|
-
taskId: string;
|
|
467
|
-
} | undefined;
|
|
468
|
-
} | undefined;
|
|
469
|
-
}>;
|
|
470
|
-
/**
|
|
471
|
-
* Sends a logging message to the client, if connected.
|
|
472
|
-
* Note: You only need to send the parameters object, not the entire JSON-RPC message.
|
|
473
|
-
* @see {@linkcode LoggingMessageNotification}
|
|
474
|
-
* @param params
|
|
475
|
-
* @param sessionId Optional for stateless transports and backward compatibility.
|
|
476
|
-
*/
|
|
477
|
-
sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string): Promise<void>;
|
|
478
|
-
sendResourceUpdated(params: ResourceUpdatedNotification['params']): Promise<void>;
|
|
479
|
-
sendResourceListChanged(): Promise<void>;
|
|
480
|
-
sendToolListChanged(): Promise<void>;
|
|
481
|
-
sendPromptListChanged(): Promise<void>;
|
|
482
|
-
}
|
|
139
|
+
declare function originValidationResponse(req: Request, allowedOriginHostnames: string[]): Response | undefined;
|
|
483
140
|
//#endregion
|
|
484
|
-
//#region src/server/
|
|
141
|
+
//#region src/server/requestStateCodec.d.ts
|
|
485
142
|
/**
|
|
486
|
-
*
|
|
487
|
-
* For advanced usage (like sending notifications or setting custom request handlers), use the underlying
|
|
488
|
-
* {@linkcode Server} instance available via the {@linkcode McpServer.server | server} property.
|
|
489
|
-
*
|
|
490
|
-
* @example
|
|
491
|
-
* ```ts source="./mcp.examples.ts#McpServer_basicUsage"
|
|
492
|
-
* const server = new McpServer({
|
|
493
|
-
* name: 'my-server',
|
|
494
|
-
* version: '1.0.0'
|
|
495
|
-
* });
|
|
496
|
-
* ```
|
|
143
|
+
* Options for {@linkcode createRequestStateCodec}.
|
|
497
144
|
*/
|
|
498
|
-
|
|
145
|
+
interface RequestStateCodecOptions {
|
|
499
146
|
/**
|
|
500
|
-
* The
|
|
147
|
+
* The HMAC secret. A `string` value is UTF-8-encoded. MUST be at least
|
|
148
|
+
* 32 bytes (256 bits) long; a `RangeError` is thrown at
|
|
149
|
+
* construction otherwise. The same key must be available to every server
|
|
150
|
+
* instance that may receive an echoed `requestState` (so a per-process
|
|
151
|
+
* random key only works when one process serves every round of a flow).
|
|
501
152
|
*/
|
|
502
|
-
|
|
503
|
-
private _registeredResources;
|
|
504
|
-
private _registeredResourceTemplates;
|
|
505
|
-
private _registeredTools;
|
|
506
|
-
private _registeredPrompts;
|
|
507
|
-
private _experimental?;
|
|
508
|
-
constructor(serverInfo: Implementation, options?: ServerOptions);
|
|
153
|
+
key: Uint8Array | string;
|
|
509
154
|
/**
|
|
510
|
-
*
|
|
511
|
-
*
|
|
512
|
-
*
|
|
513
|
-
*
|
|
514
|
-
* @experimental
|
|
155
|
+
* How long a minted `requestState` stays valid, in seconds. An echoed
|
|
156
|
+
* value past its expiry is rejected by {@linkcode RequestStateCodec.verify}.
|
|
157
|
+
* Defaults to `600` (ten minutes).
|
|
515
158
|
*/
|
|
516
|
-
|
|
517
|
-
tasks: ExperimentalMcpServerTasks;
|
|
518
|
-
};
|
|
159
|
+
ttlSeconds?: number;
|
|
519
160
|
/**
|
|
520
|
-
*
|
|
521
|
-
*
|
|
522
|
-
*
|
|
161
|
+
* Optional context binding. Called at mint time and again at verify time;
|
|
162
|
+
* a `requestState` minted under one binding value is rejected when echoed
|
|
163
|
+
* under a different one. Use this to bind state to the authenticated
|
|
164
|
+
* principal and/or the originating method (the spec's user-binding MUST
|
|
165
|
+
* for state that influences authorization), for example:
|
|
523
166
|
*
|
|
524
|
-
*
|
|
525
|
-
*
|
|
526
|
-
* const server = new McpServer({ name: 'my-server', version: '1.0.0' });
|
|
527
|
-
* const transport = new StdioServerTransport();
|
|
528
|
-
* await server.connect(transport);
|
|
167
|
+
* ```ts
|
|
168
|
+
* bind: ctx => `${ctx.mcpReq.method}\0${ctx.http?.authInfo?.clientId ?? ''}`
|
|
529
169
|
* ```
|
|
530
|
-
*/
|
|
531
|
-
connect(transport: Transport): Promise<void>;
|
|
532
|
-
/**
|
|
533
|
-
* Closes the connection.
|
|
534
|
-
*/
|
|
535
|
-
close(): Promise<void>;
|
|
536
|
-
private _toolHandlersInitialized;
|
|
537
|
-
private setToolRequestHandlers;
|
|
538
|
-
/**
|
|
539
|
-
* Creates a tool error result.
|
|
540
170
|
*
|
|
541
|
-
*
|
|
542
|
-
*
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
/**
|
|
546
|
-
* Validates tool input arguments against the tool's input schema.
|
|
547
|
-
*/
|
|
548
|
-
private validateToolInput;
|
|
549
|
-
/**
|
|
550
|
-
* Validates tool output against the tool's output schema.
|
|
551
|
-
*/
|
|
552
|
-
private validateToolOutput;
|
|
553
|
-
/**
|
|
554
|
-
* Executes a tool handler (either regular or task-based).
|
|
555
|
-
*/
|
|
556
|
-
private executeToolHandler;
|
|
557
|
-
/**
|
|
558
|
-
* Handles automatic task polling for tools with `taskSupport` `'optional'`.
|
|
559
|
-
*/
|
|
560
|
-
private handleAutomaticTaskPolling;
|
|
561
|
-
private _completionHandlerInitialized;
|
|
562
|
-
private setCompletionRequestHandler;
|
|
563
|
-
private handlePromptCompletion;
|
|
564
|
-
private handleResourceCompletion;
|
|
565
|
-
private _resourceHandlersInitialized;
|
|
566
|
-
private setResourceRequestHandlers;
|
|
567
|
-
private _promptHandlersInitialized;
|
|
568
|
-
private setPromptRequestHandlers;
|
|
569
|
-
/**
|
|
570
|
-
* Registers a resource with a config object and callback.
|
|
571
|
-
* For static resources, use a URI string. For dynamic resources, use a {@linkcode ResourceTemplate}.
|
|
171
|
+
* The returned value is stored in the envelope as a domain-separated HMAC
|
|
172
|
+
* tag (keyed by the codec's `key`), not the raw string — so a principal
|
|
173
|
+
* identifier in the binding does not appear in the wire value the client
|
|
174
|
+
* holds.
|
|
572
175
|
*
|
|
573
|
-
* @
|
|
574
|
-
*
|
|
575
|
-
* server.registerResource(
|
|
576
|
-
* 'config',
|
|
577
|
-
* 'config://app',
|
|
578
|
-
* {
|
|
579
|
-
* title: 'Application Config',
|
|
580
|
-
* mimeType: 'text/plain'
|
|
581
|
-
* },
|
|
582
|
-
* async uri => ({
|
|
583
|
-
* contents: [{ uri: uri.href, text: 'App configuration here' }]
|
|
584
|
-
* })
|
|
585
|
-
* );
|
|
586
|
-
* ```
|
|
176
|
+
* When configured, {@linkcode RequestStateCodec.mint} requires its `ctx`
|
|
177
|
+
* argument.
|
|
587
178
|
*/
|
|
588
|
-
|
|
589
|
-
registerResource(name: string, uriOrTemplate: ResourceTemplate, config: ResourceMetadata, readCallback: ReadResourceTemplateCallback): RegisteredResourceTemplate;
|
|
590
|
-
private _createRegisteredResource;
|
|
591
|
-
private _createRegisteredResourceTemplate;
|
|
592
|
-
private _createRegisteredPrompt;
|
|
593
|
-
private _createRegisteredTool;
|
|
594
|
-
/**
|
|
595
|
-
* Registers a tool with a config object and callback.
|
|
596
|
-
*
|
|
597
|
-
* @example
|
|
598
|
-
* ```ts source="./mcp.examples.ts#McpServer_registerTool_basic"
|
|
599
|
-
* server.registerTool(
|
|
600
|
-
* 'calculate-bmi',
|
|
601
|
-
* {
|
|
602
|
-
* title: 'BMI Calculator',
|
|
603
|
-
* description: 'Calculate Body Mass Index',
|
|
604
|
-
* inputSchema: z.object({
|
|
605
|
-
* weightKg: z.number(),
|
|
606
|
-
* heightM: z.number()
|
|
607
|
-
* }),
|
|
608
|
-
* outputSchema: z.object({ bmi: z.number() })
|
|
609
|
-
* },
|
|
610
|
-
* async ({ weightKg, heightM }) => {
|
|
611
|
-
* const output = { bmi: weightKg / (heightM * heightM) };
|
|
612
|
-
* return {
|
|
613
|
-
* content: [{ type: 'text', text: JSON.stringify(output) }],
|
|
614
|
-
* structuredContent: output
|
|
615
|
-
* };
|
|
616
|
-
* }
|
|
617
|
-
* );
|
|
618
|
-
* ```
|
|
619
|
-
*/
|
|
620
|
-
registerTool<OutputArgs extends StandardSchemaWithJSON, InputArgs extends StandardSchemaWithJSON | undefined = undefined>(name: string, config: {
|
|
621
|
-
title?: string;
|
|
622
|
-
description?: string;
|
|
623
|
-
inputSchema?: InputArgs;
|
|
624
|
-
outputSchema?: OutputArgs;
|
|
625
|
-
annotations?: ToolAnnotations;
|
|
626
|
-
_meta?: Record<string, unknown>;
|
|
627
|
-
}, cb: ToolCallback<InputArgs>): RegisteredTool;
|
|
628
|
-
/**
|
|
629
|
-
* Registers a prompt with a config object and callback.
|
|
630
|
-
*
|
|
631
|
-
* @example
|
|
632
|
-
* ```ts source="./mcp.examples.ts#McpServer_registerPrompt_basic"
|
|
633
|
-
* server.registerPrompt(
|
|
634
|
-
* 'review-code',
|
|
635
|
-
* {
|
|
636
|
-
* title: 'Code Review',
|
|
637
|
-
* description: 'Review code for best practices',
|
|
638
|
-
* argsSchema: z.object({ code: z.string() })
|
|
639
|
-
* },
|
|
640
|
-
* ({ code }) => ({
|
|
641
|
-
* messages: [
|
|
642
|
-
* {
|
|
643
|
-
* role: 'user' as const,
|
|
644
|
-
* content: {
|
|
645
|
-
* type: 'text' as const,
|
|
646
|
-
* text: `Please review this code:\n\n${code}`
|
|
647
|
-
* }
|
|
648
|
-
* }
|
|
649
|
-
* ]
|
|
650
|
-
* })
|
|
651
|
-
* );
|
|
652
|
-
* ```
|
|
653
|
-
*/
|
|
654
|
-
registerPrompt<Args extends StandardSchemaWithJSON>(name: string, config: {
|
|
655
|
-
title?: string;
|
|
656
|
-
description?: string;
|
|
657
|
-
argsSchema?: Args;
|
|
658
|
-
_meta?: Record<string, unknown>;
|
|
659
|
-
}, cb: PromptCallback<Args>): RegisteredPrompt;
|
|
660
|
-
/**
|
|
661
|
-
* Checks if the server is connected to a transport.
|
|
662
|
-
* @returns `true` if the server is connected
|
|
663
|
-
*/
|
|
664
|
-
isConnected(): boolean;
|
|
665
|
-
/**
|
|
666
|
-
* Sends a logging message to the client, if connected.
|
|
667
|
-
* Note: You only need to send the parameters object, not the entire JSON-RPC message.
|
|
668
|
-
* @see {@linkcode LoggingMessageNotification}
|
|
669
|
-
* @param params
|
|
670
|
-
* @param sessionId Optional for stateless transports and backward compatibility.
|
|
671
|
-
*
|
|
672
|
-
* @example
|
|
673
|
-
* ```ts source="./mcp.examples.ts#McpServer_sendLoggingMessage_basic"
|
|
674
|
-
* await server.sendLoggingMessage({
|
|
675
|
-
* level: 'info',
|
|
676
|
-
* data: 'Processing complete'
|
|
677
|
-
* });
|
|
678
|
-
* ```
|
|
679
|
-
*/
|
|
680
|
-
sendLoggingMessage(params: LoggingMessageNotification['params'], sessionId?: string): Promise<void>;
|
|
681
|
-
/**
|
|
682
|
-
* Sends a resource list changed event to the client, if connected.
|
|
683
|
-
*/
|
|
684
|
-
sendResourceListChanged(): void;
|
|
685
|
-
/**
|
|
686
|
-
* Sends a tool list changed event to the client, if connected.
|
|
687
|
-
*/
|
|
688
|
-
sendToolListChanged(): void;
|
|
689
|
-
/**
|
|
690
|
-
* Sends a prompt list changed event to the client, if connected.
|
|
691
|
-
*/
|
|
692
|
-
sendPromptListChanged(): void;
|
|
179
|
+
bind?: (ctx: ServerContext) => string;
|
|
693
180
|
}
|
|
694
181
|
/**
|
|
695
|
-
*
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
*
|
|
702
|
-
*
|
|
182
|
+
* The codec returned by {@linkcode createRequestStateCodec}: `mint` seals a
|
|
183
|
+
* JSON-serializable payload into the wire string a handler returns from
|
|
184
|
+
* `inputRequired({ requestState })`; `verify` is the function to drop into
|
|
185
|
+
* {@linkcode server/server.ServerOptions | ServerOptions}`.requestState.verify`
|
|
186
|
+
* (it throws on any failure, which the seam answers as the frozen `-32602`).
|
|
187
|
+
* The decoded payload `verify` resolves with is handed to the handler by the
|
|
188
|
+
* seam via the typed `ctx.mcpReq.requestState<T>()` accessor — `mint<T>` and
|
|
189
|
+
* `requestState<T>()` are the typed encode/read pair.
|
|
703
190
|
*/
|
|
704
|
-
|
|
705
|
-
private _callbacks;
|
|
706
|
-
private _uriTemplate;
|
|
707
|
-
constructor(uriTemplate: string | UriTemplate, _callbacks: {
|
|
708
|
-
/**
|
|
709
|
-
* A callback to list all resources matching this template. This is required to be specified, even if `undefined`, to avoid accidentally forgetting resource listing.
|
|
710
|
-
*/
|
|
711
|
-
list: ListResourcesCallback | undefined;
|
|
712
|
-
/**
|
|
713
|
-
* An optional callback to autocomplete variables within the URI template. Useful for clients and users to discover possible values.
|
|
714
|
-
*/
|
|
715
|
-
complete?: {
|
|
716
|
-
[variable: string]: CompleteResourceTemplateCallback;
|
|
717
|
-
};
|
|
718
|
-
});
|
|
719
|
-
/**
|
|
720
|
-
* Gets the URI template pattern.
|
|
721
|
-
*/
|
|
722
|
-
get uriTemplate(): UriTemplate;
|
|
191
|
+
interface RequestStateCodec<T = unknown> {
|
|
723
192
|
/**
|
|
724
|
-
*
|
|
193
|
+
* Seal `payload` into an opaque wire string. The result is what the
|
|
194
|
+
* handler returns from `inputRequired({ requestState })`.
|
|
195
|
+
*
|
|
196
|
+
* @param ctx The handler's context. Required when the codec was created
|
|
197
|
+
* with a {@linkcode RequestStateCodecOptions.bind | bind}
|
|
198
|
+
* callback; ignored otherwise.
|
|
725
199
|
*/
|
|
726
|
-
|
|
200
|
+
mint(payload: T, ctx?: ServerContext): Promise<string>;
|
|
727
201
|
/**
|
|
728
|
-
*
|
|
202
|
+
* Verify an echoed `requestState` and return the original payload. Throws
|
|
203
|
+
* on any failure (bad MAC, expired, bind mismatch, malformed). The thrown
|
|
204
|
+
* message is a fixed opaque reason code (`'malformed'` / `'mac'` /
|
|
205
|
+
* `'expired'` / `'bind'`) — never the decoded payload, the binding value,
|
|
206
|
+
* or any other context-derived field.
|
|
207
|
+
*
|
|
208
|
+
* Pass this directly as `ServerOptions.requestState.verify`.
|
|
729
209
|
*/
|
|
730
|
-
|
|
210
|
+
verify(state: string, ctx: ServerContext): Promise<T>;
|
|
731
211
|
}
|
|
732
|
-
type BaseToolCallback<SendResultT extends Result, Ctx extends ServerContext, Args extends StandardSchemaWithJSON | undefined> = Args extends StandardSchemaWithJSON ? (args: StandardSchemaWithJSON.InferOutput<Args>, ctx: Ctx) => SendResultT | Promise<SendResultT> : (ctx: Ctx) => SendResultT | Promise<SendResultT>;
|
|
733
|
-
/**
|
|
734
|
-
* Callback for a tool handler registered with {@linkcode McpServer.registerTool}.
|
|
735
|
-
*/
|
|
736
|
-
type ToolCallback<Args extends StandardSchemaWithJSON | undefined = undefined> = BaseToolCallback<CallToolResult, ServerContext, Args>;
|
|
737
|
-
/**
|
|
738
|
-
* Supertype that can handle both regular tools (simple callback) and task-based tools (task handler object).
|
|
739
|
-
*/
|
|
740
|
-
type AnyToolHandler<Args extends StandardSchemaWithJSON | undefined = undefined> = ToolCallback<Args> | ToolTaskHandler<Args>;
|
|
741
|
-
/**
|
|
742
|
-
* Internal executor type that encapsulates handler invocation with proper types.
|
|
743
|
-
*/
|
|
744
|
-
type ToolExecutor = (args: unknown, ctx: ServerContext) => Promise<CallToolResult | CreateTaskResult>;
|
|
745
|
-
type RegisteredTool = {
|
|
746
|
-
title?: string;
|
|
747
|
-
description?: string;
|
|
748
|
-
inputSchema?: StandardSchemaWithJSON;
|
|
749
|
-
outputSchema?: StandardSchemaWithJSON;
|
|
750
|
-
annotations?: ToolAnnotations;
|
|
751
|
-
execution?: ToolExecution;
|
|
752
|
-
_meta?: Record<string, unknown>;
|
|
753
|
-
handler: AnyToolHandler<StandardSchemaWithJSON | undefined>;
|
|
754
|
-
/** @hidden */
|
|
755
|
-
executor: ToolExecutor;
|
|
756
|
-
enabled: boolean;
|
|
757
|
-
enable(): void;
|
|
758
|
-
disable(): void;
|
|
759
|
-
update(updates: {
|
|
760
|
-
name?: string | null;
|
|
761
|
-
title?: string;
|
|
762
|
-
description?: string;
|
|
763
|
-
paramsSchema?: StandardSchemaWithJSON;
|
|
764
|
-
outputSchema?: StandardSchemaWithJSON;
|
|
765
|
-
annotations?: ToolAnnotations;
|
|
766
|
-
_meta?: Record<string, unknown>;
|
|
767
|
-
callback?: ToolCallback<StandardSchemaWithJSON>;
|
|
768
|
-
enabled?: boolean;
|
|
769
|
-
}): void;
|
|
770
|
-
remove(): void;
|
|
771
|
-
};
|
|
772
212
|
/**
|
|
773
|
-
*
|
|
774
|
-
|
|
775
|
-
type ResourceMetadata = Omit<Resource, 'uri' | 'name'>;
|
|
776
|
-
/**
|
|
777
|
-
* Callback to list all resources matching a given template.
|
|
778
|
-
*/
|
|
779
|
-
type ListResourcesCallback = (ctx: ServerContext) => ListResourcesResult | Promise<ListResourcesResult>;
|
|
780
|
-
/**
|
|
781
|
-
* Callback to read a resource at a given URI.
|
|
782
|
-
*/
|
|
783
|
-
type ReadResourceCallback = (uri: URL, ctx: ServerContext) => ReadResourceResult | Promise<ReadResourceResult>;
|
|
784
|
-
type RegisteredResource = {
|
|
785
|
-
name: string;
|
|
786
|
-
title?: string;
|
|
787
|
-
metadata?: ResourceMetadata;
|
|
788
|
-
readCallback: ReadResourceCallback;
|
|
789
|
-
enabled: boolean;
|
|
790
|
-
enable(): void;
|
|
791
|
-
disable(): void;
|
|
792
|
-
update(updates: {
|
|
793
|
-
name?: string;
|
|
794
|
-
title?: string;
|
|
795
|
-
uri?: string | null;
|
|
796
|
-
metadata?: ResourceMetadata;
|
|
797
|
-
callback?: ReadResourceCallback;
|
|
798
|
-
enabled?: boolean;
|
|
799
|
-
}): void;
|
|
800
|
-
remove(): void;
|
|
801
|
-
};
|
|
802
|
-
/**
|
|
803
|
-
* Callback to read a resource at a given URI, following a filled-in URI template.
|
|
804
|
-
*/
|
|
805
|
-
type ReadResourceTemplateCallback = (uri: URL, variables: Variables, ctx: ServerContext) => ReadResourceResult | Promise<ReadResourceResult>;
|
|
806
|
-
type RegisteredResourceTemplate = {
|
|
807
|
-
resourceTemplate: ResourceTemplate;
|
|
808
|
-
title?: string;
|
|
809
|
-
metadata?: ResourceMetadata;
|
|
810
|
-
readCallback: ReadResourceTemplateCallback;
|
|
811
|
-
enabled: boolean;
|
|
812
|
-
enable(): void;
|
|
813
|
-
disable(): void;
|
|
814
|
-
update(updates: {
|
|
815
|
-
name?: string | null;
|
|
816
|
-
title?: string;
|
|
817
|
-
template?: ResourceTemplate;
|
|
818
|
-
metadata?: ResourceMetadata;
|
|
819
|
-
callback?: ReadResourceTemplateCallback;
|
|
820
|
-
enabled?: boolean;
|
|
821
|
-
}): void;
|
|
822
|
-
remove(): void;
|
|
823
|
-
};
|
|
824
|
-
type PromptCallback<Args extends StandardSchemaWithJSON | undefined = undefined> = Args extends StandardSchemaWithJSON ? (args: StandardSchemaWithJSON.InferOutput<Args>, ctx: ServerContext) => GetPromptResult | Promise<GetPromptResult> : (ctx: ServerContext) => GetPromptResult | Promise<GetPromptResult>;
|
|
825
|
-
/**
|
|
826
|
-
* Internal handler type that encapsulates parsing and callback invocation.
|
|
827
|
-
* This allows type-safe handling without runtime type assertions.
|
|
828
|
-
*/
|
|
829
|
-
type PromptHandler = (args: Record<string, unknown> | undefined, ctx: ServerContext) => Promise<GetPromptResult>;
|
|
830
|
-
type RegisteredPrompt = {
|
|
831
|
-
title?: string;
|
|
832
|
-
description?: string;
|
|
833
|
-
argsSchema?: StandardSchemaWithJSON;
|
|
834
|
-
_meta?: Record<string, unknown>;
|
|
835
|
-
/** @hidden */
|
|
836
|
-
handler: PromptHandler;
|
|
837
|
-
enabled: boolean;
|
|
838
|
-
enable(): void;
|
|
839
|
-
disable(): void;
|
|
840
|
-
update<Args extends StandardSchemaWithJSON>(updates: {
|
|
841
|
-
name?: string | null;
|
|
842
|
-
title?: string;
|
|
843
|
-
description?: string;
|
|
844
|
-
argsSchema?: Args;
|
|
845
|
-
_meta?: Record<string, unknown>;
|
|
846
|
-
callback?: PromptCallback<Args>;
|
|
847
|
-
enabled?: boolean;
|
|
848
|
-
}): void;
|
|
849
|
-
remove(): void;
|
|
850
|
-
};
|
|
851
|
-
//#endregion
|
|
852
|
-
//#region src/server/middleware/hostHeaderValidation.d.ts
|
|
853
|
-
type HostHeaderValidationResult = {
|
|
854
|
-
ok: true;
|
|
855
|
-
hostname: string;
|
|
856
|
-
} | {
|
|
857
|
-
ok: false;
|
|
858
|
-
errorCode: 'missing_host' | 'invalid_host_header' | 'invalid_host';
|
|
859
|
-
message: string;
|
|
860
|
-
hostHeader?: string;
|
|
861
|
-
hostname?: string;
|
|
862
|
-
};
|
|
863
|
-
/**
|
|
864
|
-
* Parse and validate a `Host` header against an allowlist of hostnames (port-agnostic).
|
|
213
|
+
* Create an opt-in HMAC-SHA256 codec for the multi-round-trip `requestState`
|
|
214
|
+
* (protocol revision 2026-07-28).
|
|
865
215
|
*
|
|
866
|
-
* -
|
|
867
|
-
*
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
/**
|
|
871
|
-
* Convenience allowlist for `localhost` DNS rebinding protection.
|
|
872
|
-
*/
|
|
873
|
-
declare function localhostAllowedHostnames(): string[];
|
|
874
|
-
/**
|
|
875
|
-
* Web-standard `Request` helper for DNS rebinding protection.
|
|
876
|
-
* @example
|
|
877
|
-
* ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidationResponse_basicUsage"
|
|
878
|
-
* const result = validateHostHeader(req.headers.get('host'), ['localhost']);
|
|
879
|
-
* ```
|
|
880
|
-
*/
|
|
881
|
-
declare function hostHeaderValidationResponse(req: Request, allowedHostnames: string[]): Response | undefined;
|
|
882
|
-
//#endregion
|
|
883
|
-
//#region src/server/stdio.d.ts
|
|
884
|
-
/**
|
|
885
|
-
* Server transport for stdio: this communicates with an MCP client by reading from the current process' `stdin` and writing to `stdout`.
|
|
216
|
+
* `requestState` round-trips through the client and is attacker-controlled
|
|
217
|
+
* input on re-entry. The SDK applies no protection of its own; this helper is
|
|
218
|
+
* the convenience implementation of the spec's integrity MUST so authors don't
|
|
219
|
+
* hand-roll HMAC. Wire shape:
|
|
886
220
|
*
|
|
887
|
-
*
|
|
221
|
+
* "v1." b64url({"p":<payload>,"exp":<unixSeconds>,"b":<bindTag>?}) "." b64url(mac)
|
|
888
222
|
*
|
|
889
|
-
*
|
|
890
|
-
*
|
|
891
|
-
*
|
|
892
|
-
*
|
|
893
|
-
*
|
|
894
|
-
*
|
|
223
|
+
* where `bindTag` is `b64url(HMAC(key, "mcp.requestState.bind:" + bind(ctx))[:16])`
|
|
224
|
+
* — the binding value is never embedded raw.
|
|
225
|
+
*
|
|
226
|
+
* The codec is **signed, not encrypted**: the body is integrity-protected but
|
|
227
|
+
* the client can base64url-decode it and read the payload (`p`) in clear. Do
|
|
228
|
+
* not put secrets in the payload; use an AEAD construction if confidentiality
|
|
229
|
+
* is required. The handler reads its payload back via the typed
|
|
230
|
+
* `ctx.mcpReq.requestState<T>()` accessor — the seam has already run `verify`
|
|
231
|
+
* (integrity proven, payload decoded) by the time the handler is entered.
|
|
232
|
+
*
|
|
233
|
+
* Verification is fail-closed and constant-time (WebCrypto `subtle.verify` for
|
|
234
|
+
* the body MAC; a fixed-length XOR-accumulator compare for the bind tag).
|
|
235
|
+
* See `examples/mrtr/server.ts` for a worked end-to-end example.
|
|
236
|
+
*
|
|
237
|
+
* Design comparison (mcp.d `secureRequestState`, the peer SDK's reference
|
|
238
|
+
* implementation): mcp.d additionally offers an AES-256-GCM encrypted mode and
|
|
239
|
+
* derives independent cipher / bind-HMAC sub-keys from the operator secret via
|
|
240
|
+
* HKDF-SHA256, with an auto-generated per-process ephemeral key when none is
|
|
241
|
+
* supplied. This codec deliberately ships only the signed mode and a single
|
|
242
|
+
* keyed HMAC (domain-separated by input prefix) — HKDF sub-key derivation and
|
|
243
|
+
* an encrypted mode are intentionally out of scope for the initial release.
|
|
895
244
|
*/
|
|
896
|
-
declare
|
|
897
|
-
private _stdin;
|
|
898
|
-
private _stdout;
|
|
899
|
-
private _readBuffer;
|
|
900
|
-
private _started;
|
|
901
|
-
private _closed;
|
|
902
|
-
constructor(_stdin?: Readable, _stdout?: Writable);
|
|
903
|
-
onclose?: () => void;
|
|
904
|
-
onerror?: (error: Error) => void;
|
|
905
|
-
onmessage?: (message: JSONRPCMessage) => void;
|
|
906
|
-
_ondata: (chunk: Buffer) => void;
|
|
907
|
-
_onerror: (error: Error) => void;
|
|
908
|
-
_onstdouterror: (error: Error) => void;
|
|
909
|
-
/**
|
|
910
|
-
* Starts listening for messages on `stdin`.
|
|
911
|
-
*/
|
|
912
|
-
start(): Promise<void>;
|
|
913
|
-
private processReadBuffer;
|
|
914
|
-
close(): Promise<void>;
|
|
915
|
-
send(message: JSONRPCMessage): Promise<void>;
|
|
916
|
-
}
|
|
245
|
+
declare function createRequestStateCodec<T = unknown>(options: RequestStateCodecOptions): RequestStateCodec<T>;
|
|
917
246
|
//#endregion
|
|
918
247
|
//#region src/server/streamableHttp.d.ts
|
|
919
248
|
type StreamId = string;
|
|
@@ -954,7 +283,7 @@ interface WebStandardStreamableHTTPServerTransportOptions {
|
|
|
954
283
|
*
|
|
955
284
|
* If not provided, session management is disabled (stateless mode).
|
|
956
285
|
*/
|
|
957
|
-
sessionIdGenerator?: () => string;
|
|
286
|
+
sessionIdGenerator?: (() => string) | undefined;
|
|
958
287
|
/**
|
|
959
288
|
* A callback for session initialization events
|
|
960
289
|
* This is called when the server initializes a new session.
|
|
@@ -962,7 +291,7 @@ interface WebStandardStreamableHTTPServerTransportOptions {
|
|
|
962
291
|
* and need to keep track of them.
|
|
963
292
|
* @param sessionId The generated session ID
|
|
964
293
|
*/
|
|
965
|
-
onsessioninitialized?: (sessionId: string) => void | Promise<void
|
|
294
|
+
onsessioninitialized?: ((sessionId: string) => void | Promise<void>) | undefined;
|
|
966
295
|
/**
|
|
967
296
|
* A callback for session close events
|
|
968
297
|
* This is called when the server closes a session due to a `DELETE` request.
|
|
@@ -973,7 +302,7 @@ interface WebStandardStreamableHTTPServerTransportOptions {
|
|
|
973
302
|
* session open/running.
|
|
974
303
|
* @param sessionId The session ID that was closed
|
|
975
304
|
*/
|
|
976
|
-
onsessionclosed?: (sessionId: string) => void | Promise<void
|
|
305
|
+
onsessionclosed?: ((sessionId: string) => void | Promise<void>) | undefined;
|
|
977
306
|
/**
|
|
978
307
|
* If `true`, the server will return JSON responses instead of starting an SSE stream.
|
|
979
308
|
* This can be useful for simple request/response scenarios without streaming.
|
|
@@ -1089,6 +418,7 @@ interface HandleRequestOptions {
|
|
|
1089
418
|
declare class WebStandardStreamableHTTPServerTransport implements Transport {
|
|
1090
419
|
private sessionIdGenerator;
|
|
1091
420
|
private _started;
|
|
421
|
+
private _closed;
|
|
1092
422
|
private _streamMapping;
|
|
1093
423
|
private _requestToStreamMapping;
|
|
1094
424
|
private _requestResponseMap;
|
|
@@ -1132,10 +462,24 @@ declare class WebStandardStreamableHTTPServerTransport implements Transport {
|
|
|
1132
462
|
* Returns a `Response` object (Web Standard)
|
|
1133
463
|
*/
|
|
1134
464
|
handleRequest(req: Request, options?: HandleRequestOptions): Promise<Response>;
|
|
465
|
+
/**
|
|
466
|
+
* Returns true if the client's protocol version supports empty SSE data in
|
|
467
|
+
* priming events (the fix shipped with protocol version `2025-11-25`).
|
|
468
|
+
*
|
|
469
|
+
* The version is checked for membership in this transport instance's
|
|
470
|
+
* supported protocol versions rather than with an open-ended
|
|
471
|
+
* `>= '2025-11-25'` comparison: the value may come from an `initialize`
|
|
472
|
+
* request body, which (unlike the `MCP-Protocol-Version` header) is not
|
|
473
|
+
* validated against `supportedProtocolVersions` before reaching this
|
|
474
|
+
* check. An unknown future version string must not silently enable
|
|
475
|
+
* behavior reserved for versions this transport actually supports.
|
|
476
|
+
*/
|
|
477
|
+
private supportsEmptySSEData;
|
|
1135
478
|
/**
|
|
1136
479
|
* Writes a priming event to establish resumption capability.
|
|
1137
480
|
* Only sends if `eventStore` is configured (opt-in for resumability) and
|
|
1138
|
-
* the client's protocol version supports empty SSE data (
|
|
481
|
+
* the client's protocol version supports empty SSE data (a supported
|
|
482
|
+
* version that is >= `2025-11-25`).
|
|
1139
483
|
*/
|
|
1140
484
|
private writePrimingEvent;
|
|
1141
485
|
/**
|
|
@@ -1202,5 +546,5 @@ declare class WebStandardStreamableHTTPServerTransport implements Transport {
|
|
|
1202
546
|
//#region src/fromJsonSchema.d.ts
|
|
1203
547
|
declare function fromJsonSchema<T = unknown>(schema: JsonSchemaType, validator?: jsonSchemaValidator): StandardSchemaWithJSON<T, T>;
|
|
1204
548
|
//#endregion
|
|
1205
|
-
export { AjvJsonSchemaValidator, Annotations, type AnyToolHandler, AudioContent, AuthInfo, type AuthorizationServerMetadata, type BaseContext, BaseMetadata, type
|
|
549
|
+
export { type AjvJsonSchemaValidator, Annotations, type AnyToolHandler, AudioContent, AuthInfo, type AuthorizationServerMetadata, BAGGAGE_META_KEY, type BaseContext, BaseMetadata, type BaseToolCallback, BlobResourceContents, BooleanSchema, CLIENT_CAPABILITIES_META_KEY, CLIENT_INFO_META_KEY, type CacheHint, type CacheScope, CallToolRequest, CallToolRequestParams, CallToolResult, CancelTaskRequest, CancelTaskResult, CancelledNotification, CancelledNotificationParams, type CfWorkerJsonSchemaValidator, type CfWorkerSchemaDraft, ClientCapabilities, type ClientContext, ClientNotification, ClientRequest, ClientResult, CompatibilityCallToolResult, type CompletableSchema, type CompleteCallback, CompleteRequest, CompleteRequestParams, CompleteRequestPrompt, CompleteRequestResourceTemplate, type CompleteResourceTemplateCallback, CompleteResult, ContentBlock, type CreateMcpHandlerOptions, CreateMessageRequest, CreateMessageRequestParams, CreateMessageRequestParamsBase, CreateMessageRequestParamsWithTools, CreateMessageResult, CreateMessageResultWithTools, CreateTaskResult, Cursor, DEFAULT_NEGOTIATED_PROTOCOL_VERSION, DEFAULT_REQUEST_TIMEOUT_MSEC, DiscoverRequest, DiscoverResult, ElicitRequest, ElicitRequestFormParams, ElicitRequestParams, ElicitRequestURLParams, ElicitResult, ElicitationCompleteNotification, ElicitationCompleteNotificationParams, EmbeddedResource, EmptyResult, EnumSchema, type EventId, type EventStore, type FetchLike, GetPromptRequest, GetPromptRequestParams, GetPromptResult, GetTaskPayloadRequest, GetTaskPayloadResult, GetTaskRequest, GetTaskResult, type HandleRequestOptions, HandlerResultTypeMap, type HostHeaderValidationResult, INTERNAL_ERROR, INVALID_PARAMS, INVALID_REQUEST, Icon, Icons, type IdJagTokenExchangeResponse, ImageContent, Implementation, InMemoryServerEventBus, InMemoryTransport, type InboundClassificationOutcome, type InboundHttpRequest, type InboundLadderRejection, type InboundLegacyRoute, type InboundLegacyRouteReason, type InboundModernRoute, type InboundValidationRung, InitializeRequest, InitializeRequestParams, InitializeResult, InitializedNotification, InputRequest, InputRequests, InputRequiredResult, type InputRequiredSpec, InputResponse, type InputResponseView, InputResponses, InternalError, InvalidParamsError, InvalidRequestError, JSONArray, JSONObject, JSONRPCErrorResponse, JSONRPCMessage, JSONRPCNotification, JSONRPCRequest, JSONRPCResponse, JSONRPCResultResponse, JSONRPC_VERSION, JSONValue, type JsonSchemaType, type JsonSchemaValidator, type JsonSchemaValidatorResult, LATEST_PROTOCOL_VERSION, LOG_LEVEL_META_KEY, type LegacyHttpHandler, LegacyTitledEnumSchema, ListChangedCallback, ListChangedHandlers, ListChangedOptions, ListPromptsRequest, ListPromptsResult, ListResourceTemplatesRequest, ListResourceTemplatesResult, type ListResourcesCallback, ListResourcesRequest, ListResourcesResult, ListRootsRequest, ListRootsResult, ListTasksRequest, ListTasksResult, ListToolsRequest, ListToolsResult, LoggingLevel, LoggingMessageNotification, LoggingMessageNotificationParams, METHOD_NOT_FOUND, type McpHandlerRequestOptions, type McpHttpHandler, type McpRequestContext, McpServer, type McpServerFactory, MessageClassification, MessageExtraInfo, MetaObject, MethodNotFoundError, MissingRequiredClientCapabilityError, MissingRequiredClientCapabilityErrorData, ModelHint, ModelPreferences, MultiSelectEnumSchema, Notification, NotificationMethod, type NotificationOptions, NotificationParams, NotificationTypeMap, NumberSchema, type OAuthClientInformation, type OAuthClientInformationFull, type OAuthClientInformationMixed, type OAuthClientMetadata, type OAuthClientRegistrationError, OAuthError, OAuthErrorCode, type OAuthErrorResponse, type OAuthMetadata, type OAuthProtectedResourceMetadata, type OAuthTokenRevocationRequest, type OAuthTokens, type OpenIdProviderDiscoveryMetadata, type OpenIdProviderMetadata, type OriginValidationResult, PARSE_ERROR, PROTOCOL_VERSION_META_KEY, PaginatedRequest, PaginatedRequestParams, PaginatedResult, ParseError, PerRequestHTTPServerTransport, type PerRequestHTTPServerTransportOptions, type PerRequestMessageExtra, type PerRequestResponseMode, PingRequest, PrimitiveSchemaDefinition, Progress, type ProgressCallback, ProgressNotification, ProgressNotificationParams, ProgressToken, Prompt, PromptArgument, type PromptCallback, PromptListChangedNotification, PromptMessage, PromptReference, type ProtocolEra, ProtocolError, ProtocolErrorCode, type ProtocolOptions, RELATED_TASK_META_KEY, ReadBuffer, type ReadResourceCallback, ReadResourceRequest, ReadResourceRequestParams, ReadResourceResult, type ReadResourceTemplateCallback, type RegisteredPrompt, type RegisteredResource, type RegisteredResourceTemplate, type RegisteredTool, RelatedTaskMetadata, Request$1 as Request, type RequestHandlerSchemas, RequestId, RequestMeta, RequestMetaEnvelope, RequestMetaObject, RequestMethod, type RequestOptions, RequestParams, type RequestStateAccessor, type RequestStateCodec, type RequestStateCodecOptions, RequestTypeMap, Resource, ResourceContents, ResourceLink, ResourceListChangedNotification, type ResourceMetadata, ResourceNotFoundError, ResourceRequestParams, ResourceTemplate, ResourceTemplateReference, ResourceTemplateType, ResourceUpdatedNotification, ResourceUpdatedNotificationParams, Result, ResultTypeMap, Role, Root, RootsListChangedNotification, STDIO_DEFAULT_MAX_BUFFER_SIZE, SUBSCRIPTION_ID_META_KEY, SUPPORTED_PROTOCOL_VERSIONS, SamplingContent, SamplingMessage, SamplingMessageContentBlock, SdkError, SdkErrorCode, SdkHttpError, type SdkHttpErrorData, Server, ServerCapabilities, type ServerContext, type ServerEvent, type ServerEventBus, ServerNotification, type ServerNotifier, type ServerOptions, ServerRequest, ServerResult, SetLevelRequest, SetLevelRequestParams, SingleSelectEnumSchema, type SpecTypeName, type SpecTypes, type StandardSchemaV1, type StandardSchemaV1Sync, type StandardSchemaWithJSON, type StoredOAuthClientInformation, type StoredOAuthTokens, type StreamId, StringSchema, SubscribeRequest, SubscribeRequestParams, SubscriptionFilter, SubscriptionsAcknowledgedNotification, SubscriptionsAcknowledgedNotificationParams, SubscriptionsListenRequest, SubscriptionsListenRequestParams, SubscriptionsListenResult, SubscriptionsListenResultMeta, TRACEPARENT_META_KEY, TRACESTATE_META_KEY, Task, TaskAugmentedRequestParams, TaskCreationParams, TaskMetadata, TaskStatus, TaskStatusNotification, TaskStatusNotificationParams, TextContent, TextResourceContents, TitledMultiSelectEnumSchema, TitledSingleSelectEnumSchema, Tool, ToolAnnotations, type ToolCallback, ToolChoice, ToolExecution, ToolListChangedNotification, ToolResultContent, ToolUseContent, type Transport, type TransportSendOptions, UnsubscribeRequest, UnsubscribeRequestParams, UnsupportedProtocolVersionError, UnsupportedProtocolVersionErrorData, UntitledMultiSelectEnumSchema, UntitledSingleSelectEnumSchema, UriTemplate, UrlElicitationRequiredError, type Variables, WebStandardStreamableHTTPServerTransport, type WebStandardStreamableHTTPServerTransportOptions, acceptedContent, assertCompleteRequestPrompt, assertCompleteRequestResourceTemplate, checkResourceAllowed, classifyInboundRequest, completable, createFetchWithInit, createMcpHandler, createRequestStateCodec, deserializeMessage, fromJsonSchema, getDisplayName, hostHeaderValidationResponse, inputRequired, inputResponse, isCallToolResult, isCompletable, isInitializeRequest, isInitializedNotification, isInputRequiredResult, isJSONRPCErrorResponse, isJSONRPCNotification, isJSONRPCRequest, isJSONRPCResponse, isJSONRPCResultResponse, isLegacyRequest, isSpecType, isTaskAugmentedRequestParams, type jsonSchemaValidator, legacyStatelessFallback, localhostAllowedHostnames, localhostAllowedOrigins, originValidationResponse, parseJSONRPCMessage, resourceUrlFromServerUrl, serializeMessage, specTypeSchemas, validateHostHeader, validateOriginHeader };
|
|
1206
550
|
//# sourceMappingURL=index.d.mts.map
|