@modelcontextprotocol/server 2.0.0-alpha.1

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.
@@ -0,0 +1,1206 @@
1
+ import { $ as ServerCapabilities, A as CreateTaskResult, B as ListRootsRequest, C as ClientCapabilities, D as CreateMessageRequestParamsWithTools, E as CreateMessageRequestParamsBase, F as GetTaskPayloadResult, G as ReadResourceResult, H as LoggingMessageNotification, I as GetTaskResult, J as RequestTypeMap, K as RequestId, L as Implementation, M as ElicitRequestURLParams, N as ElicitResult, O as CreateMessageResult, P as GetPromptResult, Q as ResultTypeMap, R as JSONRPCMessage, S as CancelTaskResult, T as CreateMessageRequestParams, U as MessageExtraInfo, V as ListTasksResult, W as NotificationMethod, X as ResourceUpdatedNotification, Y as Resource, Z as Result, _ as CreateTaskServerContext, a as StandardSchemaWithJSON, b as AuthInfo, c as BaseContext, d as ProtocolOptions, et as ToolAnnotations, f as RequestOptions, g as ResponseMessage, h as TaskManagerOptions, i as jsonSchemaValidator, j as ElicitRequestFormParams, k as CreateMessageResultWithTools, l as NotificationOptions, m as Transport, o as UriTemplate, p as ServerContext, q as RequestMethod, r as JsonSchemaType, s as Variables, tt as ToolExecution, u as Protocol, v as TaskServerContext, w as CreateMessageRequest, x as CallToolResult, y as TaskToolExecution, z as ListResourcesResult } from "./index-DbrUKkja.mjs";
2
+ import { Readable, Writable } from "node:stream";
3
+
4
+ //#region src/server/completable.d.ts
5
+ declare const COMPLETABLE_SYMBOL: unique symbol;
6
+ type CompleteCallback<T extends StandardSchemaWithJSON = StandardSchemaWithJSON> = (value: StandardSchemaWithJSON.InferInput<T>, context?: {
7
+ arguments?: Record<string, string>;
8
+ }) => StandardSchemaWithJSON.InferInput<T>[] | Promise<StandardSchemaWithJSON.InferInput<T>[]>;
9
+ type CompletableMeta<T extends StandardSchemaWithJSON = StandardSchemaWithJSON> = {
10
+ complete: CompleteCallback<T>;
11
+ };
12
+ type CompletableSchema<T extends StandardSchemaWithJSON> = T & {
13
+ [COMPLETABLE_SYMBOL]: CompletableMeta<T>;
14
+ };
15
+ /**
16
+ * Wraps a schema to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP.
17
+ *
18
+ * @example
19
+ * ```ts source="./completable.examples.ts#completable_basicUsage"
20
+ * server.registerPrompt(
21
+ * 'review-code',
22
+ * {
23
+ * title: 'Code Review',
24
+ * argsSchema: z.object({
25
+ * language: completable(z.string().describe('Programming language'), value =>
26
+ * ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => lang.startsWith(value))
27
+ * )
28
+ * })
29
+ * },
30
+ * ({ language }) => ({
31
+ * messages: [
32
+ * {
33
+ * role: 'user' as const,
34
+ * content: {
35
+ * type: 'text' as const,
36
+ * text: `Review this ${language} code.`
37
+ * }
38
+ * }
39
+ * ]
40
+ * })
41
+ * );
42
+ * ```
43
+ *
44
+ * @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions
45
+ */
46
+ declare function completable<T extends StandardSchemaWithJSON>(schema: T, complete: CompleteCallback<T>): CompletableSchema<T>;
47
+ /**
48
+ * Checks if a schema is completable (has completion metadata).
49
+ */
50
+ declare function isCompletable(schema: unknown): schema is CompletableSchema<StandardSchemaWithJSON>;
51
+ //#endregion
52
+ //#region src/experimental/tasks/interfaces.d.ts
53
+ /**
54
+ * Handler for creating a task.
55
+ * @experimental
56
+ */
57
+ type CreateTaskRequestHandler<SendResultT extends Result, Args extends StandardSchemaWithJSON | undefined = undefined> = BaseToolCallback<SendResultT, CreateTaskServerContext, Args>;
58
+ /**
59
+ * Handler for task operations (`get`, `getResult`).
60
+ * @experimental
61
+ */
62
+ type TaskRequestHandler<SendResultT extends Result, Args extends StandardSchemaWithJSON | undefined = undefined> = BaseToolCallback<SendResultT, TaskServerContext, Args>;
63
+ /**
64
+ * Interface for task-based tool handlers.
65
+ *
66
+ * Task-based tools split a long-running operation into three phases:
67
+ * `createTask`, `getTask`, and `getTaskResult`.
68
+ *
69
+ * @see {@linkcode @modelcontextprotocol/server!experimental/tasks/mcpServer.ExperimentalMcpServerTasks#registerToolTask | registerToolTask} for registration.
70
+ * @experimental
71
+ */
72
+ interface ToolTaskHandler<Args extends StandardSchemaWithJSON | undefined = undefined> {
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
+ }
89
+ //#endregion
90
+ //#region src/experimental/tasks/mcpServer.d.ts
91
+ /**
92
+ * Experimental task features for {@linkcode McpServer}.
93
+ *
94
+ * Access via `server.experimental.tasks`:
95
+ * ```typescript
96
+ * server.experimental.tasks.registerToolTask('long-running', config, handler);
97
+ * ```
98
+ *
99
+ * @experimental
100
+ */
101
+ declare class ExperimentalMcpServerTasks {
102
+ private readonly _mcpServer;
103
+ constructor(_mcpServer: McpServer);
104
+ /**
105
+ * Registers a task-based tool with a config object and handler.
106
+ *
107
+ * Task-based tools support long-running operations that can be polled for status
108
+ * and results. The handler must implement {@linkcode ToolTaskHandler.createTask | createTask}, {@linkcode ToolTaskHandler.getTask | getTask}, and {@linkcode ToolTaskHandler.getTaskResult | getTaskResult}
109
+ * methods.
110
+ *
111
+ * @example
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
159
+ /**
160
+ * Experimental task features for low-level MCP servers.
161
+ *
162
+ * Access via `server.experimental.tasks`:
163
+ * ```typescript
164
+ * const stream = server.experimental.tasks.requestStream(request, options);
165
+ * ```
166
+ *
167
+ * For high-level server usage with task-based tools, use {@linkcode index.McpServer | McpServer}.experimental.tasks instead.
168
+ *
169
+ * @experimental
170
+ */
171
+ declare class ExperimentalServerTasks {
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
322
+ /**
323
+ * Extended tasks capability that includes runtime configuration (store, messageQueue).
324
+ * The runtime-only fields are stripped before advertising capabilities to clients.
325
+ */
326
+ type ServerTasksCapabilityWithRuntime = NonNullable<ServerCapabilities['tasks']> & TaskManagerOptions;
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
+ };
348
+ /**
349
+ * An MCP server on top of a pluggable transport.
350
+ *
351
+ * This server will automatically respond to the initialization flow as initiated from the client.
352
+ *
353
+ * @deprecated Use {@linkcode server/mcp.McpServer | McpServer} instead for the high-level API. Only use `Server` for advanced use cases.
354
+ */
355
+ declare class Server extends Protocol<ServerContext> {
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
+ }
483
+ //#endregion
484
+ //#region src/server/mcp.d.ts
485
+ /**
486
+ * High-level MCP server that provides a simpler API for working with resources, tools, and prompts.
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
+ * ```
497
+ */
498
+ declare class McpServer {
499
+ /**
500
+ * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications.
501
+ */
502
+ readonly server: Server;
503
+ private _registeredResources;
504
+ private _registeredResourceTemplates;
505
+ private _registeredTools;
506
+ private _registeredPrompts;
507
+ private _experimental?;
508
+ constructor(serverInfo: Implementation, options?: ServerOptions);
509
+ /**
510
+ * Access experimental features.
511
+ *
512
+ * WARNING: These APIs are experimental and may change without notice.
513
+ *
514
+ * @experimental
515
+ */
516
+ get experimental(): {
517
+ tasks: ExperimentalMcpServerTasks;
518
+ };
519
+ /**
520
+ * Attaches to the given transport, starts it, and starts listening for messages.
521
+ *
522
+ * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward.
523
+ *
524
+ * @example
525
+ * ```ts source="./mcp.examples.ts#McpServer_connect_stdio"
526
+ * const server = new McpServer({ name: 'my-server', version: '1.0.0' });
527
+ * const transport = new StdioServerTransport();
528
+ * await server.connect(transport);
529
+ * ```
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
+ *
541
+ * @param errorMessage - The error message.
542
+ * @returns The tool error result.
543
+ */
544
+ private createToolError;
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}.
572
+ *
573
+ * @example
574
+ * ```ts source="./mcp.examples.ts#McpServer_registerResource_static"
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
+ * ```
587
+ */
588
+ registerResource(name: string, uriOrTemplate: string, config: ResourceMetadata, readCallback: ReadResourceCallback): RegisteredResource;
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;
693
+ }
694
+ /**
695
+ * A callback to complete one variable within a resource template's URI template.
696
+ */
697
+ type CompleteResourceTemplateCallback = (value: string, context?: {
698
+ arguments?: Record<string, string>;
699
+ }) => string[] | Promise<string[]>;
700
+ /**
701
+ * A resource template combines a URI pattern with optional functionality to enumerate
702
+ * all resources matching that pattern.
703
+ */
704
+ declare class ResourceTemplate {
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;
723
+ /**
724
+ * Gets the list callback, if one was provided.
725
+ */
726
+ get listCallback(): ListResourcesCallback | undefined;
727
+ /**
728
+ * Gets the callback for completing a specific URI template variable, if one was provided.
729
+ */
730
+ completeCallback(variable: string): CompleteResourceTemplateCallback | undefined;
731
+ }
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
+ /**
773
+ * Additional, optional information for annotating a resource.
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).
865
+ *
866
+ * - Input host header may include a port (e.g. `localhost:3000`) or IPv6 brackets (e.g. `[::1]:3000`).
867
+ * - Allowlist items should be hostnames only (no ports). For IPv6, include brackets (e.g. `[::1]`).
868
+ */
869
+ declare function validateHostHeader(hostHeader: string | null | undefined, allowedHostnames: string[]): HostHeaderValidationResult;
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`.
886
+ *
887
+ * This transport is only available in Node.js environments.
888
+ *
889
+ * @example
890
+ * ```ts source="./stdio.examples.ts#StdioServerTransport_basicUsage"
891
+ * const server = new McpServer({ name: 'my-server', version: '1.0.0' });
892
+ * const transport = new StdioServerTransport();
893
+ * await server.connect(transport);
894
+ * ```
895
+ */
896
+ declare class StdioServerTransport implements Transport {
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
+ }
917
+ //#endregion
918
+ //#region src/server/streamableHttp.d.ts
919
+ type StreamId = string;
920
+ type EventId = string;
921
+ /**
922
+ * Interface for resumability support via event storage
923
+ */
924
+ interface EventStore {
925
+ /**
926
+ * Stores an event for later retrieval
927
+ * @param streamId ID of the stream the event belongs to
928
+ * @param message The JSON-RPC message to store
929
+ * @returns The generated event ID for the stored event
930
+ */
931
+ storeEvent(streamId: StreamId, message: JSONRPCMessage): Promise<EventId>;
932
+ /**
933
+ * Get the stream ID associated with a given event ID.
934
+ * @param eventId The event ID to look up
935
+ * @returns The stream ID, or `undefined` if not found
936
+ *
937
+ * Optional: If not provided, the SDK will use the `streamId` returned by
938
+ * {@linkcode replayEventsAfter} for stream mapping.
939
+ */
940
+ getStreamIdForEventId?(eventId: EventId): Promise<StreamId | undefined>;
941
+ replayEventsAfter(lastEventId: EventId, {
942
+ send
943
+ }: {
944
+ send: (eventId: EventId, message: JSONRPCMessage) => Promise<void>;
945
+ }): Promise<StreamId>;
946
+ }
947
+ /**
948
+ * Configuration options for {@linkcode WebStandardStreamableHTTPServerTransport}
949
+ */
950
+ interface WebStandardStreamableHTTPServerTransportOptions {
951
+ /**
952
+ * Function that generates a session ID for the transport.
953
+ * The session ID SHOULD be globally unique and cryptographically secure (e.g., a securely generated UUID, a JWT, or a cryptographic hash)
954
+ *
955
+ * If not provided, session management is disabled (stateless mode).
956
+ */
957
+ sessionIdGenerator?: () => string;
958
+ /**
959
+ * A callback for session initialization events
960
+ * This is called when the server initializes a new session.
961
+ * Useful in cases when you need to register multiple mcp sessions
962
+ * and need to keep track of them.
963
+ * @param sessionId The generated session ID
964
+ */
965
+ onsessioninitialized?: (sessionId: string) => void | Promise<void>;
966
+ /**
967
+ * A callback for session close events
968
+ * This is called when the server closes a session due to a `DELETE` request.
969
+ * Useful in cases when you need to clean up resources associated with the session.
970
+ * Note that this is different from the transport closing, if you are handling
971
+ * HTTP requests from multiple nodes you might want to close each
972
+ * {@linkcode WebStandardStreamableHTTPServerTransport} after a request is completed while still keeping the
973
+ * session open/running.
974
+ * @param sessionId The session ID that was closed
975
+ */
976
+ onsessionclosed?: (sessionId: string) => void | Promise<void>;
977
+ /**
978
+ * If `true`, the server will return JSON responses instead of starting an SSE stream.
979
+ * This can be useful for simple request/response scenarios without streaming.
980
+ * Default is `false` (SSE streams are preferred).
981
+ */
982
+ enableJsonResponse?: boolean;
983
+ /**
984
+ * Event store for resumability support
985
+ * If provided, resumability will be enabled, allowing clients to reconnect and resume messages
986
+ */
987
+ eventStore?: EventStore;
988
+ /**
989
+ * List of allowed `Host` header values for DNS rebinding protection.
990
+ * If not specified, host validation is disabled.
991
+ * @deprecated Use external middleware for host validation instead.
992
+ */
993
+ allowedHosts?: string[];
994
+ /**
995
+ * List of allowed `Origin` header values for DNS rebinding protection.
996
+ * If not specified, origin validation is disabled.
997
+ * @deprecated Use external middleware for origin validation instead.
998
+ */
999
+ allowedOrigins?: string[];
1000
+ /**
1001
+ * Enable DNS rebinding protection (requires `allowedHosts` and/or `allowedOrigins` to be configured).
1002
+ * Default is `false` for backwards compatibility.
1003
+ * @deprecated Use external middleware for DNS rebinding protection instead.
1004
+ */
1005
+ enableDnsRebindingProtection?: boolean;
1006
+ /**
1007
+ * Retry interval in milliseconds to suggest to clients in SSE `retry` field.
1008
+ * When set, the server will send a `retry` field in SSE priming events to control
1009
+ * client reconnection timing for polling behavior.
1010
+ */
1011
+ retryInterval?: number;
1012
+ /**
1013
+ * List of protocol versions that this transport will accept.
1014
+ * Used to validate the `mcp-protocol-version` header in incoming requests.
1015
+ *
1016
+ * Note: When using {@linkcode server/server.Server.connect | Server.connect()}, the server automatically passes its
1017
+ * `supportedProtocolVersions` to the transport, so you typically don't need
1018
+ * to set this option directly.
1019
+ *
1020
+ * @default {@linkcode SUPPORTED_PROTOCOL_VERSIONS}
1021
+ */
1022
+ supportedProtocolVersions?: string[];
1023
+ }
1024
+ /**
1025
+ * Options for handling a request
1026
+ */
1027
+ interface HandleRequestOptions {
1028
+ /**
1029
+ * Pre-parsed request body. If provided, the transport will use this instead of parsing `req.json()`.
1030
+ * Useful when using body-parser middleware that has already parsed the body.
1031
+ */
1032
+ parsedBody?: unknown;
1033
+ /**
1034
+ * Authentication info from middleware. If provided, will be passed to message handlers.
1035
+ */
1036
+ authInfo?: AuthInfo;
1037
+ }
1038
+ /**
1039
+ * Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification
1040
+ * using Web Standard APIs (`Request`, `Response`, `ReadableStream`).
1041
+ *
1042
+ * This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc.
1043
+ *
1044
+ * In stateful mode:
1045
+ * - Session ID is generated and included in response headers
1046
+ * - Session ID is always included in initialization responses
1047
+ * - Requests with invalid session IDs are rejected with `404 Not Found`
1048
+ * - Non-initialization requests without a session ID are rejected with `400 Bad Request`
1049
+ * - State is maintained in-memory (connections, message history)
1050
+ *
1051
+ * In stateless mode:
1052
+ * - No Session ID is included in any responses
1053
+ * - No session validation is performed
1054
+ *
1055
+ * @example Stateful setup
1056
+ * ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateful"
1057
+ * const server = new McpServer({ name: 'my-server', version: '1.0.0' });
1058
+ *
1059
+ * const transport = new WebStandardStreamableHTTPServerTransport({
1060
+ * sessionIdGenerator: () => crypto.randomUUID()
1061
+ * });
1062
+ *
1063
+ * await server.connect(transport);
1064
+ * ```
1065
+ *
1066
+ * @example Stateless setup
1067
+ * ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateless"
1068
+ * const transport = new WebStandardStreamableHTTPServerTransport({
1069
+ * sessionIdGenerator: undefined
1070
+ * });
1071
+ * ```
1072
+ *
1073
+ * @example Hono.js
1074
+ * ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_hono"
1075
+ * app.all('/mcp', async c => {
1076
+ * return transport.handleRequest(c.req.raw);
1077
+ * });
1078
+ * ```
1079
+ *
1080
+ * @example Cloudflare Workers
1081
+ * ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_workers"
1082
+ * const worker = {
1083
+ * async fetch(request: Request): Promise<Response> {
1084
+ * return transport.handleRequest(request);
1085
+ * }
1086
+ * };
1087
+ * ```
1088
+ */
1089
+ declare class WebStandardStreamableHTTPServerTransport implements Transport {
1090
+ private sessionIdGenerator;
1091
+ private _started;
1092
+ private _streamMapping;
1093
+ private _requestToStreamMapping;
1094
+ private _requestResponseMap;
1095
+ private _initialized;
1096
+ private _enableJsonResponse;
1097
+ private _standaloneSseStreamId;
1098
+ private _eventStore?;
1099
+ private _onsessioninitialized?;
1100
+ private _onsessionclosed?;
1101
+ private _allowedHosts?;
1102
+ private _allowedOrigins?;
1103
+ private _enableDnsRebindingProtection;
1104
+ private _retryInterval?;
1105
+ private _supportedProtocolVersions;
1106
+ sessionId?: string;
1107
+ onclose?: () => void;
1108
+ onerror?: (error: Error) => void;
1109
+ onmessage?: (message: JSONRPCMessage, extra?: MessageExtraInfo) => void;
1110
+ constructor(options?: WebStandardStreamableHTTPServerTransportOptions);
1111
+ /**
1112
+ * Starts the transport. This is required by the {@linkcode Transport} interface but is a no-op
1113
+ * for the Streamable HTTP transport as connections are managed per-request.
1114
+ */
1115
+ start(): Promise<void>;
1116
+ /**
1117
+ * Sets the supported protocol versions for header validation.
1118
+ * Called by the server during {@linkcode server/server.Server.connect | connect()} to pass its supported versions.
1119
+ */
1120
+ setSupportedProtocolVersions(versions: string[]): void;
1121
+ /**
1122
+ * Helper to create a JSON error response
1123
+ */
1124
+ private createJsonErrorResponse;
1125
+ /**
1126
+ * Validates request headers for DNS rebinding protection.
1127
+ * @returns Error response if validation fails, `undefined` if validation passes.
1128
+ */
1129
+ private validateRequestHeaders;
1130
+ /**
1131
+ * Handles an incoming HTTP request, whether `GET`, `POST`, or `DELETE`
1132
+ * Returns a `Response` object (Web Standard)
1133
+ */
1134
+ handleRequest(req: Request, options?: HandleRequestOptions): Promise<Response>;
1135
+ /**
1136
+ * Writes a priming event to establish resumption capability.
1137
+ * Only sends if `eventStore` is configured (opt-in for resumability) and
1138
+ * the client's protocol version supports empty SSE data (>= `2025-11-25`).
1139
+ */
1140
+ private writePrimingEvent;
1141
+ /**
1142
+ * Handles `GET` requests for SSE stream
1143
+ */
1144
+ private handleGetRequest;
1145
+ /**
1146
+ * Replays events that would have been sent after the specified event ID
1147
+ * Only used when resumability is enabled
1148
+ */
1149
+ private replayEvents;
1150
+ /**
1151
+ * Writes an event to an SSE stream via controller with proper formatting
1152
+ */
1153
+ private writeSSEEvent;
1154
+ /**
1155
+ * Handles unsupported requests (`PUT`, `PATCH`, etc.)
1156
+ */
1157
+ private handleUnsupportedRequest;
1158
+ /**
1159
+ * Handles `POST` requests containing JSON-RPC messages
1160
+ */
1161
+ private handlePostRequest;
1162
+ /**
1163
+ * Handles `DELETE` requests to terminate sessions
1164
+ */
1165
+ private handleDeleteRequest;
1166
+ /**
1167
+ * Validates session ID for non-initialization requests.
1168
+ * Returns `Response` error if invalid, `undefined` otherwise
1169
+ */
1170
+ private validateSession;
1171
+ /**
1172
+ * Validates the `MCP-Protocol-Version` header on incoming requests.
1173
+ *
1174
+ * For initialization: Version negotiation handles unknown versions gracefully
1175
+ * (server responds with its supported version).
1176
+ *
1177
+ * For subsequent requests with `MCP-Protocol-Version` header:
1178
+ * - Accept if in supported list
1179
+ * - 400 if unsupported
1180
+ *
1181
+ * For HTTP requests without the `MCP-Protocol-Version` header:
1182
+ * - Accept and default to the version negotiated at initialization
1183
+ */
1184
+ private validateProtocolVersion;
1185
+ close(): Promise<void>;
1186
+ /**
1187
+ * Close an SSE stream for a specific request, triggering client reconnection.
1188
+ * Use this to implement polling behavior during long-running operations -
1189
+ * client will reconnect after the retry interval specified in the priming event.
1190
+ */
1191
+ closeSSEStream(requestId: RequestId): void;
1192
+ /**
1193
+ * Close the standalone `GET` SSE stream, triggering client reconnection.
1194
+ * Use this to implement polling behavior for server-initiated notifications.
1195
+ */
1196
+ closeStandaloneSSEStream(): void;
1197
+ send(message: JSONRPCMessage, options?: {
1198
+ relatedRequestId?: RequestId;
1199
+ }): Promise<void>;
1200
+ }
1201
+ //#endregion
1202
+ //#region src/fromJsonSchema.d.ts
1203
+ declare function fromJsonSchema<T = unknown>(schema: JsonSchemaType, validator?: jsonSchemaValidator): StandardSchemaWithJSON<T, T>;
1204
+ //#endregion
1205
+ export { type AnyToolHandler, type BaseToolCallback, type CompletableSchema, type CompleteCallback, type CompleteResourceTemplateCallback, type CreateTaskRequestHandler, type EventId, type EventStore, ExperimentalMcpServerTasks, ExperimentalServerTasks, type HandleRequestOptions, type HostHeaderValidationResult, type ListResourcesCallback, McpServer, type PromptCallback, type ReadResourceCallback, type ReadResourceTemplateCallback, type RegisteredPrompt, type RegisteredResource, type RegisteredResourceTemplate, type RegisteredTool, type ResourceMetadata, ResourceTemplate, Server, type ServerOptions, StdioServerTransport, type StreamId, type TaskRequestHandler, type ToolCallback, type ToolTaskHandler, WebStandardStreamableHTTPServerTransport, type WebStandardStreamableHTTPServerTransportOptions, completable, fromJsonSchema, hostHeaderValidationResponse, isCompletable, localhostAllowedHostnames, validateHostHeader };
1206
+ //# sourceMappingURL=index.d.mts.map