mcpTypes.ts ×31

Frontier kind: Code frontier

unlabeled · c_6317a7bc5dcc

293 tests · 24234 LOC · 126 files · introduces 0 tests · 4652 LOC · 8 files

Introduces — evidence that enters the hierarchy at this concept

Code
104 ranges4652 lines · 8 files
Tests
0 tests

Contains — complete concept membership

All code (extent)
2509 ranges24234 lines · 126 files · Browse complete extent
All tests (intent)
293 testsBrowse complete intent

Neighbourhood graph

The orange circle is the focus. Violet and green circles are every ancestor and descendant, broader and narrower, at any distance; blue squares and pink diamonds are the introduced files and exact introduced tests of every visible concept, not only the focus's. Arrows point from broader to narrower concepts and bridge only concepts omitted from this view. Undirected links show source or test introduction. Concept and file size follows LOC; exact test nodes use test-count units.

Introduced files, introduced tests, and structurally relevant concept specialization

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the native relationship evidence on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the native relationship evidence on this page while the interactive map is unavailable.

Native relationship evidence

Every exact file and test below is linked only from the concept that introduces it.

Introduced tests

Every collected test enters the hierarchy at exactly one concept.

No tests are introduced at this concept. Its intent tests are introduced by other concepts.

Introduced code

Every collected source range enters the hierarchy at exactly one concept.

8 files ranked by introduced lines: 4652 introduced LOC across 104 ranges. Expand a file to inspect source; the > gutter marks introduced lines.

src/vs/platform/mcp/common/modelContextProtocol.ts 3277 introduced LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- modelContextProtocol.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > /* eslint-disable local/code-no-unexternalized-strings */
7 >
8 > //#region proposals
9 > /**
10 > * MCP protocol proposals.
11 > * - Proposals here MUST have an MCP PR linked to them
12 > * - Proposals here are subject to change and SHALL be removed when
13 > * the upstream MCP PR is merged or closed.
14 > */
15 > export namespace MCP {
16 >
17 > // Nothing, yet
18 >
19 > }
20 >
21 > //#endregion
22 >
23 > /**
24 > * Schema updated from the Model Context Protocol repository at
25 > * https://github.com/modelcontextprotocol/specification/tree/main/schema
26 > *
27 > * ⚠️ Do not edit within `namespace` manually except to update schema versions ⚠️
28 > */
29 > export namespace MCP {
30 > /* JSON-RPC types */
31 >
32 > /**
33 > * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent.
34 > *
35 > * @category JSON-RPC
36 > */
37 > export type JSONRPCMessage =
38 > | JSONRPCRequest
39 > | JSONRPCNotification
40 > | JSONRPCResponse;
41 >
42 > /** @internal */
43 > export const LATEST_PROTOCOL_VERSION = "2025-11-25";
44 > /** @internal */
45 > export const JSONRPC_VERSION = "2.0";
46 >
47 > /**
48 > * Represents the contents of a `_meta` field, which clients and servers use to attach additional metadata to their interactions.
49 > *
50 > * Certain key names are reserved by MCP for protocol-level metadata; implementations MUST NOT make assumptions about values at these keys. Additionally, specific schema definitions may reserve particular names for purpose-specific metadata, as declared in those definitions.
51 > *
52 > * Valid keys have two segments:
53 > *
54 > * **Prefix:**
55 > * - Optional - if specified, MUST be a series of _labels_ separated by dots (`.`), followed by a slash (`/`).
56 > * - Labels MUST start with a letter and end with a letter or digit. Interior characters may be letters, digits, or hyphens (`-`).
57 > * - Any prefix consisting of zero or more labels, followed by `modelcontextprotocol` or `mcp`, followed by any label, is **reserved** for MCP use. For example: `modelcontextprotocol.io/`, `mcp.dev/`, `api.modelcontextprotocol.org/`, and `tools.mcp.com/` are all reserved.
58 > *
59 > * **Name:**
60 > * - Unless empty, MUST start and end with an alphanumeric character (`[a-z0-9A-Z]`).
61 > * - Interior characters may be alphanumeric, hyphens (`-`), underscores (`_`), or dots (`.`).
62 > *
63 > * @see [General fields: `_meta`](/specification/draft/basic/index#meta) for more details.
64 > * @category Common Types
65 > */
66 > export type MetaObject = Record<string, unknown>;
67 >
68 > /**
69 > * Extends {@link MetaObject} with additional request-specific fields. All key naming rules from `MetaObject` apply.
70 > *
71 > * @see {@link MetaObject} for key naming rules and reserved prefixes.
72 > * @see [General fields: `_meta`](/specification/draft/basic/index#meta) for more details.
73 > * @category Common Types
74 > */
75 > export interface RequestMetaObject extends MetaObject {
76 > /**
77 > * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by {@link ProgressNotification | notifications/progress}). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
78 > */
79 > progressToken?: ProgressToken;
80 > }
81 >
82 > /**
83 > * A progress token, used to associate progress notifications with the original request.
84 > *
85 > * @category Common Types
86 > */
87 > export type ProgressToken = string | number;
88 >
89 > /**
90 > * An opaque token used to represent a cursor for pagination.
91 > *
92 > * @category Common Types
93 > */
94 > export type Cursor = string;
95 >
96 > /**
97 > * Common params for any task-augmented request.
98 > *
99 > * @internal
100 > */
101 > export interface TaskAugmentedRequestParams extends RequestParams {
102 > /**
103 > * If specified, the caller is requesting task-augmented execution for this request.
104 > * The request will return a {@link CreateTaskResult} immediately, and the actual result can be
105 > * retrieved later via {@link GetTaskPayloadRequest | tasks/result}.
106 > *
107 > * Task augmentation is subject to capability negotiation - receivers MUST declare support
108 > * for task augmentation of specific request types in their capabilities.
109 > */
110 > task?: TaskMetadata;
111 > }
112 >
113 > /**
114 > * Common params for any request.
115 > *
116 > * @category Common Types
117 > */
118 > export interface RequestParams {
119 > _meta?: RequestMetaObject;
120 > }
121 >
122 > /** @internal */
123 > export interface Request {
124 > method: string;
125 > // Allow unofficial extensions of `Request.params` without impacting `RequestParams`.
126 > // eslint-disable-next-line @typescript-eslint/no-explicit-any
127 > params?: { [key: string]: any };
128 > }
129 >
130 > /**
131 > * Common params for any notification.
132 > *
133 > * @category Common Types
134 > */
135 > export interface NotificationParams {
136 > _meta?: MetaObject;
137 > }
138 >
139 > /** @internal */
140 > export interface Notification {
141 > method: string;
142 > // Allow unofficial extensions of `Notification.params` without impacting `NotificationParams`.
143 > // eslint-disable-next-line @typescript-eslint/no-explicit-any
144 > params?: { [key: string]: any };
145 > }
146 >
147 > /**
148 > * Common result fields.
149 > *
150 > * @category Common Types
151 > */
152 > export interface Result {
153 > _meta?: MetaObject;
154 > [key: string]: unknown;
155 > }
156 >
157 > /**
158 > * @category Errors
159 > */
160 > export interface Error {
161 > /**
162 > * The error type that occurred.
163 > */
164 > code: number;
165 > /**
166 > * A short description of the error. The message SHOULD be limited to a concise single sentence.
167 > */
168 > message: string;
169 > /**
170 > * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
171 > */
172 > data?: unknown;
173 > }
174 >
175 > /**
176 > * A uniquely identifying ID for a request in JSON-RPC.
177 > *
178 > * @category Common Types
179 > */
180 > export type RequestId = string | number;
181 >
182 > /**
183 > * A request that expects a response.
184 > *
185 > * @category JSON-RPC
186 > */
187 > export interface JSONRPCRequest extends Request {
188 > jsonrpc: typeof JSONRPC_VERSION;
189 > id: RequestId;
190 > }
191 >
192 > /**
193 > * A notification which does not expect a response.
194 > *
195 > * @category JSON-RPC
196 > */
197 > export interface JSONRPCNotification extends Notification {
198 > jsonrpc: typeof JSONRPC_VERSION;
199 > }
200 >
201 > /**
202 > * A successful (non-error) response to a request.
203 > *
204 > * @category JSON-RPC
205 > */
206 > export interface JSONRPCResultResponse {
207 > jsonrpc: typeof JSONRPC_VERSION;
208 > id: RequestId;
209 > result: Result;
210 > }
211 >
212 > /**
213 > * A response to a request that indicates an error occurred.
214 > *
215 > * @category JSON-RPC
216 > */
217 > export interface JSONRPCErrorResponse {
218 > jsonrpc: typeof JSONRPC_VERSION;
219 > id?: RequestId;
220 > error: Error;
221 > }
222 >
223 > /**
224 > * A response to a request, containing either the result or error.
225 > *
226 > * @category JSON-RPC
227 > */
228 > export type JSONRPCResponse = JSONRPCResultResponse | JSONRPCErrorResponse;
229 >
230 > // Standard JSON-RPC error codes
231 > export const PARSE_ERROR = -32700;
232 > export const INVALID_REQUEST = -32600;
233 > export const METHOD_NOT_FOUND = -32601;
234 > export const INVALID_PARAMS = -32602;
235 > export const INTERNAL_ERROR = -32603;
236 >
237 > /**
238 > * A JSON-RPC error indicating that invalid JSON was received by the server. This error is returned when the server cannot parse the JSON text of a message.
239 > *
240 > * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object}
241 > *
242 > * @example Invalid JSON
243 > * {@includeCode ./examples/ParseError/invalid-json.json}
244 > *
245 > * @category Errors
246 > */
247 > export interface ParseError extends Error {
248 > code: typeof PARSE_ERROR;
249 > }
250 >
251 > /**
252 > * A JSON-RPC error indicating that the request is not a valid request object. This error is returned when the message structure does not conform to the JSON-RPC 2.0 specification requirements for a request (e.g., missing required fields like `jsonrpc` or `method`, or using invalid types for these fields).
253 > *
254 > * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object}
255 > *
256 > * @category Errors
257 > */
258 > export interface InvalidRequestError extends Error {
259 > code: typeof INVALID_REQUEST;
260 > }
261 >
262 > /**
263 > * A JSON-RPC error indicating that the requested method does not exist or is not available.
264 > *
265 > * In MCP, this error is returned when a request is made for a method that requires a capability that has not been declared. This can occur in either direction:
266 > *
267 > * - A server returning this error when the client requests a capability it doesn't support (e.g., requesting completions when the `completions` capability was not advertised)
268 > * - A client returning this error when the server requests a capability it doesn't support (e.g., requesting roots when the client did not declare the `roots` capability)
269 > *
270 > * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object}
271 > *
272 > * @example Roots not supported
273 > * {@includeCode ./examples/MethodNotFoundError/roots-not-supported.json}
274 > *
275 > * @category Errors
276 > */
277 > export interface MethodNotFoundError extends Error {
278 > code: typeof METHOD_NOT_FOUND;
279 > }
280 >
281 > /**
282 > * A JSON-RPC error indicating that the method parameters are invalid or malformed.
283 > *
284 > * In MCP, this error is returned in various contexts when request parameters fail validation:
285 > *
286 > * - **Tools**: Unknown tool name or invalid tool arguments
287 > * - **Prompts**: Unknown prompt name or missing required arguments
288 > * - **Pagination**: Invalid or expired cursor values
289 > * - **Logging**: Invalid log level
290 > * - **Tasks**: Invalid or nonexistent task ID, invalid cursor, or attempting to cancel a task already in a terminal status
291 > * - **Elicitation**: Server requests an elicitation mode not declared in client capabilities
292 > * - **Sampling**: Missing tool result or tool results mixed with other content
293 > *
294 > * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object}
295 > *
296 > * @example Unknown tool
297 > * {@includeCode ./examples/InvalidParamsError/unknown-tool.json}
298 > *
299 > * @example Invalid tool arguments
300 > * {@includeCode ./examples/InvalidParamsError/invalid-tool-arguments.json}
301 > *
302 > * @example Unknown prompt
303 > * {@includeCode ./examples/InvalidParamsError/unknown-prompt.json}
304 > *
305 > * @example Invalid cursor
306 > * {@includeCode ./examples/InvalidParamsError/invalid-cursor.json}
307 > *
308 > * @category Errors
309 > */
310 > export interface InvalidParamsError extends Error {
311 > code: typeof INVALID_PARAMS;
312 > }
313 >
314 > /**
315 > * A JSON-RPC error indicating that an internal error occurred on the receiver. This error is returned when the receiver encounters an unexpected condition that prevents it from fulfilling the request.
316 > *
317 > * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object}
318 > *
319 > * @example Unexpected error
320 > * {@includeCode ./examples/InternalError/unexpected-error.json}
321 > *
322 > * @category Errors
323 > */
324 > export interface InternalError extends Error {
325 > code: typeof INTERNAL_ERROR;
326 > }
327 >
328 > // Implementation-specific JSON-RPC error codes [-32000, -32099]
329 > /** @internal */
330 > export const URL_ELICITATION_REQUIRED = -32042;
331 >
332 > /**
333 > * An error response that indicates that the server requires the client to provide additional information via an elicitation request.
334 > *
335 > * @example Authorization required
336 > * {@includeCode ./examples/URLElicitationRequiredError/authorization-required.json}
337 > *
338 > * @internal
339 > */
340 > export interface URLElicitationRequiredError extends Omit<
341 > JSONRPCErrorResponse,
342 > "error"
343 > > {
344 > error: Error & {
345 > code: typeof URL_ELICITATION_REQUIRED;
346 > data: {
347 > elicitations: ElicitRequestURLParams[];
348 > [key: string]: unknown;
349 > };
350 > };
351 > }
352 >
353 > /* Empty result */
354 > /**
355 > * A result that indicates success but carries no data.
356 > *
357 > * @category Common Types
358 > */
359 > export type EmptyResult = Result;
360 >
361 > /* Cancellation */
362 > /**
363 > * Parameters for a `notifications/cancelled` notification.
364 > *
365 > * @example User-requested cancellation
366 > * {@includeCode ./examples/CancelledNotificationParams/user-requested-cancellation.json}
367 > *
368 > * @category `notifications/cancelled`
369 > */
370 > export interface CancelledNotificationParams extends NotificationParams {
371 > /**
372 > * The ID of the request to cancel.
373 > *
374 > * This MUST correspond to the ID of a request previously issued in the same direction.
375 > * This MUST be provided for cancelling non-task requests.
376 > * This MUST NOT be used for cancelling tasks (use the {@link CancelTaskRequest | tasks/cancel} request instead).
377 > */
378 > requestId?: RequestId;
379 >
380 > /**
381 > * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
382 > */
383 > reason?: string;
384 > }
385 >
386 > /**
387 > * This notification can be sent by either side to indicate that it is cancelling a previously-issued request.
388 > *
389 > * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.
390 > *
391 > * This notification indicates that the result will be unused, so any associated processing SHOULD cease.
392 > *
393 > * A client MUST NOT attempt to cancel its `initialize` request.
394 > *
395 > * For task cancellation, use the {@link CancelTaskRequest | tasks/cancel} request instead of this notification.
396 > *
397 > * @example User-requested cancellation
398 > * {@includeCode ./examples/CancelledNotification/user-requested-cancellation.json}
399 > *
400 > * @category `notifications/cancelled`
401 > */
402 > export interface CancelledNotification extends JSONRPCNotification {
403 > method: "notifications/cancelled";
404 > params: CancelledNotificationParams;
405 > }
406 >
407 > /* Initialization */
408 > /**
409 > * Parameters for an `initialize` request.
410 > *
411 > * @example Full client capabilities
412 > * {@includeCode ./examples/InitializeRequestParams/full-client-capabilities.json}
413 > *
414 > * @category `initialize`
415 > */
416 > export interface InitializeRequestParams extends RequestParams {
417 > /**
418 > * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
419 > */
420 > protocolVersion: string;
421 > capabilities: ClientCapabilities;
422 > clientInfo: Implementation;
423 > }
424 >
425 > /**
426 > * This request is sent from the client to the server when it first connects, asking it to begin initialization.
427 > *
428 > * @example Initialize request
429 > * {@includeCode ./examples/InitializeRequest/initialize-request.json}
430 > *
431 > * @category `initialize`
432 > */
433 > export interface InitializeRequest extends JSONRPCRequest {
434 > method: "initialize";
435 > params: InitializeRequestParams;
436 > }
437 >
438 > /**
439 > * The result returned by the server for an {@link InitializeRequest | initialize} request.
440 > *
441 > * @example Full server capabilities
442 > * {@includeCode ./examples/InitializeResult/full-server-capabilities.json}
443 > *
444 > * @category `initialize`
445 > */
446 > export interface InitializeResult extends Result {
447 > /**
448 > * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.
449 > */
450 > protocolVersion: string;
451 > capabilities: ServerCapabilities;
452 > serverInfo: Implementation;
453 >
454 > /**
455 > * Instructions describing how to use the server and its features.
456 > *
457 > * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.
458 > */
459 > instructions?: string;
460 > }
461 >
462 > /**
463 > * A successful response from the server for a {@link InitializeRequest | initialize} request.
464 > *
465 > * @example Initialize result response
466 > * {@includeCode ./examples/InitializeResultResponse/initialize-result-response.json}
467 > *
468 > * @category `initialize`
469 > */
470 > export interface InitializeResultResponse extends JSONRPCResultResponse {
471 > result: InitializeResult;
472 > }
473 >
474 > /**
475 > * This notification is sent from the client to the server after initialization has finished.
476 > *
477 > * @example Initialized notification
478 > * {@includeCode ./examples/InitializedNotification/initialized-notification.json}
479 > *
480 > * @category `notifications/initialized`
481 > */
482 > export interface InitializedNotification extends JSONRPCNotification {
483 > method: "notifications/initialized";
484 > params?: NotificationParams;
485 > }
486 >
487 > /**
488 > * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities.
489 > *
490 > * @category `initialize`
491 > */
492 > export interface ClientCapabilities {
493 > /**
494 > * Experimental, non-standard capabilities that the client supports.
495 > */
496 > experimental?: { [key: string]: object };
497 > /**
498 > * Present if the client supports listing roots.
499 > *
500 > * @example Roots - minimum baseline support
501 > * {@includeCode ./examples/ClientCapabilities/roots-minimum-baseline-support.json}
502 > *
503 > * @example Roots - list changed notifications
504 > * {@includeCode ./examples/ClientCapabilities/roots-list-changed-notifications.json}
505 > */
506 > roots?: {
507 > /**
508 > * Whether the client supports notifications for changes to the roots list.
509 > */
510 > listChanged?: boolean;
511 > };
512 > /**
513 > * Present if the client supports sampling from an LLM.
514 > *
515 > * @example Sampling - minimum baseline support
516 > * {@includeCode ./examples/ClientCapabilities/sampling-minimum-baseline-support.json}
517 > *
518 > * @example Sampling - tool use support
519 > * {@includeCode ./examples/ClientCapabilities/sampling-tool-use-support.json}
520 > *
521 > * @example Sampling - context inclusion support (soft-deprecated)
522 > * {@includeCode ./examples/ClientCapabilities/sampling-context-inclusion-support-soft-deprecated.json}
523 > */
524 > sampling?: {
525 > /**
526 > * Whether the client supports context inclusion via `includeContext` parameter.
527 > * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).
528 > */
529 > context?: object;
530 > /**
531 > * Whether the client supports tool use via `tools` and `toolChoice` parameters.
532 > */
533 > tools?: object;
534 > };
535 > /**
536 > * Present if the client supports elicitation from the server.
537 > *
538 > * @example Elicitation - form and URL mode support
539 > * {@includeCode ./examples/ClientCapabilities/elicitation-form-and-url-mode-support.json}
540 > *
541 > * @example Elicitation - form mode only (implicit)
542 > * {@includeCode ./examples/ClientCapabilities/elicitation-form-only-implicit.json}
543 > */
544 > elicitation?: { form?: object; url?: object };
545 >
546 > /**
547 > * Present if the client supports task-augmented requests.
548 > */
549 > tasks?: {
550 > /**
551 > * Whether this client supports {@link ListTasksRequest | tasks/list}.
552 > */
553 > list?: object;
554 > /**
555 > * Whether this client supports {@link CancelTaskRequest | tasks/cancel}.
556 > */
557 > cancel?: object;
558 > /**
559 > * Specifies which request types can be augmented with tasks.
560 > */
561 > requests?: {
562 > /**
563 > * Task support for sampling-related requests.
564 > */
565 > sampling?: {
566 > /**
567 > * Whether the client supports task-augmented `sampling/createMessage` requests.
568 > */
569 > createMessage?: object;
570 > };
571 > /**
572 > * Task support for elicitation-related requests.
573 > */
574 > elicitation?: {
575 > /**
576 > * Whether the client supports task-augmented {@link ElicitRequest | elicitation/create} requests.
577 > */
578 > create?: object;
579 > };
580 > };
581 > };
582 > /**
583 > * Optional MCP extensions that the client supports. Keys are extension identifiers
584 > * (e.g., "io.modelcontextprotocol/oauth-client-credentials"), and values are
585 > * per-extension settings objects. An empty object indicates support with no settings.
586 > *
587 > * @example Extensions - UI extension with MIME type support
588 > * {@includeCode ./examples/ClientCapabilities/extensions-ui-mime-types.json}
589 > */
590 > extensions?: { [key: string]: object };
591 > }
592 >
593 > /**
594 > * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities.
595 > *
596 > * @category `initialize`
597 > */
598 > export interface ServerCapabilities {
599 > /**
600 > * Experimental, non-standard capabilities that the server supports.
601 > */
602 > experimental?: { [key: string]: object };
603 > /**
604 > * Present if the server supports sending log messages to the client.
605 > *
606 > * @example Logging - minimum baseline support
607 > * {@includeCode ./examples/ServerCapabilities/logging-minimum-baseline-support.json}
608 > */
609 > logging?: object;
610 > /**
611 > * Present if the server supports argument autocompletion suggestions.
612 > *
613 > * @example Completions - minimum baseline support
614 > * {@includeCode ./examples/ServerCapabilities/completions-minimum-baseline-support.json}
615 > */
616 > completions?: object;
617 > /**
618 > * Present if the server offers any prompt templates.
619 > *
620 > * @example Prompts - minimum baseline support
621 > * {@includeCode ./examples/ServerCapabilities/prompts-minimum-baseline-support.json}
622 > *
623 > * @example Prompts - list changed notifications
624 > * {@includeCode ./examples/ServerCapabilities/prompts-list-changed-notifications.json}
625 > */
626 > prompts?: {
627 > /**
628 > * Whether this server supports notifications for changes to the prompt list.
629 > */
630 > listChanged?: boolean;
631 > };
632 > /**
633 > * Present if the server offers any resources to read.
634 > *
635 > * @example Resources - minimum baseline support
636 > * {@includeCode ./examples/ServerCapabilities/resources-minimum-baseline-support.json}
637 > *
638 > * @example Resources - subscription to individual resource updates (only)
639 > * {@includeCode ./examples/ServerCapabilities/resources-subscription-to-individual-resource-updates-only.json}
640 > *
641 > * @example Resources - list changed notifications (only)
642 > * {@includeCode ./examples/ServerCapabilities/resources-list-changed-notifications-only.json}
643 > *
644 > * @example Resources - all notifications
645 > * {@includeCode ./examples/ServerCapabilities/resources-all-notifications.json}
646 > */
647 > resources?: {
648 > /**
649 > * Whether this server supports subscribing to resource updates.
650 > */
651 > subscribe?: boolean;
652 > /**
653 > * Whether this server supports notifications for changes to the resource list.
654 > */
655 > listChanged?: boolean;
656 > };
657 > /**
658 > * Present if the server offers any tools to call.
659 > *
660 > * @example Tools - minimum baseline support
661 > * {@includeCode ./examples/ServerCapabilities/tools-minimum-baseline-support.json}
662 > *
663 > * @example Tools - list changed notifications
664 > * {@includeCode ./examples/ServerCapabilities/tools-list-changed-notifications.json}
665 > */
666 > tools?: {
667 > /**
668 > * Whether this server supports notifications for changes to the tool list.
669 > */
670 > listChanged?: boolean;
671 > };
672 > /**
673 > * Present if the server supports task-augmented requests.
674 > */
675 > tasks?: {
676 > /**
677 > * Whether this server supports {@link ListTasksRequest | tasks/list}.
678 > */
679 > list?: object;
680 > /**
681 > * Whether this server supports {@link CancelTaskRequest | tasks/cancel}.
682 > */
683 > cancel?: object;
684 > /**
685 > * Specifies which request types can be augmented with tasks.
686 > */
687 > requests?: {
688 > /**
689 > * Task support for tool-related requests.
690 > */
691 > tools?: {
692 > /**
693 > * Whether the server supports task-augmented {@link CallToolRequest | tools/call} requests.
694 > */
695 > call?: object;
696 > };
697 > };
698 > };
699 > /**
700 > * Optional MCP extensions that the server supports. Keys are extension identifiers
701 > * (e.g., "io.modelcontextprotocol/apps"), and values are per-extension settings
702 > * objects. An empty object indicates support with no settings.
703 > *
704 > * @example Extensions - UI extension support
705 > * {@includeCode ./examples/ServerCapabilities/extensions-ui.json}
706 > */
707 > extensions?: { [key: string]: object };
708 > }
709 >
710 > /**
711 > * An optionally-sized icon that can be displayed in a user interface.
712 > *
713 > * @category Common Types
714 > */
715 > export interface Icon {
716 > /**
717 > * A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a
718 > * `data:` URI with Base64-encoded image data.
719 > *
720 > * Consumers SHOULD take steps to ensure URLs serving icons are from the
721 > * same domain as the client/server or a trusted domain.
722 > *
723 > * Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain
724 > * executable JavaScript.
725 > *
726 > * @format uri
727 > */
728 > src: string;
729 >
730 > /**
731 > * Optional MIME type override if the source MIME type is missing or generic.
732 > * For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`.
733 > */
734 > mimeType?: string;
735 >
736 > /**
737 > * Optional array of strings that specify sizes at which the icon can be used.
738 > * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.
739 > *
740 > * If not provided, the client should assume that the icon can be used at any size.
741 > */
742 > sizes?: string[];
743 >
744 > /**
745 > * Optional specifier for the theme this icon is designed for. `"light"` indicates
746 > * the icon is designed to be used with a light background, and `"dark"` indicates
747 > * the icon is designed to be used with a dark background.
748 > *
749 > * If not provided, the client should assume the icon can be used with any theme.
750 > */
751 > theme?: "light" | "dark";
752 > }
753 >
754 > /**
755 > * Base interface to add `icons` property.
756 > *
757 > * @internal
758 > */
759 > export interface Icons {
760 > /**
761 > * Optional set of sized icons that the client can display in a user interface.
762 > *
763 > * Clients that support rendering icons MUST support at least the following MIME types:
764 > * - `image/png` - PNG images (safe, universal compatibility)
765 > * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)
766 > *
767 > * Clients that support rendering icons SHOULD also support:
768 > * - `image/svg+xml` - SVG images (scalable but requires security precautions)
769 > * - `image/webp` - WebP images (modern, efficient format)
770 > */
771 > icons?: Icon[];
772 > }
773 >
774 > /**
775 > * Base interface for metadata with name (identifier) and title (display name) properties.
776 > *
777 > * @internal
778 > */
779 > export interface BaseMetadata {
780 > /**
781 > * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).
782 > */
783 > name: string;
784 >
785 > /**
786 > * Intended for UI and end-user contexts - optimized to be human-readable and easily understood,
787 > * even by those unfamiliar with domain-specific terminology.
788 > *
789 > * If not provided, the name should be used for display (except for {@link Tool},
790 > * where `annotations.title` should be given precedence over using `name`,
791 > * if present).
792 > */
793 > title?: string;
794 > }
795 >
796 > /**
797 > * Describes the MCP implementation.
798 > *
799 > * @category `initialize`
800 > */
801 > export interface Implementation extends BaseMetadata, Icons {
802 > /**
803 > * The version of this implementation.
804 > */
805 > version: string;
806 >
807 > /**
808 > * An optional human-readable description of what this implementation does.
809 > *
810 > * This can be used by clients or servers to provide context about their purpose
811 > * and capabilities. For example, a server might describe the types of resources
812 > * or tools it provides, while a client might describe its intended use case.
813 > */
814 > description?: string;
815 >
816 > /**
817 > * An optional URL of the website for this implementation.
818 > *
819 > * @format uri
820 > */
821 > websiteUrl?: string;
822 > }
823 >
824 > /* Ping */
825 > /**
826 > * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected.
827 > *
828 > * @example Ping request
829 > * {@includeCode ./examples/PingRequest/ping-request.json}
830 > *
831 > * @category `ping`
832 > */
833 > export interface PingRequest extends JSONRPCRequest {
834 > method: "ping";
835 > params?: RequestParams;
836 > }
837 >
838 > /**
839 > * A successful response for a {@link PingRequest | ping} request.
840 > *
841 > * @example Ping result response
842 > * {@includeCode ./examples/PingResultResponse/ping-result-response.json}
843 > *
844 > * @category `ping`
845 > */
846 > export interface PingResultResponse extends JSONRPCResultResponse {
847 > result: EmptyResult;
848 > }
849 >
850 > /* Progress notifications */
851 >
852 > /**
853 > * Parameters for a {@link ProgressNotification | notifications/progress} notification.
854 > *
855 > * @example Progress message
856 > * {@includeCode ./examples/ProgressNotificationParams/progress-message.json}
857 > *
858 > * @category `notifications/progress`
859 > */
860 > export interface ProgressNotificationParams extends NotificationParams {
861 > /**
862 > * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
863 > */
864 > progressToken: ProgressToken;
865 > /**
866 > * The progress thus far. This should increase every time progress is made, even if the total is unknown.
867 > *
868 > * @TJS-type number
869 > */
870 > progress: number;
871 > /**
872 > * Total number of items to process (or total progress required), if known.
873 > *
874 > * @TJS-type number
875 > */
876 > total?: number;
877 > /**
878 > * An optional message describing the current progress.
879 > */
880 > message?: string;
881 > }
882 >
883 > /**
884 > * An out-of-band notification used to inform the receiver of a progress update for a long-running request.
885 > *
886 > * @example Progress message
887 > * {@includeCode ./examples/ProgressNotification/progress-message.json}
888 > *
889 > * @category `notifications/progress`
890 > */
891 > export interface ProgressNotification extends JSONRPCNotification {
892 > method: "notifications/progress";
893 > params: ProgressNotificationParams;
894 > }
895 >
896 > /* Pagination */
897 > /**
898 > * Common params for paginated requests.
899 > *
900 > * @example List request with cursor
901 > * {@includeCode ./examples/PaginatedRequestParams/list-with-cursor.json}
902 > *
903 > * @category Common Types
904 > */
905 > export interface PaginatedRequestParams extends RequestParams {
906 > /**
907 > * An opaque token representing the current pagination position.
908 > * If provided, the server should return results starting after this cursor.
909 > */
910 > cursor?: Cursor;
911 > }
912 >
913 > /** @internal */
914 > export interface PaginatedRequest extends JSONRPCRequest {
915 > params?: PaginatedRequestParams;
916 > }
917 >
918 > /** @internal */
919 > export interface PaginatedResult extends Result {
920 > /**
921 > * An opaque token representing the pagination position after the last returned result.
922 > * If present, there may be more results available.
923 > */
924 > nextCursor?: Cursor;
925 > }
926 >
927 > /* Resources */
928 > /**
929 > * Sent from the client to request a list of resources the server has.
930 > *
931 > * @example List resources request
932 > * {@includeCode ./examples/ListResourcesRequest/list-resources-request.json}
933 > *
934 > * @category `resources/list`
935 > */
936 > export interface ListResourcesRequest extends PaginatedRequest {
937 > method: "resources/list";
938 > }
939 >
940 > /**
941 > * The result returned by the server for a {@link ListResourcesRequest | resources/list} request.
942 > *
943 > * @example Resources list with cursor
944 > * {@includeCode ./examples/ListResourcesResult/resources-list-with-cursor.json}
945 > *
946 > * @category `resources/list`
947 > */
948 > export interface ListResourcesResult extends PaginatedResult {
949 > resources: Resource[];
950 > }
951 >
952 > /**
953 > * A successful response from the server for a {@link ListResourcesRequest | resources/list} request.
954 > *
955 > * @example List resources result response
956 > * {@includeCode ./examples/ListResourcesResultResponse/list-resources-result-response.json}
957 > *
958 > * @category `resources/list`
959 > */
960 > export interface ListResourcesResultResponse extends JSONRPCResultResponse {
961 > result: ListResourcesResult;
962 > }
963 >
964 > /**
965 > * Sent from the client to request a list of resource templates the server has.
966 > *
967 > * @example List resource templates request
968 > * {@includeCode ./examples/ListResourceTemplatesRequest/list-resource-templates-request.json}
969 > *
970 > * @category `resources/templates/list`
971 > */
972 > export interface ListResourceTemplatesRequest extends PaginatedRequest {
973 > method: "resources/templates/list";
974 > }
975 >
976 > /**
977 > * The result returned by the server for a {@link ListResourceTemplatesRequest | resources/templates/list} request.
978 > *
979 > * @example Resource templates list
980 > * {@includeCode ./examples/ListResourceTemplatesResult/resource-templates-list.json}
981 > *
982 > * @category `resources/templates/list`
983 > */
984 > export interface ListResourceTemplatesResult extends PaginatedResult {
985 > resourceTemplates: ResourceTemplate[];
986 > }
987 >
988 > /**
989 > * A successful response from the server for a {@link ListResourceTemplatesRequest | resources/templates/list} request.
990 > *
991 > * @example List resource templates result response
992 > * {@includeCode ./examples/ListResourceTemplatesResultResponse/list-resource-templates-result-response.json}
993 > *
994 > * @category `resources/templates/list`
995 > */
996 > export interface ListResourceTemplatesResultResponse extends JSONRPCResultResponse {
997 > result: ListResourceTemplatesResult;
998 > }
999 >
1000 > /**
1001 > * Common params for resource-related requests.
1002 > *
1003 > * @internal
1004 > */
1005 > export interface ResourceRequestParams extends RequestParams {
1006 > /**
1007 > * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it.
1008 > *
1009 > * @format uri
1010 > */
1011 > uri: string;
1012 > }
1013 >
1014 > /**
1015 > * Parameters for a `resources/read` request.
1016 > *
1017 > * @category `resources/read`
1018 > */
1019 > export interface ReadResourceRequestParams extends ResourceRequestParams { }
1020 >
1021 > /**
1022 > * Sent from the client to the server, to read a specific resource URI.
1023 > *
1024 > * @example Read resource request
1025 > * {@includeCode ./examples/ReadResourceRequest/read-resource-request.json}
1026 > *
1027 > * @category `resources/read`
1028 > */
1029 > export interface ReadResourceRequest extends JSONRPCRequest {
1030 > method: "resources/read";
1031 > params: ReadResourceRequestParams;
1032 > }
1033 >
1034 > /**
1035 > * The result returned by the server for a {@link ReadResourceRequest | resources/read} request.
1036 > *
1037 > * @example File resource contents
1038 > * {@includeCode ./examples/ReadResourceResult/file-resource-contents.json}
1039 > *
1040 > * @category `resources/read`
1041 > */
1042 > export interface ReadResourceResult extends Result {
1043 > contents: (TextResourceContents | BlobResourceContents)[];
1044 > }
1045 >
1046 > /**
1047 > * A successful response from the server for a {@link ReadResourceRequest | resources/read} request.
1048 > *
1049 > * @example Read resource result response
1050 > * {@includeCode ./examples/ReadResourceResultResponse/read-resource-result-response.json}
1051 > *
1052 > * @category `resources/read`
1053 > */
1054 > export interface ReadResourceResultResponse extends JSONRPCResultResponse {
1055 > result: ReadResourceResult;
1056 > }
1057 >
1058 > /**
1059 > * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client.
1060 > *
1061 > * @example Resources list changed
1062 > * {@includeCode ./examples/ResourceListChangedNotification/resources-list-changed.json}
1063 > *
1064 > * @category `notifications/resources/list_changed`
1065 > */
1066 > export interface ResourceListChangedNotification extends JSONRPCNotification {
1067 > method: "notifications/resources/list_changed";
1068 > params?: NotificationParams;
1069 > }
1070 >
1071 > /**
1072 > * Parameters for a `resources/subscribe` request.
1073 > *
1074 > * @example Subscribe to file resource
1075 > * {@includeCode ./examples/SubscribeRequestParams/subscribe-to-file-resource.json}
1076 > *
1077 > * @category `resources/subscribe`
1078 > */
1079 > export interface SubscribeRequestParams extends ResourceRequestParams { }
1080 >
1081 > /**
1082 > * Sent from the client to request {@link ResourceUpdatedNotification | resources/updated} notifications from the server whenever a particular resource changes.
1083 > *
1084 > * @example Subscribe request
1085 > * {@includeCode ./examples/SubscribeRequest/subscribe-request.json}
1086 > *
1087 > * @category `resources/subscribe`
1088 > */
1089 > export interface SubscribeRequest extends JSONRPCRequest {
1090 > method: "resources/subscribe";
1091 > params: SubscribeRequestParams;
1092 > }
1093 >
1094 > /**
1095 > * A successful response from the server for a {@link SubscribeRequest | resources/subscribe} request.
1096 > *
1097 > * @example Subscribe result response
1098 > * {@includeCode ./examples/SubscribeResultResponse/subscribe-result-response.json}
1099 > *
1100 > * @category `resources/subscribe`
1101 > */
1102 > export interface SubscribeResultResponse extends JSONRPCResultResponse {
1103 > result: EmptyResult;
1104 > }
1105 >
1106 > /**
1107 > * Parameters for a `resources/unsubscribe` request.
1108 > *
1109 > * @category `resources/unsubscribe`
1110 > */
1111 > export interface UnsubscribeRequestParams extends ResourceRequestParams { }
1112 >
1113 > /**
1114 > * Sent from the client to request cancellation of {@link ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@link SubscribeRequest | resources/subscribe} request.
1115 > *
1116 > * @example Unsubscribe request
1117 > * {@includeCode ./examples/UnsubscribeRequest/unsubscribe-request.json}
1118 > *
1119 > * @category `resources/unsubscribe`
1120 > */
1121 > export interface UnsubscribeRequest extends JSONRPCRequest {
1122 > method: "resources/unsubscribe";
1123 > params: UnsubscribeRequestParams;
1124 > }
1125 >
1126 > /**
1127 > * A successful response from the server for a {@link UnsubscribeRequest | resources/unsubscribe} request.
1128 > *
1129 > * @example Unsubscribe result response
1130 > * {@includeCode ./examples/UnsubscribeResultResponse/unsubscribe-result-response.json}
1131 > *
1132 > * @category `resources/unsubscribe`
1133 > */
1134 > export interface UnsubscribeResultResponse extends JSONRPCResultResponse {
1135 > result: EmptyResult;
1136 > }
1137 >
1138 > /**
1139 > * Parameters for a `notifications/resources/updated` notification.
1140 > *
1141 > * @example File resource updated
1142 > * {@includeCode ./examples/ResourceUpdatedNotificationParams/file-resource-updated.json}
1143 > *
1144 > * @category `notifications/resources/updated`
1145 > */
1146 > export interface ResourceUpdatedNotificationParams extends NotificationParams {
1147 > /**
1148 > * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
1149 > *
1150 > * @format uri
1151 > */
1152 > uri: string;
1153 > }
1154 >
1155 > /**
1156 > * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@link SubscribeRequest | resources/subscribe} request.
1157 > *
1158 > * @example File resource updated notification
1159 > * {@includeCode ./examples/ResourceUpdatedNotification/file-resource-updated-notification.json}
1160 > *
1161 > * @category `notifications/resources/updated`
1162 > */
1163 > export interface ResourceUpdatedNotification extends JSONRPCNotification {
1164 > method: "notifications/resources/updated";
1165 > params: ResourceUpdatedNotificationParams;
1166 > }
1167 >
1168 > /**
1169 > * A known resource that the server is capable of reading.
1170 > *
1171 > * @example File resource with annotations
1172 > * {@includeCode ./examples/Resource/file-resource-with-annotations.json}
1173 > *
1174 > * @category `resources/list`
1175 > */
1176 > export interface Resource extends BaseMetadata, Icons {
1177 > /**
1178 > * The URI of this resource.
1179 > *
1180 > * @format uri
1181 > */
1182 > uri: string;
1183 >
1184 > /**
1185 > * A description of what this resource represents.
1186 > *
1187 > * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
1188 > */
1189 > description?: string;
1190 >
1191 > /**
1192 > * The MIME type of this resource, if known.
1193 > */
1194 > mimeType?: string;
1195 >
1196 > /**
1197 > * Optional annotations for the client.
1198 > */
1199 > annotations?: Annotations;
1200 >
1201 > /**
1202 > * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.
1203 > *
1204 > * This can be used by Hosts to display file sizes and estimate context window usage.
1205 > */
1206 > size?: number;
1207 >
1208 > _meta?: MetaObject;
1209 > }
1210 >
1211 > /**
1212 > * A template description for resources available on the server.
1213 > *
1214 > * @category `resources/templates/list`
1215 > */
1216 > export interface ResourceTemplate extends BaseMetadata, Icons {
1217 > /**
1218 > * A URI template (according to RFC 6570) that can be used to construct resource URIs.
1219 > *
1220 > * @format uri-template
1221 > */
1222 > uriTemplate: string;
1223 >
1224 > /**
1225 > * A description of what this template is for.
1226 > *
1227 > * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
1228 > */
1229 > description?: string;
1230 >
1231 > /**
1232 > * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.
1233 > */
1234 > mimeType?: string;
1235 >
1236 > /**
1237 > * Optional annotations for the client.
1238 > */
1239 > annotations?: Annotations;
1240 >
1241 > _meta?: MetaObject;
1242 > }
1243 >
1244 > /**
1245 > * The contents of a specific resource or sub-resource.
1246 > *
1247 > * @internal
1248 > */
1249 > export interface ResourceContents {
1250 > /**
1251 > * The URI of this resource.
1252 > *
1253 > * @format uri
1254 > */
1255 > uri: string;
1256 > /**
1257 > * The MIME type of this resource, if known.
1258 > */
1259 > mimeType?: string;
1260 >
1261 > _meta?: MetaObject;
1262 > }
1263 >
1264 > /**
1265 > * @example Text file contents
1266 > * {@includeCode ./examples/TextResourceContents/text-file-contents.json}
1267 > *
1268 > * @category Content
1269 > */
1270 > export interface TextResourceContents extends ResourceContents {
1271 > /**
1272 > * The text of the item. This must only be set if the item can actually be represented as text (not binary data).
1273 > */
1274 > text: string;
1275 > }
1276 >
1277 > /**
1278 > * @example Image file contents
1279 > * {@includeCode ./examples/BlobResourceContents/image-file-contents.json}
1280 > *
1281 > * @category Content
1282 > */
1283 > export interface BlobResourceContents extends ResourceContents {
1284 > /**
1285 > * A base64-encoded string representing the binary data of the item.
1286 > *
1287 > * @format byte
1288 > */
1289 > blob: string;
1290 > }
1291 >
1292 > /* Prompts */
1293 > /**
1294 > * Sent from the client to request a list of prompts and prompt templates the server has.
1295 > *
1296 > * @example List prompts request
1297 > * {@includeCode ./examples/ListPromptsRequest/list-prompts-request.json}
1298 > *
1299 > * @category `prompts/list`
1300 > */
1301 > export interface ListPromptsRequest extends PaginatedRequest {
1302 > method: "prompts/list";
1303 > }
1304 >
1305 > /**
1306 > * The result returned by the server for a {@link ListPromptsRequest | prompts/list} request.
1307 > *
1308 > * @example Prompts list with cursor
1309 > * {@includeCode ./examples/ListPromptsResult/prompts-list-with-cursor.json}
1310 > *
1311 > * @category `prompts/list`
1312 > */
1313 > export interface ListPromptsResult extends PaginatedResult {
1314 > prompts: Prompt[];
1315 > }
1316 >
1317 > /**
1318 > * A successful response from the server for a {@link ListPromptsRequest | prompts/list} request.
1319 > *
1320 > * @example List prompts result response
1321 > * {@includeCode ./examples/ListPromptsResultResponse/list-prompts-result-response.json}
1322 > *
1323 > * @category `prompts/list`
1324 > */
1325 > export interface ListPromptsResultResponse extends JSONRPCResultResponse {
1326 > result: ListPromptsResult;
1327 > }
1328 >
1329 > /**
1330 > * Parameters for a `prompts/get` request.
1331 > *
1332 > * @example Get code review prompt
1333 > * {@includeCode ./examples/GetPromptRequestParams/get-code-review-prompt.json}
1334 > *
1335 > * @category `prompts/get`
1336 > */
1337 > export interface GetPromptRequestParams extends RequestParams {
1338 > /**
1339 > * The name of the prompt or prompt template.
1340 > */
1341 > name: string;
1342 > /**
1343 > * Arguments to use for templating the prompt.
1344 > */
1345 > arguments?: { [key: string]: string };
1346 > }
1347 >
1348 > /**
1349 > * Used by the client to get a prompt provided by the server.
1350 > *
1351 > * @example Get prompt request
1352 > * {@includeCode ./examples/GetPromptRequest/get-prompt-request.json}
1353 > *
1354 > * @category `prompts/get`
1355 > */
1356 > export interface GetPromptRequest extends JSONRPCRequest {
1357 > method: "prompts/get";
1358 > params: GetPromptRequestParams;
1359 > }
1360 >
1361 > /**
1362 > * The result returned by the server for a {@link GetPromptRequest | prompts/get} request.
1363 > *
1364 > * @example Code review prompt
1365 > * {@includeCode ./examples/GetPromptResult/code-review-prompt.json}
1366 > *
1367 > * @category `prompts/get`
1368 > */
1369 > export interface GetPromptResult extends Result {
1370 > /**
1371 > * An optional description for the prompt.
1372 > */
1373 > description?: string;
1374 > messages: PromptMessage[];
1375 > }
1376 >
1377 > /**
1378 > * A successful response from the server for a {@link GetPromptRequest | prompts/get} request.
1379 > *
1380 > * @example Get prompt result response
1381 > * {@includeCode ./examples/GetPromptResultResponse/get-prompt-result-response.json}
1382 > *
1383 > * @category `prompts/get`
1384 > */
1385 > export interface GetPromptResultResponse extends JSONRPCResultResponse {
1386 > result: GetPromptResult;
1387 > }
1388 >
1389 > /**
1390 > * A prompt or prompt template that the server offers.
1391 > *
1392 > * @category `prompts/list`
1393 > */
1394 > export interface Prompt extends BaseMetadata, Icons {
1395 > /**
1396 > * An optional description of what this prompt provides
1397 > */
1398 > description?: string;
1399 >
1400 > /**
1401 > * A list of arguments to use for templating the prompt.
1402 > */
1403 > arguments?: PromptArgument[];
1404 >
1405 > _meta?: MetaObject;
1406 > }
1407 >
1408 > /**
1409 > * Describes an argument that a prompt can accept.
1410 > *
1411 > * @category `prompts/list`
1412 > */
1413 > export interface PromptArgument extends BaseMetadata {
1414 > /**
1415 > * A human-readable description of the argument.
1416 > */
1417 > description?: string;
1418 > /**
1419 > * Whether this argument must be provided.
1420 > */
1421 > required?: boolean;
1422 > }
1423 >
1424 > /**
1425 > * The sender or recipient of messages and data in a conversation.
1426 > *
1427 > * @category Common Types
1428 > */
1429 > export type Role = "user" | "assistant";
1430 >
1431 > /**
1432 > * Describes a message returned as part of a prompt.
1433 > *
1434 > * This is similar to {@link SamplingMessage}, but also supports the embedding of
1435 > * resources from the MCP server.
1436 > *
1437 > * @category `prompts/get`
1438 > */
1439 > export interface PromptMessage {
1440 > role: Role;
1441 > content: ContentBlock;
1442 > }
1443 >
1444 > /**
1445 > * A resource that the server is capable of reading, included in a prompt or tool call result.
1446 > *
1447 > * Note: resource links returned by tools are not guaranteed to appear in the results of {@link ListResourcesRequest | resources/list} requests.
1448 > *
1449 > * @example File resource link
1450 > * {@includeCode ./examples/ResourceLink/file-resource-link.json}
1451 > *
1452 > * @category Content
1453 > */
1454 > export interface ResourceLink extends Resource {
1455 > type: "resource_link";
1456 > }
1457 >
1458 > /**
1459 > * The contents of a resource, embedded into a prompt or tool call result.
1460 > *
1461 > * It is up to the client how best to render embedded resources for the benefit
1462 > * of the LLM and/or the user.
1463 > *
1464 > * @example Embedded file resource with annotations
1465 > * {@includeCode ./examples/EmbeddedResource/embedded-file-resource-with-annotations.json}
1466 > *
1467 > * @category Content
1468 > */
1469 > export interface EmbeddedResource {
1470 > type: "resource";
1471 > resource: TextResourceContents | BlobResourceContents;
1472 >
1473 > /**
1474 > * Optional annotations for the client.
1475 > */
1476 > annotations?: Annotations;
1477 >
1478 > _meta?: MetaObject;
1479 > }
1480 > /**
1481 > * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client.
1482 > *
1483 > * @example Prompts list changed
1484 > * {@includeCode ./examples/PromptListChangedNotification/prompts-list-changed.json}
1485 > *
1486 > * @category `notifications/prompts/list_changed`
1487 > */
1488 > export interface PromptListChangedNotification extends JSONRPCNotification {
1489 > method: "notifications/prompts/list_changed";
1490 > params?: NotificationParams;
1491 > }
1492 >
1493 > /* Tools */
1494 > /**
1495 > * Sent from the client to request a list of tools the server has.
1496 > *
1497 > * @example List tools request
1498 > * {@includeCode ./examples/ListToolsRequest/list-tools-request.json}
1499 > *
1500 > * @category `tools/list`
1501 > */
1502 > export interface ListToolsRequest extends PaginatedRequest {
1503 > method: "tools/list";
1504 > }
1505 >
1506 > /**
1507 > * The result returned by the server for a {@link ListToolsRequest | tools/list} request.
1508 > *
1509 > * @example Tools list with cursor
1510 > * {@includeCode ./examples/ListToolsResult/tools-list-with-cursor.json}
1511 > *
1512 > * @category `tools/list`
1513 > */
1514 > export interface ListToolsResult extends PaginatedResult {
1515 > tools: Tool[];
1516 > }
1517 >
1518 > /**
1519 > * A successful response from the server for a {@link ListToolsRequest | tools/list} request.
1520 > *
1521 > * @example List tools result response
1522 > * {@includeCode ./examples/ListToolsResultResponse/list-tools-result-response.json}
1523 > *
1524 > * @category `tools/list`
1525 > */
1526 > export interface ListToolsResultResponse extends JSONRPCResultResponse {
1527 > result: ListToolsResult;
1528 > }
1529 >
1530 > /**
1531 > * The result returned by the server for a {@link CallToolRequest | tools/call} request.
1532 > *
1533 > * @example Result with unstructured text
1534 > * {@includeCode ./examples/CallToolResult/result-with-unstructured-text.json}
1535 > *
1536 > * @example Result with structured content
1537 > * {@includeCode ./examples/CallToolResult/result-with-structured-content.json}
1538 > *
1539 > * @example Invalid tool input error
1540 > * {@includeCode ./examples/CallToolResult/invalid-tool-input-error.json}
1541 > *
1542 > * @category `tools/call`
1543 > */
1544 > export interface CallToolResult extends Result {
1545 > /**
1546 > * A list of content objects that represent the unstructured result of the tool call.
1547 > */
1548 > content: ContentBlock[];
1549 >
1550 > /**
1551 > * An optional JSON object that represents the structured result of the tool call.
1552 > */
1553 > structuredContent?: { [key: string]: unknown };
1554 >
1555 > /**
1556 > * Whether the tool call ended in an error.
1557 > *
1558 > * If not set, this is assumed to be false (the call was successful).
1559 > *
1560 > * Any errors that originate from the tool SHOULD be reported inside the result
1561 > * object, with `isError` set to true, _not_ as an MCP protocol-level error
1562 > * response. Otherwise, the LLM would not be able to see that an error occurred
1563 > * and self-correct.
1564 > *
1565 > * However, any errors in _finding_ the tool, an error indicating that the
1566 > * server does not support tool calls, or any other exceptional conditions,
1567 > * should be reported as an MCP error response.
1568 > */
1569 > isError?: boolean;
1570 > }
1571 >
1572 > /**
1573 > * A successful response from the server for a {@link CallToolRequest | tools/call} request.
1574 > *
1575 > * @example Call tool result response
1576 > * {@includeCode ./examples/CallToolResultResponse/call-tool-result-response.json}
1577 > *
1578 > * @category `tools/call`
1579 > */
1580 > export interface CallToolResultResponse extends JSONRPCResultResponse {
1581 > result: CallToolResult;
1582 > }
1583 >
1584 > /**
1585 > * Parameters for a `tools/call` request.
1586 > *
1587 > * @example `get_weather` tool call params
1588 > * {@includeCode ./examples/CallToolRequestParams/get-weather-tool-call-params.json}
1589 > *
1590 > * @example Tool call params with progress token
1591 > * {@includeCode ./examples/CallToolRequestParams/tool-call-params-with-progress-token.json}
1592 > *
1593 > * @category `tools/call`
1594 > */
1595 > export interface CallToolRequestParams extends TaskAugmentedRequestParams {
1596 > /**
1597 > * The name of the tool.
1598 > */
1599 > name: string;
1600 > /**
1601 > * Arguments to use for the tool call.
1602 > */
1603 > arguments?: { [key: string]: unknown };
1604 > }
1605 >
1606 > /**
1607 > * Used by the client to invoke a tool provided by the server.
1608 > *
1609 > * @example Call tool request
1610 > * {@includeCode ./examples/CallToolRequest/call-tool-request.json}
1611 > *
1612 > * @category `tools/call`
1613 > */
1614 > export interface CallToolRequest extends JSONRPCRequest {
1615 > method: "tools/call";
1616 > params: CallToolRequestParams;
1617 > }
1618 >
1619 > /**
1620 > * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client.
1621 > *
1622 > * @example Tools list changed
1623 > * {@includeCode ./examples/ToolListChangedNotification/tools-list-changed.json}
1624 > *
1625 > * @category `notifications/tools/list_changed`
1626 > */
1627 > export interface ToolListChangedNotification extends JSONRPCNotification {
1628 > method: "notifications/tools/list_changed";
1629 > params?: NotificationParams;
1630 > }
1631 >
1632 > /**
1633 > * Additional properties describing a {@link Tool} to clients.
1634 > *
1635 > * NOTE: all properties in `ToolAnnotations` are **hints**.
1636 > * They are not guaranteed to provide a faithful description of
1637 > * tool behavior (including descriptive properties like `title`).
1638 > *
1639 > * Clients should never make tool use decisions based on `ToolAnnotations`
1640 > * received from untrusted servers.
1641 > *
1642 > * @category `tools/list`
1643 > */
1644 > export interface ToolAnnotations {
1645 > /**
1646 > * A human-readable title for the tool.
1647 > */
1648 > title?: string;
1649 >
1650 > /**
1651 > * If true, the tool does not modify its environment.
1652 > *
1653 > * Default: false
1654 > */
1655 > readOnlyHint?: boolean;
1656 >
1657 > /**
1658 > * If true, the tool may perform destructive updates to its environment.
1659 > * If false, the tool performs only additive updates.
1660 > *
1661 > * (This property is meaningful only when `readOnlyHint == false`)
1662 > *
1663 > * Default: true
1664 > */
1665 > destructiveHint?: boolean;
1666 >
1667 > /**
1668 > * If true, calling the tool repeatedly with the same arguments
1669 > * will have no additional effect on its environment.
1670 > *
1671 > * (This property is meaningful only when `readOnlyHint == false`)
1672 > *
1673 > * Default: false
1674 > */
1675 > idempotentHint?: boolean;
1676 >
1677 > /**
1678 > * If true, this tool may interact with an "open world" of external
1679 > * entities. If false, the tool's domain of interaction is closed.
1680 > * For example, the world of a web search tool is open, whereas that
1681 > * of a memory tool is not.
1682 > *
1683 > * Default: true
1684 > */
1685 > openWorldHint?: boolean;
1686 > }
1687 >
1688 > /**
1689 > * Execution-related properties for a tool.
1690 > *
1691 > * @category `tools/list`
1692 > */
1693 > export interface ToolExecution {
1694 > /**
1695 > * Indicates whether this tool supports task-augmented execution.
1696 > * This allows clients to handle long-running operations through polling
1697 > * the task system.
1698 > *
1699 > * - `"forbidden"`: Tool does not support task-augmented execution (default when absent)
1700 > * - `"optional"`: Tool may support task-augmented execution
1701 > * - `"required"`: Tool requires task-augmented execution
1702 > *
1703 > * Default: `"forbidden"`
1704 > */
1705 > taskSupport?: "forbidden" | "optional" | "required";
1706 > }
1707 >
1708 > /**
1709 > * Definition for a tool the client can call.
1710 > *
1711 > * @example With default 2020-12 input schema
1712 > * {@includeCode ./examples/Tool/with-default-2020-12-input-schema.json}
1713 > *
1714 > * @example With explicit draft-07 input schema
1715 > * {@includeCode ./examples/Tool/with-explicit-draft-07-input-schema.json}
1716 > *
1717 > * @example With no parameters
1718 > * {@includeCode ./examples/Tool/with-no-parameters.json}
1719 > *
1720 > * @example With output schema for structured content
1721 > * {@includeCode ./examples/Tool/with-output-schema-for-structured-content.json}
1722 > *
1723 > * @category `tools/list`
1724 > */
1725 > export interface Tool extends BaseMetadata, Icons {
1726 > /**
1727 > * A human-readable description of the tool.
1728 > *
1729 > * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model.
1730 > */
1731 > description?: string;
1732 >
1733 > /**
1734 > * A JSON Schema object defining the expected parameters for the tool.
1735 > */
1736 > inputSchema: {
1737 > $schema?: string;
1738 > type: "object";
1739 > properties?: { [key: string]: object };
1740 > required?: string[];
1741 > };
1742 >
1743 > /**
1744 > * Execution-related properties for this tool.
1745 > */
1746 > execution?: ToolExecution;
1747 >
1748 > /**
1749 > * An optional JSON Schema object defining the structure of the tool's output returned in
1750 > * the structuredContent field of a {@link CallToolResult}.
1751 > *
1752 > * Defaults to JSON Schema 2020-12 when no explicit `$schema` is provided.
1753 > * Currently restricted to `type: "object"` at the root level.
1754 > */
1755 > outputSchema?: {
1756 > $schema?: string;
1757 > type: "object";
1758 > properties?: { [key: string]: object };
1759 > required?: string[];
1760 > };
1761 >
1762 > /**
1763 > * Optional additional tool information.
1764 > *
1765 > * Display name precedence order is: `title`, `annotations.title`, then `name`.
1766 > */
1767 > annotations?: ToolAnnotations;
1768 >
1769 > _meta?: MetaObject;
1770 > }
1771 >
1772 > /* Tasks */
1773 >
1774 > /**
1775 > * The status of a task.
1776 > *
1777 > * @category `tasks`
1778 > */
1779 > export type TaskStatus =
1780 > | "working" // The request is currently being processed
1781 > | "input_required" // The task is waiting for input (e.g., elicitation or sampling)
1782 > | "completed" // The request completed successfully and results are available
1783 > | "failed" // The associated request did not complete successfully. For tool calls specifically, this includes cases where the tool call result has `isError` set to true.
1784 > | "cancelled"; // The request was cancelled before completion
1785 >
1786 > /**
1787 > * Metadata for augmenting a request with task execution.
1788 > * Include this in the `task` field of the request parameters.
1789 > *
1790 > * @category `tasks`
1791 > */
1792 > export interface TaskMetadata {
1793 > /**
1794 > * Requested duration in milliseconds to retain task from creation.
1795 > */
1796 > ttl?: number;
1797 > }
1798 >
1799 > /**
1800 > * Metadata for associating messages with a task.
1801 > * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`.
1802 > *
1803 > * @category `tasks`
1804 > */
1805 > export interface RelatedTaskMetadata {
1806 > /**
1807 > * The task identifier this message is associated with.
1808 > */
1809 > taskId: string;
1810 > }
1811 >
1812 > /**
1813 > * Data associated with a task.
1814 > *
1815 > * @category `tasks`
1816 > */
1817 > export interface Task {
1818 > /**
1819 > * The task identifier.
1820 > */
1821 > taskId: string;
1822 >
1823 > /**
1824 > * Current task state.
1825 > */
1826 > status: TaskStatus;
1827 >
1828 > /**
1829 > * Optional human-readable message describing the current task state.
1830 > * This can provide context for any status, including:
1831 > * - Reasons for "cancelled" status
1832 > * - Summaries for "completed" status
1833 > * - Diagnostic information for "failed" status (e.g., error details, what went wrong)
1834 > */
1835 > statusMessage?: string;
1836 >
1837 > /**
1838 > * ISO 8601 timestamp when the task was created.
1839 > */
1840 > createdAt: string;
1841 >
1842 > /**
1843 > * ISO 8601 timestamp when the task was last updated.
1844 > */
1845 > lastUpdatedAt: string;
1846 >
1847 > /**
1848 > * Actual retention duration from creation in milliseconds, null for unlimited.
1849 > */
1850 > ttl: number | null;
1851 >
1852 > /**
1853 > * Suggested polling interval in milliseconds.
1854 > */
1855 > pollInterval?: number;
1856 > }
1857 >
1858 > /**
1859 > * The result returned for a task-augmented request.
1860 > *
1861 > * @category `tasks`
1862 > */
1863 > export interface CreateTaskResult extends Result {
1864 > task: Task;
1865 > }
1866 >
1867 > /**
1868 > * A successful response for a task-augmented request.
1869 > *
1870 > * @category `tasks`
1871 > */
1872 > export interface CreateTaskResultResponse extends JSONRPCResultResponse {
1873 > result: CreateTaskResult;
1874 > }
1875 >
1876 > /**
1877 > * A request to retrieve the state of a task.
1878 > *
1879 > * @category `tasks/get`
1880 > */
1881 > export interface GetTaskRequest extends JSONRPCRequest {
1882 > method: "tasks/get";
1883 > params: {
1884 > /**
1885 > * The task identifier to query.
1886 > */
1887 > taskId: string;
1888 > };
1889 > }
1890 >
1891 > /**
1892 > * The result returned for a {@link GetTaskRequest | tasks/get} request.
1893 > *
1894 > * @category `tasks/get`
1895 > */
1896 > export type GetTaskResult = Result & Task;
1897 >
1898 > /**
1899 > * A successful response for a {@link GetTaskRequest | tasks/get} request.
1900 > *
1901 > * @category `tasks/get`
1902 > */
1903 > export interface GetTaskResultResponse extends JSONRPCResultResponse {
1904 > result: GetTaskResult;
1905 > }
1906 >
1907 > /**
1908 > * A request to retrieve the result of a completed task.
1909 > *
1910 > * @category `tasks/result`
1911 > */
1912 > export interface GetTaskPayloadRequest extends JSONRPCRequest {
1913 > method: "tasks/result";
1914 > params: {
1915 > /**
1916 > * The task identifier to retrieve results for.
1917 > */
1918 > taskId: string;
1919 > };
1920 > }
1921 >
1922 > /**
1923 > * The result returned for a {@link GetTaskPayloadRequest | tasks/result} request.
1924 > * The structure matches the result type of the original request.
1925 > * For example, a {@link CallToolRequest | tools/call} task would return the {@link CallToolResult} structure.
1926 > *
1927 > * @category `tasks/result`
1928 > */
1929 > export interface GetTaskPayloadResult extends Result {
1930 > [key: string]: unknown;
1931 > }
1932 >
1933 > /**
1934 > * A successful response for a {@link GetTaskPayloadRequest | tasks/result} request.
1935 > *
1936 > * @category `tasks/result`
1937 > */
1938 > export interface GetTaskPayloadResultResponse extends JSONRPCResultResponse {
1939 > result: GetTaskPayloadResult;
1940 > }
1941 >
1942 > /**
1943 > * A request to cancel a task.
1944 > *
1945 > * @category `tasks/cancel`
1946 > */
1947 > export interface CancelTaskRequest extends JSONRPCRequest {
1948 > method: "tasks/cancel";
1949 > params: {
1950 > /**
1951 > * The task identifier to cancel.
1952 > */
1953 > taskId: string;
1954 > };
1955 > }
1956 >
1957 > /**
1958 > * The result returned for a {@link CancelTaskRequest | tasks/cancel} request.
1959 > *
1960 > * @category `tasks/cancel`
1961 > */
1962 > export type CancelTaskResult = Result & Task;
1963 >
1964 > /**
1965 > * A successful response for a {@link CancelTaskRequest | tasks/cancel} request.
1966 > *
1967 > * @category `tasks/cancel`
1968 > */
1969 > export interface CancelTaskResultResponse extends JSONRPCResultResponse {
1970 > result: CancelTaskResult;
1971 > }
1972 >
1973 > /**
1974 > * A request to retrieve a list of tasks.
1975 > *
1976 > * @category `tasks/list`
1977 > */
1978 > export interface ListTasksRequest extends PaginatedRequest {
1979 > method: "tasks/list";
1980 > }
1981 >
1982 > /**
1983 > * The result returned for a {@link ListTasksRequest | tasks/list} request.
1984 > *
1985 > * @category `tasks/list`
1986 > */
1987 > export interface ListTasksResult extends PaginatedResult {
1988 > tasks: Task[];
1989 > }
1990 >
1991 > /**
1992 > * A successful response for a {@link ListTasksRequest | tasks/list} request.
1993 > *
1994 > * @category `tasks/list`
1995 > */
1996 > export interface ListTasksResultResponse extends JSONRPCResultResponse {
1997 > result: ListTasksResult;
1998 > }
1999 >
2000 > /**
2001 > * Parameters for a `notifications/tasks/status` notification.
2002 > *
2003 > * @category `notifications/tasks/status`
2004 > */
2005 > export type TaskStatusNotificationParams = NotificationParams & Task;
2006 >
2007 > /**
2008 > * An optional notification from the receiver to the requestor, informing them that a task's status has changed. Receivers are not required to send these notifications.
2009 > *
2010 > * @category `notifications/tasks/status`
2011 > */
2012 > export interface TaskStatusNotification extends JSONRPCNotification {
2013 > method: "notifications/tasks/status";
2014 > params: TaskStatusNotificationParams;
2015 > }
2016 >
2017 > /* Logging */
2018 >
2019 > /**
2020 > * Parameters for a `logging/setLevel` request.
2021 > *
2022 > * @example Set log level to "info"
2023 > * {@includeCode ./examples/SetLevelRequestParams/set-log-level-to-info.json}
2024 > *
2025 > * @category `logging/setLevel`
2026 > */
2027 > export interface SetLevelRequestParams extends RequestParams {
2028 > /**
2029 > * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as {@link LoggingMessageNotification | notifications/message}.
2030 > */
2031 > level: LoggingLevel;
2032 > }
2033 >
2034 > /**
2035 > * A request from the client to the server, to enable or adjust logging.
2036 > *
2037 > * @example Set logging level request
2038 > * {@includeCode ./examples/SetLevelRequest/set-logging-level-request.json}
2039 > *
2040 > * @category `logging/setLevel`
2041 > */
2042 > export interface SetLevelRequest extends JSONRPCRequest {
2043 > method: "logging/setLevel";
2044 > params: SetLevelRequestParams;
2045 > }
2046 >
2047 > /**
2048 > * A successful response from the server for a {@link SetLevelRequest | logging/setLevel} request.
2049 > *
2050 > * @example Set logging level result response
2051 > * {@includeCode ./examples/SetLevelResultResponse/set-logging-level-result-response.json}
2052 > *
2053 > * @category `logging/setLevel`
2054 > */
2055 > export interface SetLevelResultResponse extends JSONRPCResultResponse {
2056 > result: EmptyResult;
2057 > }
2058 >
2059 > /**
2060 > * Parameters for a `notifications/message` notification.
2061 > *
2062 > * @example Log database connection failed
2063 > * {@includeCode ./examples/LoggingMessageNotificationParams/log-database-connection-failed.json}
2064 > *
2065 > * @category `notifications/message`
2066 > */
2067 > export interface LoggingMessageNotificationParams extends NotificationParams {
2068 > /**
2069 > * The severity of this log message.
2070 > */
2071 > level: LoggingLevel;
2072 > /**
2073 > * An optional name of the logger issuing this message.
2074 > */
2075 > logger?: string;
2076 > /**
2077 > * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
2078 > */
2079 > data: unknown;
2080 > }
2081 >
2082 > /**
2083 > * JSONRPCNotification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically.
2084 > *
2085 > * @example Log database connection failed
2086 > * {@includeCode ./examples/LoggingMessageNotification/log-database-connection-failed.json}
2087 > *
2088 > * @category `notifications/message`
2089 > */
2090 > export interface LoggingMessageNotification extends JSONRPCNotification {
2091 > method: "notifications/message";
2092 > params: LoggingMessageNotificationParams;
2093 > }
2094 >
2095 > /**
2096 > * The severity of a log message.
2097 > *
2098 > * These map to syslog message severities, as specified in RFC-5424:
2099 > * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1
2100 > *
2101 > * @category Common Types
2102 > */
2103 > export type LoggingLevel =
2104 > | "debug"
2105 > | "info"
2106 > | "notice"
2107 > | "warning"
2108 > | "error"
2109 > | "critical"
2110 > | "alert"
2111 > | "emergency";
2112 >
2113 > /* Sampling */
2114 > /**
2115 > * Parameters for a `sampling/createMessage` request.
2116 > *
2117 > * @example Basic request
2118 > * {@includeCode ./examples/CreateMessageRequestParams/basic-request.json}
2119 > *
2120 > * @example Request with tools
2121 > * {@includeCode ./examples/CreateMessageRequestParams/request-with-tools.json}
2122 > *
2123 > * @example Follow-up request with tool results
2124 > * {@includeCode ./examples/CreateMessageRequestParams/follow-up-with-tool-results.json}
2125 > *
2126 > * @category `sampling/createMessage`
2127 > */
2128 > export interface CreateMessageRequestParams extends TaskAugmentedRequestParams {
2129 > messages: SamplingMessage[];
2130 > /**
2131 > * The server's preferences for which model to select. The client MAY ignore these preferences.
2132 > */
2133 > modelPreferences?: ModelPreferences;
2134 > /**
2135 > * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
2136 > */
2137 > systemPrompt?: string;
2138 > /**
2139 > * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.
2140 > * The client MAY ignore this request.
2141 > *
2142 > * Default is `"none"`. Values `"thisServer"` and `"allServers"` are soft-deprecated. Servers SHOULD only use these values if the client
2143 > * declares {@link ClientCapabilities.sampling.context}. These values may be removed in future spec releases.
2144 > */
2145 > includeContext?: "none" | "thisServer" | "allServers";
2146 > /**
2147 > * @TJS-type number
2148 > */
2149 > temperature?: number;
2150 > /**
2151 > * The requested maximum number of tokens to sample (to prevent runaway completions).
2152 > *
2153 > * The client MAY choose to sample fewer tokens than the requested maximum.
2154 > */
2155 > maxTokens: number;
2156 > stopSequences?: string[];
2157 > /**
2158 > * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
2159 > */
2160 > metadata?: object;
2161 > /**
2162 > * Tools that the model may use during generation.
2163 > * The client MUST return an error if this field is provided but {@link ClientCapabilities.sampling.tools} is not declared.
2164 > */
2165 > tools?: Tool[];
2166 > /**
2167 > * Controls how the model uses tools.
2168 > * The client MUST return an error if this field is provided but {@link ClientCapabilities.sampling.tools} is not declared.
2169 > * Default is `{ mode: "auto" }`.
2170 > */
2171 > toolChoice?: ToolChoice;
2172 > }
2173 >
2174 > /**
2175 > * Controls tool selection behavior for sampling requests.
2176 > *
2177 > * @category `sampling/createMessage`
2178 > */
2179 > export interface ToolChoice {
2180 > /**
2181 > * Controls the tool use ability of the model:
2182 > * - `"auto"`: Model decides whether to use tools (default)
2183 > * - `"required"`: Model MUST use at least one tool before completing
2184 > * - `"none"`: Model MUST NOT use any tools
2185 > */
2186 > mode?: "auto" | "required" | "none";
2187 > }
2188 >
2189 > /**
2190 > * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it.
2191 > *
2192 > * @example Sampling request
2193 > * {@includeCode ./examples/CreateMessageRequest/sampling-request.json}
2194 > *
2195 > * @category `sampling/createMessage`
2196 > */
2197 > export interface CreateMessageRequest extends JSONRPCRequest {
2198 > method: "sampling/createMessage";
2199 > params: CreateMessageRequestParams;
2200 > }
2201 >
2202 > /**
2203 > * The result returned by the client for a {@link CreateMessageRequest | sampling/createMessage} request.
2204 > * The client should inform the user before returning the sampled message, to allow them
2205 > * to inspect the response (human in the loop) and decide whether to allow the server to see it.
2206 > *
2207 > * @example Text response
2208 > * {@includeCode ./examples/CreateMessageResult/text-response.json}
2209 > *
2210 > * @example Tool use response
2211 > * {@includeCode ./examples/CreateMessageResult/tool-use-response.json}
2212 > *
2213 > * @example Final response after tool use
2214 > * {@includeCode ./examples/CreateMessageResult/final-response.json}
2215 > *
2216 > * @category `sampling/createMessage`
2217 > */
2218 > export interface CreateMessageResult extends Result, SamplingMessage {
2219 > /**
2220 > * The name of the model that generated the message.
2221 > */
2222 > model: string;
2223 >
2224 > /**
2225 > * The reason why sampling stopped, if known.
2226 > *
2227 > * Standard values:
2228 > * - `"endTurn"`: Natural end of the assistant's turn
2229 > * - `"stopSequence"`: A stop sequence was encountered
2230 > * - `"maxTokens"`: Maximum token limit was reached
2231 > * - `"toolUse"`: The model wants to use one or more tools
2232 > *
2233 > * This field is an open string to allow for provider-specific stop reasons.
2234 > */
2235 > stopReason?: "endTurn" | "stopSequence" | "maxTokens" | "toolUse" | string;
2236 > }
2237 >
2238 > /**
2239 > * A successful response from the client for a {@link CreateMessageRequest | sampling/createMessage} request.
2240 > *
2241 > * @example Sampling result response
2242 > * {@includeCode ./examples/CreateMessageResultResponse/sampling-result-response.json}
2243 > *
2244 > * @category `sampling/createMessage`
2245 > */
2246 > export interface CreateMessageResultResponse extends JSONRPCResultResponse {
2247 > result: CreateMessageResult;
2248 > }
2249 >
2250 > /**
2251 > * Describes a message issued to or received from an LLM API.
2252 > *
2253 > * @example Single content block
2254 > * {@includeCode ./examples/SamplingMessage/single-content-block.json}
2255 > *
2256 > * @example Multiple content blocks
2257 > * {@includeCode ./examples/SamplingMessage/multiple-content-blocks.json}
2258 > *
2259 > * @category `sampling/createMessage`
2260 > */
2261 > export interface SamplingMessage {
2262 > role: Role;
2263 > content: SamplingMessageContentBlock | SamplingMessageContentBlock[];
2264 > _meta?: MetaObject;
2265 > }
2266 >
2267 > /**
2268 > * @category `sampling/createMessage`
2269 > */
2270 > export type SamplingMessageContentBlock =
2271 > | TextContent
2272 > | ImageContent
2273 > | AudioContent
2274 > | ToolUseContent
2275 > | ToolResultContent;
2276 >
2277 > /**
2278 > * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed
2279 > *
2280 > * @category Common Types
2281 > */
2282 > export interface Annotations {
2283 > /**
2284 > * Describes who the intended audience of this object or data is.
2285 > *
2286 > * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`).
2287 > */
2288 > audience?: Role[];
2289 >
2290 > /**
2291 > * Describes how important this data is for operating the server.
2292 > *
2293 > * A value of 1 means "most important," and indicates that the data is
2294 > * effectively required, while 0 means "least important," and indicates that
2295 > * the data is entirely optional.
2296 > *
2297 > * @TJS-type number
2298 > * @minimum 0
2299 > * @maximum 1
2300 > */
2301 > priority?: number;
2302 >
2303 > /**
2304 > * The moment the resource was last modified, as an ISO 8601 formatted string.
2305 > *
2306 > * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z").
2307 > *
2308 > * Examples: last activity timestamp in an open file, timestamp when the resource
2309 > * was attached, etc.
2310 > */
2311 > lastModified?: string;
2312 > }
2313 >
2314 > /**
2315 > * @category Content
2316 > */
2317 > export type ContentBlock =
2318 > | TextContent
2319 > | ImageContent
2320 > | AudioContent
2321 > | ResourceLink
2322 > | EmbeddedResource;
2323 >
2324 > /**
2325 > * Text provided to or from an LLM.
2326 > *
2327 > * @example Text content
2328 > * {@includeCode ./examples/TextContent/text-content.json}
2329 > *
2330 > * @category Content
2331 > */
2332 > export interface TextContent {
2333 > type: "text";
2334 >
2335 > /**
2336 > * The text content of the message.
2337 > */
2338 > text: string;
2339 >
2340 > /**
2341 > * Optional annotations for the client.
2342 > */
2343 > annotations?: Annotations;
2344 >
2345 > _meta?: MetaObject;
2346 > }
2347 >
2348 > /**
2349 > * An image provided to or from an LLM.
2350 > *
2351 > * @example `image/png` content with annotations
2352 > * {@includeCode ./examples/ImageContent/image-png-content-with-annotations.json}
2353 > *
2354 > * @category Content
2355 > */
2356 > export interface ImageContent {
2357 > type: "image";
2358 >
2359 > /**
2360 > * The base64-encoded image data.
2361 > *
2362 > * @format byte
2363 > */
2364 > data: string;
2365 >
2366 > /**
2367 > * The MIME type of the image. Different providers may support different image types.
2368 > */
2369 > mimeType: string;
2370 >
2371 > /**
2372 > * Optional annotations for the client.
2373 > */
2374 > annotations?: Annotations;
2375 >
2376 > _meta?: MetaObject;
2377 > }
2378 >
2379 > /**
2380 > * Audio provided to or from an LLM.
2381 > *
2382 > * @example `audio/wav` content
2383 > * {@includeCode ./examples/AudioContent/audio-wav-content.json}
2384 > *
2385 > * @category Content
2386 > */
2387 > export interface AudioContent {
2388 > type: "audio";
2389 >
2390 > /**
2391 > * The base64-encoded audio data.
2392 > *
2393 > * @format byte
2394 > */
2395 > data: string;
2396 >
2397 > /**
2398 > * The MIME type of the audio. Different providers may support different audio types.
2399 > */
2400 > mimeType: string;
2401 >
2402 > /**
2403 > * Optional annotations for the client.
2404 > */
2405 > annotations?: Annotations;
2406 >
2407 > _meta?: MetaObject;
2408 > }
2409 >
2410 > /**
2411 > * A request from the assistant to call a tool.
2412 > *
2413 > * @example `get_weather` tool use
2414 > * {@includeCode ./examples/ToolUseContent/get-weather-tool-use.json}
2415 > *
2416 > * @category `sampling/createMessage`
2417 > */
2418 > export interface ToolUseContent {
2419 > type: "tool_use";
2420 >
2421 > /**
2422 > * A unique identifier for this tool use.
2423 > *
2424 > * This ID is used to match tool results to their corresponding tool uses.
2425 > */
2426 > id: string;
2427 >
2428 > /**
2429 > * The name of the tool to call.
2430 > */
2431 > name: string;
2432 >
2433 > /**
2434 > * The arguments to pass to the tool, conforming to the tool's input schema.
2435 > */
2436 > input: { [key: string]: unknown };
2437 >
2438 > /**
2439 > * Optional metadata about the tool use. Clients SHOULD preserve this field when
2440 > * including tool uses in subsequent sampling requests to enable caching optimizations.
2441 > */
2442 > _meta?: MetaObject;
2443 > }
2444 >
2445 > /**
2446 > * The result of a tool use, provided by the user back to the assistant.
2447 > *
2448 > * @example `get_weather` tool result
2449 > * {@includeCode ./examples/ToolResultContent/get-weather-tool-result.json}
2450 > *
2451 > * @category `sampling/createMessage`
2452 > */
2453 > export interface ToolResultContent {
2454 > type: "tool_result";
2455 >
2456 > /**
2457 > * The ID of the tool use this result corresponds to.
2458 > *
2459 > * This MUST match the ID from a previous {@link ToolUseContent}.
2460 > */
2461 > toolUseId: string;
2462 >
2463 > /**
2464 > * The unstructured result content of the tool use.
2465 > *
2466 > * This has the same format as {@link CallToolResult.content} and can include text, images,
2467 > * audio, resource links, and embedded resources.
2468 > */
2469 > content: ContentBlock[];
2470 >
2471 > /**
2472 > * An optional structured result object.
2473 > *
2474 > * If the tool defined an {@link Tool.outputSchema}, this SHOULD conform to that schema.
2475 > */
2476 > structuredContent?: { [key: string]: unknown };
2477 >
2478 > /**
2479 > * Whether the tool use resulted in an error.
2480 > *
2481 > * If true, the content typically describes the error that occurred.
2482 > * Default: false
2483 > */
2484 > isError?: boolean;
2485 >
2486 > /**
2487 > * Optional metadata about the tool result. Clients SHOULD preserve this field when
2488 > * including tool results in subsequent sampling requests to enable caching optimizations.
2489 > */
2490 > _meta?: MetaObject;
2491 > }
2492 >
2493 > /**
2494 > * The server's preferences for model selection, requested of the client during sampling.
2495 > *
2496 > * Because LLMs can vary along multiple dimensions, choosing the "best" model is
2497 > * rarely straightforward. Different models excel in different areas-some are
2498 > * faster but less capable, others are more capable but more expensive, and so
2499 > * on. This interface allows servers to express their priorities across multiple
2500 > * dimensions to help clients make an appropriate selection for their use case.
2501 > *
2502 > * These preferences are always advisory. The client MAY ignore them. It is also
2503 > * up to the client to decide how to interpret these preferences and how to
2504 > * balance them against other considerations.
2505 > *
2506 > * @example With hints and priorities
2507 > * {@includeCode ./examples/ModelPreferences/with-hints-and-priorities.json}
2508 > *
2509 > * @category `sampling/createMessage`
2510 > */
2511 > export interface ModelPreferences {
2512 > /**
2513 > * Optional hints to use for model selection.
2514 > *
2515 > * If multiple hints are specified, the client MUST evaluate them in order
2516 > * (such that the first match is taken).
2517 > *
2518 > * The client SHOULD prioritize these hints over the numeric priorities, but
2519 > * MAY still use the priorities to select from ambiguous matches.
2520 > */
2521 > hints?: ModelHint[];
2522 >
2523 > /**
2524 > * How much to prioritize cost when selecting a model. A value of 0 means cost
2525 > * is not important, while a value of 1 means cost is the most important
2526 > * factor.
2527 > *
2528 > * @TJS-type number
2529 > * @minimum 0
2530 > * @maximum 1
2531 > */
2532 > costPriority?: number;
2533 >
2534 > /**
2535 > * How much to prioritize sampling speed (latency) when selecting a model. A
2536 > * value of 0 means speed is not important, while a value of 1 means speed is
2537 > * the most important factor.
2538 > *
2539 > * @TJS-type number
2540 > * @minimum 0
2541 > * @maximum 1
2542 > */
2543 > speedPriority?: number;
2544 >
2545 > /**
2546 > * How much to prioritize intelligence and capabilities when selecting a
2547 > * model. A value of 0 means intelligence is not important, while a value of 1
2548 > * means intelligence is the most important factor.
2549 > *
2550 > * @TJS-type number
2551 > * @minimum 0
2552 > * @maximum 1
2553 > */
2554 > intelligencePriority?: number;
2555 > }
2556 >
2557 > /**
2558 > * Hints to use for model selection.
2559 > *
2560 > * Keys not declared here are currently left unspecified by the spec and are up
2561 > * to the client to interpret.
2562 > *
2563 > * @category `sampling/createMessage`
2564 > */
2565 > export interface ModelHint {
2566 > /**
2567 > * A hint for a model name.
2568 > *
2569 > * The client SHOULD treat this as a substring of a model name; for example:
2570 > * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022`
2571 > * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc.
2572 > * - `claude` should match any Claude model
2573 > *
2574 > * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example:
2575 > * - `gemini-1.5-flash` could match `claude-3-haiku-20240307`
2576 > */
2577 > name?: string;
2578 > }
2579 >
2580 > /* Autocomplete */
2581 > /**
2582 > * Parameters for a `completion/complete` request.
2583 > *
2584 > * @category `completion/complete`
2585 > *
2586 > * @example Prompt argument completion
2587 > * {@includeCode ./examples/CompleteRequestParams/prompt-argument-completion.json}
2588 > *
2589 > * @example Prompt argument completion with context
2590 > * {@includeCode ./examples/CompleteRequestParams/prompt-argument-completion-with-context.json}
2591 > */
2592 > export interface CompleteRequestParams extends RequestParams {
2593 > ref: PromptReference | ResourceTemplateReference;
2594 > /**
2595 > * The argument's information
2596 > */
2597 > argument: {
2598 > /**
2599 > * The name of the argument
2600 > */
2601 > name: string;
2602 > /**
2603 > * The value of the argument to use for completion matching.
2604 > */
2605 > value: string;
2606 > };
2607 >
2608 > /**
2609 > * Additional, optional context for completions
2610 > */
2611 > context?: {
2612 > /**
2613 > * Previously-resolved variables in a URI template or prompt.
2614 > */
2615 > arguments?: { [key: string]: string };
2616 > };
2617 > }
2618 >
2619 > /**
2620 > * A request from the client to the server, to ask for completion options.
2621 > *
2622 > * @example Completion request
2623 > * {@includeCode ./examples/CompleteRequest/completion-request.json}
2624 > *
2625 > * @category `completion/complete`
2626 > */
2627 > export interface CompleteRequest extends JSONRPCRequest {
2628 > method: "completion/complete";
2629 > params: CompleteRequestParams;
2630 > }
2631 >
2632 > /**
2633 > * The result returned by the server for a {@link CompleteRequest | completion/complete} request.
2634 > *
2635 > * @category `completion/complete`
2636 > *
2637 > * @example Single completion value
2638 > * {@includeCode ./examples/CompleteResult/single-completion-value.json}
2639 > *
2640 > * @example Multiple completion values with more available
2641 > * {@includeCode ./examples/CompleteResult/multiple-completion-values-with-more-available.json}
2642 > */
2643 > export interface CompleteResult extends Result {
2644 > completion: {
2645 > /**
2646 > * An array of completion values. Must not exceed 100 items.
2647 > */
2648 > values: string[];
2649 > /**
2650 > * The total number of completion options available. This can exceed the number of values actually sent in the response.
2651 > */
2652 > total?: number;
2653 > /**
2654 > * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
2655 > */
2656 > hasMore?: boolean;
2657 > };
2658 > }
2659 >
2660 > /**
2661 > * A successful response from the server for a {@link CompleteRequest | completion/complete} request.
2662 > *
2663 > * @example Completion result response
2664 > * {@includeCode ./examples/CompleteResultResponse/completion-result-response.json}
2665 > *
2666 > * @category `completion/complete`
2667 > */
2668 > export interface CompleteResultResponse extends JSONRPCResultResponse {
2669 > result: CompleteResult;
2670 > }
2671 >
2672 > /**
2673 > * A reference to a resource or resource template definition.
2674 > *
2675 > * @category `completion/complete`
2676 > */
2677 > export interface ResourceTemplateReference {
2678 > type: "ref/resource";
2679 > /**
2680 > * The URI or URI template of the resource.
2681 > *
2682 > * @format uri-template
2683 > */
2684 > uri: string;
2685 > }
2686 >
2687 > /**
2688 > * Identifies a prompt.
2689 > *
2690 > * @category `completion/complete`
2691 > */
2692 > export interface PromptReference extends BaseMetadata {
2693 > type: "ref/prompt";
2694 > }
2695 >
2696 > /* Roots */
2697 > /**
2698 > * Sent from the server to request a list of root URIs from the client. Roots allow
2699 > * servers to ask for specific directories or files to operate on. A common example
2700 > * for roots is providing a set of repositories or directories a server should operate
2701 > * on.
2702 > *
2703 > * This request is typically used when the server needs to understand the file system
2704 > * structure or access specific locations that the client has permission to read from.
2705 > *
2706 > * @example List roots request
2707 > * {@includeCode ./examples/ListRootsRequest/list-roots-request.json}
2708 > *
2709 > * @category `roots/list`
2710 > */
2711 > export interface ListRootsRequest extends JSONRPCRequest {
2712 > method: "roots/list";
2713 > params?: RequestParams;
2714 > }
2715 >
2716 > /**
2717 > * The result returned by the client for a {@link ListRootsRequest | roots/list} request.
2718 > * This result contains an array of {@link Root} objects, each representing a root directory
2719 > * or file that the server can operate on.
2720 > *
2721 > * @example Single root directory
2722 > * {@includeCode ./examples/ListRootsResult/single-root-directory.json}
2723 > *
2724 > * @example Multiple root directories
2725 > * {@includeCode ./examples/ListRootsResult/multiple-root-directories.json}
2726 > *
2727 > * @category `roots/list`
2728 > */
2729 > export interface ListRootsResult extends Result {
2730 > roots: Root[];
2731 > }
2732 >
2733 > /**
2734 > * A successful response from the client for a {@link ListRootsRequest | roots/list} request.
2735 > *
2736 > * @example List roots result response
2737 > * {@includeCode ./examples/ListRootsResultResponse/list-roots-result-response.json}
2738 > *
2739 > * @category `roots/list`
2740 > */
2741 > export interface ListRootsResultResponse extends JSONRPCResultResponse {
2742 > result: ListRootsResult;
2743 > }
2744 >
2745 > /**
2746 > * Represents a root directory or file that the server can operate on.
2747 > *
2748 > * @example Project directory root
2749 > * {@includeCode ./examples/Root/project-directory.json}
2750 > *
2751 > * @category `roots/list`
2752 > */
2753 > export interface Root {
2754 > /**
2755 > * The URI identifying the root. This *must* start with `file://` for now.
2756 > * This restriction may be relaxed in future versions of the protocol to allow
2757 > * other URI schemes.
2758 > *
2759 > * @format uri
2760 > */
2761 > uri: string;
2762 > /**
2763 > * An optional name for the root. This can be used to provide a human-readable
2764 > * identifier for the root, which may be useful for display purposes or for
2765 > * referencing the root in other parts of the application.
2766 > */
2767 > name?: string;
2768 >
2769 > _meta?: MetaObject;
2770 > }
2771 >
2772 > /**
2773 > * A notification from the client to the server, informing it that the list of roots has changed.
2774 > * This notification should be sent whenever the client adds, removes, or modifies any root.
2775 > * The server should then request an updated list of roots using the {@link ListRootsRequest}.
2776 > *
2777 > * @example Roots list changed
2778 > * {@includeCode ./examples/RootsListChangedNotification/roots-list-changed.json}
2779 > *
2780 > * @category `notifications/roots/list_changed`
2781 > */
2782 > export interface RootsListChangedNotification extends JSONRPCNotification {
2783 > method: "notifications/roots/list_changed";
2784 > params?: NotificationParams;
2785 > }
2786 >
2787 > /**
2788 > * The parameters for a request to elicit non-sensitive information from the user via a form in the client.
2789 > *
2790 > * @example Elicit single field
2791 > * {@includeCode ./examples/ElicitRequestFormParams/elicit-single-field.json}
2792 > *
2793 > * @example Elicit multiple fields
2794 > * {@includeCode ./examples/ElicitRequestFormParams/elicit-multiple-fields.json}
2795 > *
2796 > * @category `elicitation/create`
2797 > */
2798 > export interface ElicitRequestFormParams extends TaskAugmentedRequestParams {
2799 > /**
2800 > * The elicitation mode.
2801 > */
2802 > mode?: "form";
2803 >
2804 > /**
2805 > * The message to present to the user describing what information is being requested.
2806 > */
2807 > message: string;
2808 >
2809 > /**
2810 > * A restricted subset of JSON Schema.
2811 > * Only top-level properties are allowed, without nesting.
2812 > */
2813 > requestedSchema: {
2814 > $schema?: string;
2815 > type: "object";
2816 > properties: {
2817 > [key: string]: PrimitiveSchemaDefinition;
2818 > };
2819 > required?: string[];
2820 > };
2821 > }
2822 >
2823 > /**
2824 > * The parameters for a request to elicit information from the user via a URL in the client.
2825 > *
2826 > * @example Elicit sensitive data
2827 > * {@includeCode ./examples/ElicitRequestURLParams/elicit-sensitive-data.json}
2828 > *
2829 > * @category `elicitation/create`
2830 > */
2831 > export interface ElicitRequestURLParams extends TaskAugmentedRequestParams {
2832 > /**
2833 > * The elicitation mode.
2834 > */
2835 > mode: "url";
2836 >
2837 > /**
2838 > * The message to present to the user explaining why the interaction is needed.
2839 > */
2840 > message: string;
2841 >
2842 > /**
2843 > * The ID of the elicitation, which must be unique within the context of the server.
2844 > * The client MUST treat this ID as an opaque value.
2845 > */
2846 > elicitationId: string;
2847 >
2848 > /**
2849 > * The URL that the user should navigate to.
2850 > *
2851 > * @format uri
2852 > */
2853 > url: string;
2854 > }
2855 >
2856 > /**
2857 > * The parameters for a request to elicit additional information from the user via the client.
2858 > *
2859 > * @category `elicitation/create`
2860 > */
2861 > export type ElicitRequestParams =
2862 > | ElicitRequestFormParams
2863 > | ElicitRequestURLParams;
2864 >
2865 > /**
2866 > * A request from the server to elicit additional information from the user via the client.
2867 > *
2868 > * @example Elicitation request
2869 > * {@includeCode ./examples/ElicitRequest/elicitation-request.json}
2870 > *
2871 > * @category `elicitation/create`
2872 > */
2873 > export interface ElicitRequest extends JSONRPCRequest {
2874 > method: "elicitation/create";
2875 > params: ElicitRequestParams;
2876 > }
2877 >
2878 > /**
2879 > * Restricted schema definitions that only allow primitive types
2880 > * without nested objects or arrays.
2881 > *
2882 > * @category `elicitation/create`
2883 > */
2884 > export type PrimitiveSchemaDefinition =
2885 > | StringSchema
2886 > | NumberSchema
2887 > | BooleanSchema
2888 > | EnumSchema;
2889 >
2890 > /**
2891 > * @example Email input schema
2892 > * {@includeCode ./examples/StringSchema/email-input-schema.json}
2893 > *
2894 > * @category `elicitation/create`
2895 > */
2896 > export interface StringSchema {
2897 > type: "string";
2898 > title?: string;
2899 > description?: string;
2900 > minLength?: number;
2901 > maxLength?: number;
2902 > format?: "email" | "uri" | "date" | "date-time";
2903 > default?: string;
2904 > }
2905 >
2906 > /**
2907 > * @example Number input schema
2908 > * {@includeCode ./examples/NumberSchema/number-input-schema.json}
2909 > *
2910 > * @category `elicitation/create`
2911 > */
2912 > export interface NumberSchema {
2913 > type: "number" | "integer";
2914 > title?: string;
2915 > description?: string;
2916 > minimum?: number;
2917 > maximum?: number;
2918 > default?: number;
2919 > }
2920 >
2921 > /**
2922 > * @example Boolean input schema
2923 > * {@includeCode ./examples/BooleanSchema/boolean-input-schema.json}
2924 > *
2925 > * @category `elicitation/create`
2926 > */
2927 > export interface BooleanSchema {
2928 > type: "boolean";
2929 > title?: string;
2930 > description?: string;
2931 > default?: boolean;
2932 > }
2933 >
2934 > /**
2935 > * Schema for single-selection enumeration without display titles for options.
2936 > *
2937 > * @example Color select schema
2938 > * {@includeCode ./examples/UntitledSingleSelectEnumSchema/color-select-schema.json}
2939 > *
2940 > * @category `elicitation/create`
2941 > */
2942 > export interface UntitledSingleSelectEnumSchema {
2943 > type: "string";
2944 > /**
2945 > * Optional title for the enum field.
2946 > */
2947 > title?: string;
2948 > /**
2949 > * Optional description for the enum field.
2950 > */
2951 > description?: string;
2952 > /**
2953 > * Array of enum values to choose from.
2954 > */
2955 > enum: string[];
2956 > /**
2957 > * Optional default value.
2958 > */
2959 > default?: string;
2960 > }
2961 >
2962 > /**
2963 > * Schema for single-selection enumeration with display titles for each option.
2964 > *
2965 > * @example Titled color select schema
2966 > * {@includeCode ./examples/TitledSingleSelectEnumSchema/titled-color-select-schema.json}
2967 > *
2968 > * @category `elicitation/create`
2969 > */
2970 > export interface TitledSingleSelectEnumSchema {
2971 > type: "string";
2972 > /**
2973 > * Optional title for the enum field.
2974 > */
2975 > title?: string;
2976 > /**
2977 > * Optional description for the enum field.
2978 > */
2979 > description?: string;
2980 > /**
2981 > * Array of enum options with values and display labels.
2982 > */
2983 > oneOf: Array<{
2984 > /**
2985 > * The enum value.
2986 > */
2987 > const: string;
2988 > /**
2989 > * Display label for this option.
2990 > */
2991 > title: string;
2992 > }>;
2993 > /**
2994 > * Optional default value.
2995 > */
2996 > default?: string;
2997 > }
2998 >
2999 > /**
3000 > * @category `elicitation/create`
3001 > */
3002 > // Combined single selection enumeration
3003 > export type SingleSelectEnumSchema =
3004 > | UntitledSingleSelectEnumSchema
3005 > | TitledSingleSelectEnumSchema;
3006 >
3007 > /**
3008 > * Schema for multiple-selection enumeration without display titles for options.
3009 > *
3010 > * @example Color multi-select schema
3011 > * {@includeCode ./examples/UntitledMultiSelectEnumSchema/color-multi-select-schema.json}
3012 > *
3013 > * @category `elicitation/create`
3014 > */
3015 > export interface UntitledMultiSelectEnumSchema {
3016 > type: "array";
3017 > /**
3018 > * Optional title for the enum field.
3019 > */
3020 > title?: string;
3021 > /**
3022 > * Optional description for the enum field.
3023 > */
3024 > description?: string;
3025 > /**
3026 > * Minimum number of items to select.
3027 > */
3028 > minItems?: number;
3029 > /**
3030 > * Maximum number of items to select.
3031 > */
3032 > maxItems?: number;
3033 > /**
3034 > * Schema for the array items.
3035 > */
3036 > items: {
3037 > type: "string";
3038 > /**
3039 > * Array of enum values to choose from.
3040 > */
3041 > enum: string[];
3042 > };
3043 > /**
3044 > * Optional default value.
3045 > */
3046 > default?: string[];
3047 > }
3048 >
3049 > /**
3050 > * Schema for multiple-selection enumeration with display titles for each option.
3051 > *
3052 > * @example Titled color multi-select schema
3053 > * {@includeCode ./examples/TitledMultiSelectEnumSchema/titled-color-multi-select-schema.json}
3054 > *
3055 > * @category `elicitation/create`
3056 > */
3057 > export interface TitledMultiSelectEnumSchema {
3058 > type: "array";
3059 > /**
3060 > * Optional title for the enum field.
3061 > */
3062 > title?: string;
3063 > /**
3064 > * Optional description for the enum field.
3065 > */
3066 > description?: string;
3067 > /**
3068 > * Minimum number of items to select.
3069 > */
3070 > minItems?: number;
3071 > /**
3072 > * Maximum number of items to select.
3073 > */
3074 > maxItems?: number;
3075 > /**
3076 > * Schema for array items with enum options and display labels.
3077 > */
3078 > items: {
3079 > /**
3080 > * Array of enum options with values and display labels.
3081 > */
3082 > anyOf: Array<{
3083 > /**
3084 > * The constant enum value.
3085 > */
3086 > const: string;
3087 > /**
3088 > * Display title for this option.
3089 > */
3090 > title: string;
3091 > }>;
3092 > };
3093 > /**
3094 > * Optional default value.
3095 > */
3096 > default?: string[];
3097 > }
3098 >
3099 > /**
3100 > * @category `elicitation/create`
3101 > */
3102 > // Combined multiple selection enumeration
3103 > export type MultiSelectEnumSchema =
3104 > | UntitledMultiSelectEnumSchema
3105 > | TitledMultiSelectEnumSchema;
3106 >
3107 > /**
3108 > * Use {@link TitledSingleSelectEnumSchema} instead.
3109 > * This interface will be removed in a future version.
3110 > *
3111 > * @category `elicitation/create`
3112 > */
3113 > export interface LegacyTitledEnumSchema {
3114 > type: "string";
3115 > title?: string;
3116 > description?: string;
3117 > enum: string[];
3118 > /**
3119 > * (Legacy) Display names for enum values.
3120 > * Non-standard according to JSON schema 2020-12.
3121 > */
3122 > enumNames?: string[];
3123 > default?: string;
3124 > }
3125 >
3126 > /**
3127 > * @category `elicitation/create`
3128 > */
3129 > // Union type for all enum schemas
3130 > export type EnumSchema =
3131 > | SingleSelectEnumSchema
3132 > | MultiSelectEnumSchema
3133 > | LegacyTitledEnumSchema;
3134 >
3135 > /**
3136 > * The result returned by the client for an {@link ElicitRequest | elicitation/create} request.
3137 > *
3138 > * @example Input single field
3139 > * {@includeCode ./examples/ElicitResult/input-single-field.json}
3140 > *
3141 > * @example Input multiple fields
3142 > * {@includeCode ./examples/ElicitResult/input-multiple-fields.json}
3143 > *
3144 > * @example Accept URL mode (no content)
3145 > * {@includeCode ./examples/ElicitResult/accept-url-mode-no-content.json}
3146 > *
3147 > * @category `elicitation/create`
3148 > */
3149 > export interface ElicitResult extends Result {
3150 > /**
3151 > * The user action in response to the elicitation.
3152 > * - `"accept"`: User submitted the form/confirmed the action
3153 > * - `"decline"`: User explicitly declined the action
3154 > * - `"cancel"`: User dismissed without making an explicit choice
3155 > */
3156 > action: "accept" | "decline" | "cancel";
3157 >
3158 > /**
3159 > * The submitted form data, only present when action is `"accept"` and mode was `"form"`.
3160 > * Contains values matching the requested schema.
3161 > * Omitted for out-of-band mode responses.
3162 > */
3163 > content?: { [key: string]: string | number | boolean | string[] };
3164 > }
3165 >
3166 > /**
3167 > * A successful response from the client for a {@link ElicitRequest | elicitation/create} request.
3168 > *
3169 > * @example Elicitation result response
3170 > * {@includeCode ./examples/ElicitResultResponse/elicitation-result-response.json}
3171 > *
3172 > * @category `elicitation/create`
3173 > */
3174 > export interface ElicitResultResponse extends JSONRPCResultResponse {
3175 > result: ElicitResult;
3176 > }
3177 >
3178 > /**
3179 > * An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request.
3180 > *
3181 > * @example Elicitation complete
3182 > * {@includeCode ./examples/ElicitationCompleteNotification/elicitation-complete.json}
3183 > *
3184 > * @category `notifications/elicitation/complete`
3185 > */
3186 > export interface ElicitationCompleteNotification extends JSONRPCNotification {
3187 > method: "notifications/elicitation/complete";
3188 > params: {
3189 > /**
3190 > * The ID of the elicitation that completed.
3191 > */
3192 > elicitationId: string;
3193 > };
3194 > }
3195 >
3196 > /* Client messages */
3197 > /** @internal */
3198 > export type ClientRequest =
3199 > | PingRequest
3200 > | InitializeRequest
3201 > | CompleteRequest
3202 > | SetLevelRequest
3203 > | GetPromptRequest
3204 > | ListPromptsRequest
3205 > | ListResourcesRequest
3206 > | ListResourceTemplatesRequest
3207 > | ReadResourceRequest
3208 > | SubscribeRequest
3209 > | UnsubscribeRequest
3210 > | CallToolRequest
3211 > | ListToolsRequest
3212 > | GetTaskRequest
3213 > | GetTaskPayloadRequest
3214 > | ListTasksRequest
3215 > | CancelTaskRequest;
3216 >
3217 > /** @internal */
3218 > export type ClientNotification =
3219 > | CancelledNotification
3220 > | ProgressNotification
3221 > | InitializedNotification
3222 > | RootsListChangedNotification
3223 > | TaskStatusNotification;
3224 >
3225 > /** @internal */
3226 > export type ClientResult =
3227 > | EmptyResult
3228 > | CreateMessageResult
3229 > | ListRootsResult
3230 > | ElicitResult
3231 > | GetTaskResult
3232 > | GetTaskPayloadResult
3233 > | ListTasksResult
3234 > | CancelTaskResult;
3235 >
3236 > /* Server messages */
3237 > /** @internal */
3238 > export type ServerRequest =
3239 > | PingRequest
3240 > | CreateMessageRequest
3241 > | ListRootsRequest
3242 > | ElicitRequest
3243 > | GetTaskRequest
3244 > | GetTaskPayloadRequest
3245 > | ListTasksRequest
3246 > | CancelTaskRequest;
3247 >
3248 > /** @internal */
3249 > export type ServerNotification =
3250 > | CancelledNotification
3251 > | ProgressNotification
3252 > | LoggingMessageNotification
3253 > | ResourceUpdatedNotification
3254 > | ResourceListChangedNotification
3255 > | ToolListChangedNotification
3256 > | PromptListChangedNotification
3257 > | ElicitationCompleteNotification
3258 > | TaskStatusNotification;
3259 >
3260 > /** @internal */
3261 > export type ServerResult =
3262 > | EmptyResult
3263 > | InitializeResult
3264 > | CompleteResult
3265 > | GetPromptResult
3266 > | ListPromptsResult
3267 > | ListResourceTemplatesResult
3268 > | ListResourcesResult
3269 > | ReadResourceResult
3270 > | CallToolResult
3271 > | CreateTaskResult
3272 > | ListToolsResult
3273 > | GetTaskResult
3274 > | GetTaskPayloadResult
3275 > | ListTasksResult
3276 > | CancelTaskResult;
3277 > }
src/vs/workbench/contrib/mcp/common/mcpTypes.ts 935 introduced LOC · 31 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- mcpTypes.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { equals as arraysEqual } from '../../../../base/common/arrays.js';
7 > import { assertNever } from '../../../../base/common/assert.js';
8 > import { decodeHex, encodeHex, VSBuffer } from '../../../../base/common/buffer.js';
9 > import { CancellationToken } from '../../../../base/common/cancellation.js';
10 > import { Event } from '../../../../base/common/event.js';
11 > import { IMarkdownString } from '../../../../base/common/htmlContent.js';
12 > import { Disposable, IDisposable } from '../../../../base/common/lifecycle.js';
13 > import { equals as objectsEqual } from '../../../../base/common/objects.js';
14 > import { IObservable, ObservableMap } from '../../../../base/common/observable.js';
15 > import { IIterativePager } from '../../../../base/common/paging.js';
16 > import Severity from '../../../../base/common/severity.js';
17 > import { URI, UriComponents } from '../../../../base/common/uri.js';
18 > import { Location } from '../../../../editor/common/languages.js';
19 > import { localize } from '../../../../nls.js';
20 > import { ConfigurationTarget } from '../../../../platform/configuration/common/configuration.js';
21 > import { RawContextKey } from '../../../../platform/contextkey/common/contextkey.js';
22 > import { IEditorOptions } from '../../../../platform/editor/common/editor.js';
23 > import { ExtensionIdentifier } from '../../../../platform/extensions/common/extensions.js';
24 > import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js';
25 > import { McpGalleryManifestStatus } from '../../../../platform/mcp/common/mcpGalleryManifest.js';
26 > import { IGalleryMcpServer, IGalleryMcpServerConfiguration, IInstallableMcpServer, IQueryOptions } from '../../../../platform/mcp/common/mcpManagement.js';
27 > import { IMcpDevModeConfig, IMcpSandboxConfiguration, IMcpServerConfiguration } from '../../../../platform/mcp/common/mcpPlatformTypes.js';
28 > import { StorageScope } from '../../../../platform/storage/common/storage.js';
29 > import { IWorkspaceFolder, IWorkspaceFolderData } from '../../../../platform/workspace/common/workspace.js';
30 > import { IWorkbenchLocalMcpServer, IWorkbencMcpServerInstallOptions, WORKSPACE_FOLDER_CONFIG_ID_PREFIX } from '../../../services/mcp/common/mcpWorkbenchManagementService.js';
31 > import { ContributionEnablementState, IEnablementModel } from '../../chat/common/enablement.js';
32 > import { ToolProgress } from '../../chat/common/tools/languageModelToolsService.js';
33 > import { IMcpServerSamplingConfiguration } from './mcpConfiguration.js';
34 > import { McpServerRequestHandler } from './mcpServerRequestHandler.js';
35 > import { MCP } from './modelContextProtocol.js';
36 > import { UriTemplate } from '../../../../base/common/uriTemplate.js';
37 >
38 > export const extensionMcpCollectionPrefix = 'ext.';
39 >
40 > /**
41 > * Prefix of the collection id used for MCP servers configured via the various
42 > * `mcp.json`-style config files (user, remote user, workspace, and
43 > * `.vscode/mcp.json` workspace-folder configs). The suffix is the
44 > * {@link IMcpConfigPath.id} of the originating config path.
45 > */
46 > export const MCP_CONFIGURATION_COLLECTION_ID_PREFIX = 'mcp.config.';
47 >
48 > export function extensionPrefixedIdentifier(identifier: ExtensionIdentifier, id: string): string {
49 return ExtensionIdentifier.toKey(identifier) + '/' + id;
50 }
52 > /**
53 > * An McpCollection contains McpServers. There may be multiple collections for
54 > * different locations servers are discovered.
55 > */
56 > export interface McpCollectionDefinition {
57 > /** Origin authority from which this collection was discovered. */
58 > readonly remoteAuthority: string | null;
59 > /** Globally-unique, stable ID for this definition */
60 > readonly id: string;
61 > /** Human-readable label for the definition */
62 > readonly label: string;
63 > /** Definitions this collection contains. */
64 > readonly serverDefinitions: IObservable<readonly McpServerDefinition[]>;
65 > /**
66 > * Trust behavior of the servers. `Trusted` means it will run without a prompt, always.
67 > * `TrustedOnNonce` means it will run without a prompt as long as the nonce matches.
68 > */
69 > readonly trustBehavior: McpServerTrust.Kind.Trusted | McpServerTrust.Kind.TrustedOnNonce;
70 > /** Scope where associated collection info should be stored. */
71 > readonly scope: StorageScope;
72 > /** Configuration target where configuration related to this server should be stored. */
73 > readonly configTarget: ConfigurationTarget;
74 > /** Root-level sandbox settings from the mcp config file. */
75 > readonly sandbox?: IMcpSandboxConfiguration;
76 >
77 > /** Resolves a server definition. If present, always called before a server starts. */
78 > resolveServerLanch?(definition: McpServerDefinition): Promise<McpServerLaunch | undefined>;
79 >
80 > /** For lazy-loaded collections only: */
81 > readonly lazy?: {
82 > /** True if `serverDefinitions` were loaded from the cache */
83 > isCached: boolean;
84 > /** Triggers a load of the real server definition, which should be pushed to the IMcpRegistry. If not this definition will be removed. */
85 > load(): Promise<void>;
86 > /** Called after `load()` if the extension is not found. */
87 > removed?(): void;
88 > };
89 >
90 > readonly source?: IWorkbenchMcpServer | ExtensionIdentifier;
91 >
92 > /** Sort order of the collection. Lower values have higher priority. */
93 > readonly order: number;
94 >
95 > readonly presentation?: {
96 > /** Place where this collection is configured, used in workspace trust prompts and "show config" */
97 > readonly origin?: URI;
98 > };
99 > }
100 >
101 > export const enum McpCollectionSortOrder {
102 > WorkspaceFolder = 0,
103 > Workspace = 100,
104 > User = 200,
105 > Extension = 300,
106 > Plugin = 350,
107 > Filesystem = 400,
108 >
109 > RemoteBoost = -50,
110 > }
111 >
112 > export namespace McpCollectionDefinition {
113 > export interface FromExtHost {
114 > readonly id: string;
115 > readonly label: string;
116 > readonly isTrustedByDefault: boolean;
117 > readonly scope: StorageScope;
118 > readonly canResolveLaunch: boolean;
119 > readonly extensionId: string;
120 > readonly configTarget: ConfigurationTarget;
121 > }
122 >
123 > export function equals(a: McpCollectionDefinition, b: McpCollectionDefinition): boolean {
124 return a.id === b.id
125 && a.remoteAuthority === b.remoteAuthority
128 && objectsEqual(a.sandbox, b.sandbox);
129 }
130 > mcpTypes.ts
131 > /**
132 > * Returns `true` when the collection was discovered from the workspace (its
133 > * config target is the workspace or a workspace folder). This is
134 > * intentionally based on the config target and not the storage scope:
135 > * extension-contributed collections use a workspace storage scope but are
136 > * configured at the user level, so they are not workspace-discovered.
137 > */
138 > export function isWorkspaceDiscovered(collection: McpCollectionDefinition): boolean {
139 return collection.configTarget === ConfigurationTarget.WORKSPACE
140 || collection.configTarget === ConfigurationTarget.WORKSPACE_FOLDER;
141 }
142 > mcpTypes.ts
143 > /**
144 > * Returns `true` when the collection originates from a `.vscode/mcp.json`
145 > * workspace-folder config, identified by its collection id prefix (the
146 > * shared `mcp.config.` prefix plus the workspace-folder config id).
147 > */
148 > export function isVscodeMcpJson(collection: McpCollectionDefinition): boolean {
149 return collection.id.startsWith(`${MCP_CONFIGURATION_COLLECTION_ID_PREFIX}${WORKSPACE_FOLDER_CONFIG_ID_PREFIX}`);
150 }
151 > } mcpTypes.ts
152 >
153 > export interface McpServerDefinition {
154 > /** Globally-unique, stable ID for this definition */
155 > readonly id: string;
156 > /** Human-readable label for the definition */
157 > readonly label: string;
158 > /** Descriptor defining how the configuration should be launched. */
159 > readonly launch: McpServerLaunch;
160 > /** Explicit roots. If undefined, all workspace folders. */
161 > readonly roots?: URI[] | undefined;
162 > /** If set, allows configuration variables to be resolved in the {@link launch} with the given context */
163 > readonly variableReplacement?: McpServerDefinitionVariableReplacement;
164 > /** Nonce used for caching the server. Changing the nonce will indicate that tools need to be refreshed. */
165 > readonly cacheNonce: string;
166 > /** Dev mode configuration for the server */
167 > readonly devMode?: IMcpDevModeConfig;
168 > /** Static description of server tools/data, used to hydrate the cache. */
169 > readonly staticMetadata?: McpServerStaticMetadata;
170 > /** Indicates if the sandbox is enabled for this server. */
171 > readonly sandboxEnabled?: boolean;
172 >
173 >
174 > readonly presentation?: {
175 > /** Sort order of the definition. */
176 > readonly order?: number;
177 > /** Place where this server is configured, used in workspace trust prompts and "show config" */
178 > readonly origin?: Location;
179 > };
180 > }
181 >
182 > export const enum McpServerStaticToolAvailability {
183 > /** Tool is expected to be present as soon as the server is started. */
184 > Initial,
185 > /** Tool may be present later. */
186 > Dynamic,
187 > }
188 >
189 > export interface McpServerStaticMetadata {
190 > tools?: { availability: McpServerStaticToolAvailability; definition: MCP.Tool }[];
191 > instructions?: string;
192 > capabilities?: MCP.ServerCapabilities;
193 > serverInfo?: MCP.Implementation;
194 > }
195 >
196 > export namespace McpServerDefinition {
197 > export interface Serialized {
198 > readonly id: string;
199 > readonly label: string;
200 > readonly cacheNonce: string;
201 > readonly launch: McpServerLaunch.Serialized;
202 > readonly variableReplacement?: McpServerDefinitionVariableReplacement.Serialized;
203 > readonly staticMetadata?: McpServerStaticMetadata;
204 > readonly sandboxEnabled?: boolean;
205 > }
206 >
207 > export function toSerialized(def: McpServerDefinition): McpServerDefinition.Serialized {
208 return def;
209 }
210 > mcpTypes.ts
211 > export function fromSerialized(def: McpServerDefinition.Serialized): McpServerDefinition {
212 return {
213 id: def.id,
220 };
221 }
222 > mcpTypes.ts
223 > export function equals(a: McpServerDefinition, b: McpServerDefinition): boolean {
224 return a.id === b.id
225 && a.label === b.label
233
234 }
235 > } mcpTypes.ts
236 >
237 >
238 > export interface McpServerDefinitionVariableReplacement {
239 > section?: string; // e.g. 'mcp'
240 > folder?: IWorkspaceFolderData;
241 > target: ConfigurationTarget;
242 > }
243 >
244 > export namespace McpServerDefinitionVariableReplacement {
245 > export interface Serialized {
246 > target: ConfigurationTarget;
247 > section?: string;
248 > folder?: { name: string; index: number; uri: UriComponents };
249 > }
250 >
251 > export function toSerialized(def: McpServerDefinitionVariableReplacement): McpServerDefinitionVariableReplacement.Serialized {
252 return def;
253 }
254 > mcpTypes.ts
255 > export function fromSerialized(def: McpServerDefinitionVariableReplacement.Serialized): McpServerDefinitionVariableReplacement {
256 return {
257 section: def.section,
260 };
261 }
262 > } mcpTypes.ts
263 >
264 > /** An observable of the auto-starting servers. When 'starting' is empty, the operation is complete. */
265 > export interface IAutostartResult {
266 > working: boolean;
267 > starting: McpDefinitionReference[];
268 > serversRequiringInteraction: Array<McpDefinitionReference & { errorMessage?: string }>;
269 > }
270 >
271 > export namespace IAutostartResult {
272 > export const Empty: IAutostartResult = { working: false, starting: [], serversRequiringInteraction: [] };
273 > }
274 >
275 > export interface IMcpService {
276 > _serviceBrand: undefined;
277 > readonly servers: IObservable<readonly IMcpServer[]>;
278 >
279 > /** The enablement model for MCP servers. */
280 > readonly enablementModel: IEnablementModel;
281 >
282 > /** Resets the cached tools. */
283 > resetCaches(): void;
284 >
285 > /** Resets trusted MCP servers. */
286 > resetTrust(): void;
287 >
288 > /** Set if there are extensions that register MCP servers that have never been activated. */
289 > readonly lazyCollectionState: IObservable<{ state: LazyCollectionState; collections: McpCollectionDefinition[] }>;
290 >
291 > /** Auto-starts pending servers based on user settings. */
292 > autostart(token?: CancellationToken): IObservable<IAutostartResult>;
293 >
294 > /** Cancels any current autostart @internal */
295 > cancelAutostart(): void;
296 >
297 > /** Activates extension-providing MCP servers that have not yet been discovered. */
298 > activateCollections(): Promise<void>;
299 > }
300 >
301 > export const enum LazyCollectionState {
302 > HasUnknown,
303 > LoadingUnknown,
304 > AllKnown,
305 > }
306 >
307 > export const IMcpService = createDecorator<IMcpService>('IMcpService');
308 >
309 > export interface McpCollectionReference {
310 > id: string;
311 > label: string;
312 > order: number;
313 > presentation?: McpCollectionDefinition['presentation'];
314 > }
315 >
316 > export interface McpDefinitionReference {
317 > id: string;
318 > label: string;
319 > }
320 >
321 > export class McpStartServerInteraction {
322 /** @internal */
323 public readonly participants = new ObservableMap</* server definition ID */ string, { s: 'unknown' | 'resolved' } | { s: 'waiting'; definition: McpServerDefinition; collection: McpCollectionDefinition }>();
324 > choice?: Promise<string[] | undefined>; mcpTypes.ts
325 > }
326 >
327 > export interface IMcpServerStartOpts {
328 > /**
329 > * Automatically trust if changed. This should ONLY be set for afforances that
330 > * ensure the user sees the config before it gets started (e.g. code lenses)
331 > */
332 > autoTrustChanges?: boolean;
333 > /**
334 > * When to trigger the trust prompt.
335 > * - only-new: only prompt for servers that are not previously explicitly untrusted (default)
336 > * - all-untrusted: prompt for all servers that are not trusted
337 > * - never: don't prompt, fail silently when trying to start an untrusted server
338 > */
339 > promptType?: 'only-new' | 'all-untrusted' | 'never';
340 > /** True if th servre should be launched with debugging. */
341 > debug?: boolean;
342 > /** Correlate multiple interactions such that any trust prompts are presented in combination. */
343 > interaction?: McpStartServerInteraction;
344 > /**
345 > * If true, throw an error if any user interaction would be required during startup.
346 > * This includes variable resolution, trust prompts, and authentication prompts.
347 > */
348 > errorOnUserInteraction?: boolean;
349 > }
350 >
351 > export namespace McpServerTrust {
352 > export const enum Kind {
353 > /** The server is trusted */
354 > Trusted,
355 > /** The server is trusted as long as its nonce matches */
356 > TrustedOnNonce,
357 > /** The server trust was denied. */
358 > Untrusted,
359 > /** The server is not yet trusted or untrusted. */
360 > Unknown,
361 > }
362 > }
363 >
364 > export interface IMcpServer extends IDisposable {
365 > readonly collection: McpCollectionReference;
366 > readonly definition: McpDefinitionReference;
367 > readonly enablement: IObservable<ContributionEnablementState>;
368 > readonly connection: IObservable<IMcpServerConnection | undefined>;
369 > readonly connectionState: IObservable<McpConnectionState>;
370 > readonly serverMetadata: IObservable<{
371 > serverName?: string;
372 > serverInstructions?: string;
373 > icons: IMcpIcons;
374 > } | undefined>;
375 >
376 > /**
377 > * Full definition as it exists in the MCP registry. Unlike the references
378 > * in `collection` and `definition`, this may change over time.
379 > */
380 > readDefinitions(): IObservable<{ server: McpServerDefinition | undefined; collection: McpCollectionDefinition | undefined }>;
381 >
382 > showOutput(preserveFocus?: boolean): Promise<void>;
383 > /**
384 > * Starts the server and returns its resulting state. One of:
385 > * - Running, if all good
386 > * - Error, if the server failed to start
387 > * - Stopped, if the server was disposed or the user cancelled the launch
388 > */
389 > start(opts?: IMcpServerStartOpts): Promise<McpConnectionState>;
390 > stop(): Promise<void>;
391 >
392 > readonly cacheState: IObservable<McpServerCacheState>;
393 > readonly tools: IObservable<readonly IMcpTool[]>;
394 > readonly prompts: IObservable<readonly IMcpPrompt[]>;
395 > readonly capabilities: IObservable<McpCapability | undefined>;
396 >
397 > /**
398 > * Lists all resources on the server.
399 > */
400 > resources(token?: CancellationToken): AsyncIterable<IMcpResource[]>;
401 >
402 > /**
403 > * List resource templates on the server.
404 > */
405 > resourceTemplates(token?: CancellationToken): Promise<IMcpResourceTemplate[]>;
406 > }
407 >
408 > /**
409 > * A representation of an MCP resource. The `uri` is namespaced to VS Code and
410 > * can be used in filesystem APIs.
411 > */
412 > export interface IMcpResource {
413 > /** Identifier for the file in VS Code and operable with filesystem API */
414 > readonly uri: URI;
415 > /** Identifier of the file as given from the MCP server. */
416 > readonly mcpUri: string;
417 > readonly name: string;
418 > readonly title?: string;
419 > readonly description?: string;
420 > readonly mimeType?: string;
421 > readonly sizeInBytes?: number;
422 > readonly icons: IMcpIcons;
423 > }
424 >
425 > export interface IMcpResourceTemplate {
426 > readonly name: string;
427 > readonly title?: string;
428 > readonly description?: string;
429 > readonly mimeType?: string;
430 > readonly template: UriTemplate;
431 > readonly icons: IMcpIcons;
432 >
433 > /** Gets string completions for the given template part. */
434 > complete(templatePart: string, prefix: string, alreadyResolved: Record<string, string | string[]>, token: CancellationToken): Promise<string[]>;
435 >
436 > /** Gets the resolved URI from template parts. */
437 > resolveURI(vars: Record<string, unknown>): URI;
438 > }
439 >
440 > export const isMcpResourceTemplate = (obj: IMcpResource | IMcpResourceTemplate): obj is IMcpResourceTemplate => {
441 return (obj as IMcpResourceTemplate).template !== undefined;
442 };
443 > export const isMcpResource = (obj: IMcpResource | IMcpResourceTemplate): obj is IMcpResource => { mcpTypes.ts
444 return (obj as IMcpResource).mcpUri !== undefined;
445 };
446 > mcpTypes.ts
447 > export const enum McpServerCacheState {
448 > /** Tools have not been read before */
449 > Unknown,
450 > /** Tools were read from the cache */
451 > Cached,
452 > /** Tools were read from the cache or live, but they may be outdated. */
453 > Outdated,
454 > /** Tools are refreshing for the first time */
455 > RefreshingFromUnknown,
456 > /** Tools are refreshing and the current tools are cached */
457 > RefreshingFromCached,
458 > /** Tool state is live, server is connected */
459 > Live,
460 > }
461 >
462 > export interface IMcpPrompt {
463 > readonly id: string;
464 > readonly name: string;
465 > readonly title?: string;
466 > readonly description?: string;
467 > readonly arguments: readonly MCP.PromptArgument[];
468 >
469 > /** Gets string completions for the given prompt part. */
470 > complete(argument: string, prefix: string, alreadyResolved: Record<string, string>, token: CancellationToken): Promise<string[]>;
471 >
472 > resolve(args: Record<string, string | undefined>, token?: CancellationToken): Promise<IMcpPromptMessage[]>;
473 > }
474 >
475 > export const mcpPromptReplaceSpecialChars = (s: string) => s.replace(/[^a-z0-9_.-]/gi, '_');
476 >
477 > export const mcpPromptPrefix = (definition: McpDefinitionReference) =>
478 `/mcp.` + mcpPromptReplaceSpecialChars(definition.label);
479 > mcpTypes.ts
480 > export interface IMcpPromptMessage extends MCP.PromptMessage { }
481 >
482 > export interface IMcpToolCallContext {
483 > chatSessionResource: URI | undefined;
484 > chatRequestId?: string;
485 > /**
486 > * Optional W3C trace context `traceparent` value to forward to the MCP server
487 > * via `_meta.traceparent` on the JSON-RPC `tools/call` request (MCP SEP-414).
488 > */
489 > traceparent?: string;
490 > /** Optional W3C trace context `tracestate` value paired with {@link traceparent}. */
491 > tracestate?: string;
492 > }
493 >
494 > /**
495 > * Visibility of an MCP tool, based on the MCP Apps `_meta.ui.visibility` field.
496 > * @see https://github.com/anthropics/mcp/blob/main/apps.md
497 > */
498 > export const enum McpToolVisibility {
499 > /** Tool is visible to and callable by the language model */
500 > Model = 1 << 0,
501 > /** Tool is callable by the MCP App UI */
502 > App = 1 << 1,
503 > }
504 >
505 > /**
506 > * Serializable data for MCP App UI rendering.
507 > * This contains all the information needed to render an MCP App webview.
508 > *
509 > * The transport for the App's sub-RPCs (`tools/call`, `resources/read`,
510 > * `sampling/createMessage`, …) is determined by the discriminator:
511 > *
512 > * - `local`: resolves the MCP server via {@link IMcpService} from
513 > * `serverDefinitionId` + `collectionId`. Used for locally-configured
514 > * MCP servers.
515 > * - `agentHost`: routes through {@link IAgentHostService.handleMcpRequest}
516 > * on the AHP `mcp://` side `channel`. Used for MCP servers owned by
517 > * an agent host.
518 > */
519 > export type IMcpToolCallUIData =
520 > | {
521 > readonly kind: 'local';
522 > /** URI of the UI resource for rendering (e.g., "ui://weather-server/dashboard") */
523 > readonly resourceUri: string;
524 > /** Reference to the server definition for reconnection */
525 > readonly serverDefinitionId: string;
526 > /** Reference to the collection containing the server */
527 > readonly collectionId: string;
528 > }
529 > | {
530 > readonly kind: 'agentHost';
531 > /** URI of the UI resource for rendering (e.g., "ui://weather-server/dashboard") */
532 > readonly resourceUri: string;
533 > /** AHP `mcp://` channel URI for the originating server. */
534 > readonly channel: string;
535 > /** Stable identifier for the originating server (used as webview origin key). */
536 > readonly serverId: string;
537 > };
538 >
539 > export interface IMcpTool {
540 >
541 > readonly id: string;
542 > /** Name for #referencing in chat */
543 > readonly referenceName: string;
544 > readonly icons: IMcpIcons;
545 > readonly definition: MCP.Tool;
546 > /** Visibility of the tool (Model, App, or both). Defaults to Model | App. */
547 > readonly visibility: McpToolVisibility;
548 > /** Optional UI resource URI for MCP App rendering */
549 > readonly uiResourceUri?: string;
550 >
551 > /**
552 > * Calls a tool
553 > * @throws {@link MpcResponseError} if the tool fails to execute
554 > * @throws {@link McpConnectionFailedError} if the connection to the server fails
555 > */
556 > call(params: Record<string, unknown>, context?: IMcpToolCallContext, token?: CancellationToken): Promise<MCP.CallToolResult>;
557 >
558 > /**
559 > * Identical to {@link call}, but reports progress.
560 > */
561 > callWithProgress(params: Record<string, unknown>, progress: ToolProgress, context?: IMcpToolCallContext, token?: CancellationToken): Promise<MCP.CallToolResult>;
562 > }
563 >
564 > export const enum McpServerTransportType {
565 > /** A command-line MCP server communicating over standard in/out */
566 > Stdio = 1 << 0,
567 > /** An MCP server that uses Server-Sent Events */
568 > HTTP = 1 << 1,
569 > }
570 >
571 > /**
572 > * MCP server launched on the command line which communicated over stdio.
573 > * https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#stdio
574 > */
575 > export interface McpServerTransportStdio {
576 > readonly type: McpServerTransportType.Stdio;
577 > readonly cwd: string | undefined;
578 > readonly command: string;
579 > readonly args: readonly string[];
580 > readonly env: Record<string, string | number | null>;
581 > readonly envFile: string | undefined;
582 > readonly sandbox: IMcpSandboxConfiguration | undefined;
583 > }
584 >
585 > export interface McpServerTransportHTTPAuthentication {
586 > /**
587 > * Authentication provider ID to use to get a session for the initial MCP server connection.
588 > */
589 > readonly providerId: string;
590 > /**
591 > * Scopes to use to get a session for the initial MCP server connection.
592 > */
593 > readonly scopes: string[];
594 > }
595 >
596 > export interface McpServerTransportHTTPOAuth {
597 > readonly clientId?: string;
598 > /**
599 > * (Preview) When true, the MCP server uses enterprise-managed authentication via the configured
600 > * SSO issuer (see `mcp.enterpriseManagedAuth.idp`). Tokens are obtained through OAuth Identity
601 > * Assertion Authorization Grant (ID-JAG) so that, after a one-time sign-in, subsequent enterprise-managed
602 > * servers connect silently.
603 > */
604 > readonly enterpriseManaged?: boolean;
605 > }
606 >
607 > /**
608 > * Returns the secret-storage key under which an MCP server OAuth client secret is stored.
609 > * Scoped by the MCP server URL AND the OAuth client_id so that two servers sharing the same
610 > * client_id string (e.g. against different authorization servers) cannot clobber each other's
611 > * secret, and so the key is stable across mcp.json configurations that happen to share a label
612 > * (e.g. user mcp.json vs. workspace mcp.json). Set by the "Set Client Secret" code lens in
613 > * mcp.json and read at authentication time so that client secrets are never stored in
614 > * plain-text config files.
615 > */
616 > export function mcpOAuthClientSecretStorageKey(mcpServerUrl: string, clientId: string): string {
617 return `mcp.oauth.clientSecret:${mcpServerUrl}:${clientId}`;
618 }
619 > mcpTypes.ts
620 > /**
621 > * MCP server launched on the command line which communicated over SSE or Streamable HTTP.
622 > * https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#http-with-sse
623 > * https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http
624 > */
625 > export interface McpServerTransportHTTP {
626 > readonly type: McpServerTransportType.HTTP;
627 > readonly uri: URI;
628 > readonly headers: [string, string][];
629 > readonly oauth?: McpServerTransportHTTPOAuth;
630 > /**
631 > * @deprecated this was originally used for step-auth auth but a different approach was used instead
632 > * so it's effectively dead code.
633 > */
634 > readonly authentication?: McpServerTransportHTTPAuthentication;
635 > }
636 >
637 > export type McpServerLaunch =
638 > | McpServerTransportStdio
639 > | McpServerTransportHTTP;
640 >
641 > export namespace McpServerLaunch {
642 > export type Serialized =
643 > | { type: McpServerTransportType.HTTP; uri: UriComponents; headers: [string, string][]; oauth?: McpServerTransportHTTPOAuth; authentication?: McpServerTransportHTTPAuthentication }
644 > | { type: McpServerTransportType.Stdio; cwd: string | undefined; command: string; args: readonly string[]; env: Record<string, string | number | null>; envFile: string | undefined; sandbox: IMcpSandboxConfiguration | undefined };
645 >
646 > export function toSerialized(launch: McpServerLaunch): McpServerLaunch.Serialized {
647 return launch;
648 }
649 > mcpTypes.ts
650 > export function fromSerialized(launch: McpServerLaunch.Serialized): McpServerLaunch {
651 switch (launch.type) {
652 case McpServerTransportType.HTTP:
664 }
665 }
666 > mcpTypes.ts
667 > export async function hash(launch: McpServerLaunch): Promise<string> {
668 const nonce = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(launch)));
669 return encodeHex(VSBuffer.wrap(new Uint8Array(nonce)));
670 }
671 > } mcpTypes.ts
672 >
673 > /**
674 > * An instance that manages a connection to an MCP server. It can be started,
675 > * stopped, and restarted. Once started and in a running state, it will
676 > * eventually build a {@link IMcpServerConnection.handler}.
677 > */
678 > export interface IMcpPotentialSandboxBlock {
679 > readonly kind: 'network' | 'filesystem';
680 > readonly message: string;
681 > readonly host?: string;
682 > readonly path?: string;
683 > }
684 >
685 > export interface IMcpServerConnection extends IDisposable {
686 > readonly definition: McpServerDefinition;
687 > readonly state: IObservable<McpConnectionState>;
688 > readonly handler: IObservable<McpServerRequestHandler | undefined>;
689 > readonly onPotentialSandboxBlock: Event<IMcpPotentialSandboxBlock>;
690 >
691 > /**
692 > * Resolved launch definition. Might not match the `definition.launch` due to
693 > * resolution logic in extension-provided MCPs.
694 > */
695 > readonly launchDefinition: McpServerLaunch;
696 >
697 > /**
698 > * Starts the server if it's stopped. Returns a promise that resolves once
699 > * server exits a 'starting' state.
700 > */
701 > start(methods: IMcpClientMethods): Promise<McpConnectionState>;
702 >
703 > /**
704 > * Stops the server.
705 > */
706 > stop(): Promise<void>;
707 > }
708 >
709 > /** Client methods whose implementations are passed through the server connection. */
710 > export interface IMcpClientMethods {
711 > /** Handler for `sampling/createMessage` */
712 > createMessageRequestHandler?(req: MCP.CreateMessageRequest['params'], token?: CancellationToken): Promise<MCP.CreateMessageResult>;
713 > /** Handler for `elicitation/create` */
714 > elicitationRequestHandler?(req: MCP.ElicitRequest['params'], token?: CancellationToken): Promise<MCP.ElicitResult>;
715 > }
716 >
717 > /**
718 > * McpConnectionState is the state of the underlying connection and is
719 > * communicated e.g. from the extension host to the renderer.
720 > */
721 > export namespace McpConnectionState {
722 > export const enum Kind {
723 > Stopped,
724 > Starting,
725 > Running,
726 > Error,
727 > }
728 >
729 > export const toString = (s: McpConnectionState): string => {
730 switch (s.state) {
731 case Kind.Stopped:
741 }
742 };
743 > mcpTypes.ts
744 > export const toKindString = (s: McpConnectionState.Kind): string => {
745 switch (s) {
746 case Kind.Stopped:
756 }
757 };
758 > mcpTypes.ts
759 > /** Returns if the MCP state is one where starting a new server is valid */
760 > export const canBeStarted = (s: Kind) => s === Kind.Error || s === Kind.Stopped;
761 >
762 > /** Gets whether the state is a running state. */
763 > export const isRunning = (s: McpConnectionState) => !canBeStarted(s.state);
764 >
765 > export interface Stopped {
766 > readonly state: Kind.Stopped;
767 > readonly reason?: 'needs-user-interaction';
768 > }
769 >
770 > export interface Starting {
771 > readonly state: Kind.Starting;
772 > }
773 >
774 > export interface Running {
775 > readonly state: Kind.Running;
776 > }
777 >
778 > export interface Error {
779 > readonly state: Kind.Error;
780 > readonly code?: string;
781 > readonly shouldRetry?: boolean;
782 > readonly message: string;
783 > }
784 > }
785 >
786 > export type McpConnectionState =
787 > | McpConnectionState.Stopped
788 > | McpConnectionState.Starting
789 > | McpConnectionState.Running
790 > | McpConnectionState.Error;
791 >
792 > export class MpcResponseError extends Error {
793 > constructor(message: string, public readonly code: number, public readonly data: unknown) {
794 super(`MPC ${code}: ${message}`);
795 }
796 > } mcpTypes.ts
797 >
798 > export class McpConnectionFailedError extends Error { }
799 >
800 > export class UserInteractionRequiredError extends Error {
801 > private static readonly prefix = 'User interaction required: ';
802 >
803 > public static is(error: Error): boolean {
804 return error.message.startsWith(this.prefix);
805 }
806 > mcpTypes.ts
807 > constructor(public readonly reason: string) {
808 super(`${UserInteractionRequiredError.prefix}${reason}`);
809 }
810 > } mcpTypes.ts
811 >
812 > export interface IMcpConfigPath {
813 > id: string;
814 > key: 'userLocalValue' | 'userRemoteValue' | 'workspaceValue' | 'workspaceFolderValue';
815 > label: string;
816 > scope: StorageScope;
817 > target: ConfigurationTarget;
818 > order: number;
819 > remoteAuthority?: string;
820 > uri: URI | undefined;
821 > section?: string[];
822 > workspaceFolder?: IWorkspaceFolder;
823 > }
824 >
825 > export interface IMcpServerContainer extends IDisposable {
826 > mcpServer: IWorkbenchMcpServer | null;
827 > update(): void;
828 > }
829 >
830 > export interface IMcpServerEditorOptions extends IEditorOptions {
831 > tab?: McpServerEditorTab;
832 > sideByside?: boolean;
833 > }
834 >
835 > export const enum McpServerEnablementState {
836 > Disabled,
837 > DisabledByAccess,
838 > DisabledProfile,
839 > DisabledWorkspace,
840 > Enabled,
841 > }
842 >
843 > export const enum McpServerInstallState {
844 > Installing,
845 > Installed,
846 > Uninstalling,
847 > Uninstalled
848 > }
849 >
850 > export const enum McpServerEditorTab {
851 > Readme = 'readme',
852 > Manifest = 'manifest',
853 > Configuration = 'configuration',
854 > }
855 >
856 > export type McpServerEnablementStatus = {
857 > readonly state: McpServerEnablementState;
858 > readonly message?: {
859 > readonly severity: Severity;
860 > readonly text: IMarkdownString;
861 > };
862 > };
863 >
864 > export interface IWorkbenchMcpServer {
865 > readonly gallery: IGalleryMcpServer | undefined;
866 > readonly local: IWorkbenchLocalMcpServer | undefined;
867 > readonly installable: IInstallableMcpServer | undefined;
868 > readonly installState: McpServerInstallState;
869 > readonly runtimeStatus: McpServerEnablementStatus | undefined;
870 > readonly id: string;
871 > readonly name: string;
872 > readonly label: string;
873 > readonly description: string;
874 > readonly icon?: {
875 > readonly dark: string;
876 > readonly light: string;
877 > };
878 > readonly codicon?: string;
879 > readonly publisherUrl?: string;
880 > readonly publisherDisplayName?: string;
881 > readonly starsCount?: number;
882 > readonly license?: string;
883 > readonly repository?: string;
884 > readonly config?: IMcpServerConfiguration | undefined;
885 > readonly readmeUrl?: URI;
886 > getReadme(token: CancellationToken): Promise<string>;
887 > getManifest(token: CancellationToken): Promise<IGalleryMcpServerConfiguration>;
888 > }
889 >
890 > export const IMcpWorkbenchService = createDecorator<IMcpWorkbenchService>('IMcpWorkbenchService');
891 > export interface IMcpWorkbenchService {
892 > readonly _serviceBrand: undefined;
893 > readonly onChange: Event<IWorkbenchMcpServer | undefined>;
894 > readonly onReset: Event<void>;
895 > readonly local: readonly IWorkbenchMcpServer[];
896 > getEnabledLocalMcpServers(): IWorkbenchLocalMcpServer[];
897 > queryLocal(): Promise<IWorkbenchMcpServer[]>;
898 > queryGallery(options?: IQueryOptions, token?: CancellationToken): Promise<IIterativePager<IWorkbenchMcpServer>>;
899 > canInstall(mcpServer: IWorkbenchMcpServer): true | IMarkdownString;
900 > install(server: IWorkbenchMcpServer, installOptions?: IWorkbencMcpServerInstallOptions): Promise<IWorkbenchMcpServer>;
901 > uninstall(mcpServer: IWorkbenchMcpServer): Promise<void>;
902 > getMcpConfigPath(arg: IWorkbenchLocalMcpServer): IMcpConfigPath | undefined;
903 > getMcpConfigPath(arg: URI): Promise<IMcpConfigPath | undefined>;
904 > openSearch(searchValue: string, preserveFocus?: boolean): Promise<void>;
905 > open(extension: IWorkbenchMcpServer | string, options?: IMcpServerEditorOptions): Promise<void>;
906 > }
907 >
908 > export class McpServerContainers extends Disposable {
909 > constructor(
910 private readonly containers: IMcpServerContainer[],
911 @IMcpWorkbenchService mcpWorkbenchService: IMcpWorkbenchService
914 this._register(mcpWorkbenchService.onChange(this.update, this));
915 }
916 > mcpTypes.ts
917 > set mcpServer(extension: IWorkbenchMcpServer | null) {
918 this.containers.forEach(c => c.mcpServer = extension);
919 }
920 > mcpTypes.ts
921 > update(server: IWorkbenchMcpServer | undefined): void {
922 for (const container of this.containers) {
923 if (server && container.mcpServer) {
930 }
931 }
932 > } mcpTypes.ts
933 >
934 > export const McpServersGalleryStatusContext = new RawContextKey<string>('mcpServersGalleryStatus', McpGalleryManifestStatus.Unavailable);
935 > export const HasInstalledMcpServersContext = new RawContextKey<boolean>('hasInstalledMcpServers', true);
936 > export const InstalledMcpServersViewId = 'workbench.views.mcp.installed';
937 >
938 > export namespace McpResourceURI {
939 > export const scheme = 'mcp-resource';
940 >
941 > // Random placeholder for empty authorities, otherwise they're represente as
942 > // `scheme//path/here` in the URI which would get normalized to `scheme/path/here`.
943 > const emptyAuthorityPlaceholder = 'dylo78gyp'; // chosen by a fair dice roll. Guaranteed to be random.
944 >
945 > export function fromServer(def: McpDefinitionReference, resourceURI: URI | string): URI {
946 if (typeof resourceURI === 'string') {
947 resourceURI = URI.parse(resourceURI);
953 });
954 }
955 > mcpTypes.ts
956 > export function toServer(uri: URI | string): { definitionId: string; resourceURL: URL } {
957 if (typeof uri === 'string') {
958 uri = URI.parse(uri);
978 };
979 }
980 > mcpTypes.ts
981 > }
982 >
983 > /** Warning: this enum is cached in `mcpServer.ts` and all changes MUST only be additive. */
984 > export const enum McpCapability {
985 > Logging = 1 << 0,
986 > Completions = 1 << 1,
987 > Prompts = 1 << 2,
988 > PromptsListChanged = 1 << 3,
989 > Resources = 1 << 4,
990 > ResourcesSubscribe = 1 << 5,
991 > ResourcesListChanged = 1 << 6,
992 > Tools = 1 << 7,
993 > ToolsListChanged = 1 << 8,
994 > }
995 >
996 > export interface ISamplingOptions {
997 > server: IMcpServer;
998 > isDuringToolCall: boolean;
999 > params: MCP.CreateMessageRequest['params'];
1000 > }
1001 >
1002 > export interface ISamplingResult {
1003 > sample: MCP.CreateMessageResult;
1004 > }
1005 >
1006 > export interface IMcpSamplingService {
1007 > _serviceBrand: undefined;
1008 >
1009 > sample(opts: ISamplingOptions, token?: CancellationToken): Promise<ISamplingResult>;
1010 >
1011 > /** Whether MCP sampling logs are available for this server */
1012 > hasLogs(server: IMcpServer): boolean;
1013 > /** Gets a text report of the MCP server's sampling usage */
1014 > getLogText(server: IMcpServer): string;
1015 >
1016 > getConfig(server: IMcpServer): IMcpServerSamplingConfiguration;
1017 > updateConfig(server: IMcpServer, mutate: (r: IMcpServerSamplingConfiguration) => unknown): Promise<IMcpServerSamplingConfiguration>;
1018 > }
1019 >
1020 > export const IMcpSamplingService = createDecorator<IMcpSamplingService>('IMcpServerSampling');
1021 >
1022 > export class McpError extends Error {
1023 > public static methodNotFound(method: string) {
1024 > return new McpError(MCP.METHOD_NOT_FOUND, `Method not found: ${method}`);
1025 > }
1026 >
1027 > public static notAllowed() {
1028 return new McpError(-32000, 'The user has denied permission to call this method.');
1029 }
1030 > mcpTypes.ts
1031 > public static unknown(e: Error) {
1032 const mcpError = new McpError(MCP.INTERNAL_ERROR, `Unknown error: ${e.stack}`);
1033 mcpError.cause = e;
1034 return mcpError;
1035 }
1036 > mcpTypes.ts
1037 > constructor(
1038 public readonly code: number,
1039 message: string,
1042 super(message);
1043 }
1044 > } mcpTypes.ts
1045 >
1046 > export const enum McpToolName {
1047 > Prefix = 'mcp_',
1048 > MaxPrefixLen = 18,
1049 > MaxLength = 64,
1050 > }
1051 >
1052 >
1053 > export interface IMcpElicitationService {
1054 > _serviceBrand: undefined;
1055 >
1056 > /**
1057 > * Elicits a response from the user. The `context` is optional and can be used
1058 > * to provide additional information about the request.
1059 > *
1060 > * @param context Context for the elicitation, e.g. chat session ID.
1061 > * @param elicitation Request to elicit a response.
1062 > * @returns A promise that resolves to an {@link ElicitationResult}.
1063 > */
1064 > elicit(server: IMcpServer, context: IMcpToolCallContext | undefined, elicitation: MCP.ElicitRequest['params'], token: CancellationToken): Promise<ElicitResult>;
1065 > }
1066 >
1067 > export const enum ElicitationKind {
1068 > Form,
1069 > URL,
1070 > }
1071 >
1072 > export interface IUrlModeElicitResult extends IDisposable {
1073 > kind: ElicitationKind.URL;
1074 > value: MCP.ElicitResult;
1075 > /**
1076 > * Waits until the server tells us the elicitation is completed before resolving.
1077 > * Rejects with a CancellationError if the server stops before elicitation is
1078 > * complete, or if the token is cancelled.
1079 > */
1080 > wait: Promise<void>;
1081 > }
1082 >
1083 > export interface IFormModeElicitResult extends IDisposable {
1084 > kind: ElicitationKind.Form;
1085 > value: MCP.ElicitResult;
1086 > }
1087 >
1088 > export type ElicitResult = IUrlModeElicitResult | IFormModeElicitResult;
1089 >
1090 > export const IMcpElicitationService = createDecorator<IMcpElicitationService>('IMcpElicitationService');
1091 >
1092 > export const McpToolResourceLinkMimeType = 'application/vnd.code.resource-link';
1093 >
1094 > export interface IMcpToolResourceLinkContents {
1095 > uri: UriComponents;
1096 > underlyingMimeType?: string;
1097 > }
1098 >
1099 > export interface IMcpIcons {
1100 > /** Gets the image URI appropriate to the approximate display size */
1101 > getUrl(size: number): { dark: URI; light?: URI } | undefined;
1102 > }
src/vs/workbench/services/mcp/common/mcpWorkbenchManagementService.ts 203 introduced LOC · 30 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- mcpWorkbenchManagementService.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { DisposableStore, IDisposable } from '../../../../base/common/lifecycle.js';
7 > import { ILocalMcpServer, IMcpManagementService, IGalleryMcpServer, InstallOptions, InstallMcpServerEvent, UninstallMcpServerEvent, DidUninstallMcpServerEvent, InstallMcpServerResult, IInstallableMcpServer, IMcpGalleryService, UninstallOptions, IAllowedMcpServersService, RegistryType } from '../../../../platform/mcp/common/mcpManagement.js';
8 > import { IInstantiationService, refineServiceDecorator } from '../../../../platform/instantiation/common/instantiation.js';
9 > import { IUserDataProfileService } from '../../../services/userDataProfile/common/userDataProfile.js';
10 > import { Emitter, Event } from '../../../../base/common/event.js';
11 > import { IMcpResourceScannerService, McpResourceTarget } from '../../../../platform/mcp/common/mcpResourceScannerService.js';
12 > import { isWorkspaceFolder, IWorkspaceContextService, IWorkspaceFolder, IWorkspaceFoldersChangeEvent } from '../../../../platform/workspace/common/workspace.js';
13 > import { IUriIdentityService } from '../../../../platform/uriIdentity/common/uriIdentity.js';
14 > import { MCP_CONFIGURATION_KEY, WORKSPACE_STANDALONE_CONFIGURATIONS } from '../../configuration/common/configuration.js';
15 > import { ILogService } from '../../../../platform/log/common/log.js';
16 > import { IRemoteAgentService } from '../../remote/common/remoteAgentService.js';
17 > import { URI } from '../../../../base/common/uri.js';
18 > import { ConfigurationTarget } from '../../../../platform/configuration/common/configuration.js';
19 > import { IChannel } from '../../../../base/parts/ipc/common/ipc.js';
20 > import { McpManagementChannelClient } from '../../../../platform/mcp/common/mcpManagementIpc.js';
21 > import { IUserDataProfilesService } from '../../../../platform/userDataProfile/common/userDataProfile.js';
22 > import { IRemoteUserDataProfilesService } from '../../userDataProfile/common/remoteUserDataProfiles.js';
23 > import { AbstractMcpManagementService, AbstractMcpResourceManagementService, ILocalMcpServerInfo } from '../../../../platform/mcp/common/mcpManagementService.js';
24 > import { IFileService } from '../../../../platform/files/common/files.js';
25 > import { ResourceMap } from '../../../../base/common/map.js';
26 > import { IMarkdownString } from '../../../../base/common/htmlContent.js';
27 > import { IMcpServerConfiguration } from '../../../../platform/mcp/common/mcpPlatformTypes.js';
28 >
29 > export const USER_CONFIG_ID = 'usrlocal';
30 > export const REMOTE_USER_CONFIG_ID = 'usrremote';
31 > export const WORKSPACE_CONFIG_ID = 'workspace';
32 > export const WORKSPACE_FOLDER_CONFIG_ID_PREFIX = 'ws';
33 >
34 > export interface IWorkbencMcpServerInstallOptions extends InstallOptions {
35 > target?: ConfigurationTarget | IWorkspaceFolder;
36 > }
37 >
38 > export const enum LocalMcpServerScope {
39 > User = 'user',
40 > RemoteUser = 'remoteUser',
41 > Workspace = 'workspace',
42 > }
43 >
44 > export interface IWorkbenchLocalMcpServer extends ILocalMcpServer {
45 > readonly id: string;
46 > readonly scope: LocalMcpServerScope;
47 > }
48 >
49 > export interface InstallWorkbenchMcpServerEvent extends InstallMcpServerEvent {
50 > readonly scope: LocalMcpServerScope;
51 > }
52 >
53 > export interface IWorkbenchMcpServerInstallResult extends InstallMcpServerResult {
54 > readonly local?: IWorkbenchLocalMcpServer;
55 > }
56 >
57 > export interface UninstallWorkbenchMcpServerEvent extends UninstallMcpServerEvent {
58 > readonly scope: LocalMcpServerScope;
59 > }
60 >
61 > export interface DidUninstallWorkbenchMcpServerEvent extends DidUninstallMcpServerEvent {
62 > readonly scope: LocalMcpServerScope;
63 > }
64 >
65 > export const IWorkbenchMcpManagementService = refineServiceDecorator<IMcpManagementService, IWorkbenchMcpManagementService>(IMcpManagementService);
66 > export interface IWorkbenchMcpManagementService extends IMcpManagementService {
67 > readonly _serviceBrand: undefined;
68 >
69 > readonly onInstallMcpServerInCurrentProfile: Event<InstallWorkbenchMcpServerEvent>;
70 > readonly onDidInstallMcpServersInCurrentProfile: Event<readonly IWorkbenchMcpServerInstallResult[]>;
71 > readonly onDidUpdateMcpServersInCurrentProfile: Event<readonly IWorkbenchMcpServerInstallResult[]>;
72 > readonly onUninstallMcpServerInCurrentProfile: Event<UninstallWorkbenchMcpServerEvent>;
73 > readonly onDidUninstallMcpServerInCurrentProfile: Event<DidUninstallWorkbenchMcpServerEvent>;
74 > readonly onDidChangeProfile: Event<void>;
75 >
76 > getInstalled(): Promise<IWorkbenchLocalMcpServer[]>;
77 > install(server: IInstallableMcpServer | URI, options?: IWorkbencMcpServerInstallOptions): Promise<IWorkbenchLocalMcpServer>;
78 > installFromGallery(server: IGalleryMcpServer, options?: InstallOptions): Promise<IWorkbenchLocalMcpServer>;
79 > updateMetadata(local: ILocalMcpServer, server: IGalleryMcpServer, profileLocation?: URI): Promise<IWorkbenchLocalMcpServer>;
80 > }
81 >
82 > export class WorkbenchMcpManagementService extends AbstractMcpManagementService implements IWorkbenchMcpManagementService {
83 >
84 > private _onInstallMcpServer = this._register(new Emitter<InstallMcpServerEvent>());
85 > readonly onInstallMcpServer = this._onInstallMcpServer.event;
86 >
87 > private _onDidInstallMcpServers = this._register(new Emitter<readonly InstallMcpServerResult[]>());
88 > readonly onDidInstallMcpServers = this._onDidInstallMcpServers.event;
89 >
90 > private _onDidUpdateMcpServers = this._register(new Emitter<readonly InstallMcpServerResult[]>());
91 > readonly onDidUpdateMcpServers = this._onDidUpdateMcpServers.event;
92 >
93 > private _onUninstallMcpServer = this._register(new Emitter<UninstallMcpServerEvent>());
94 > readonly onUninstallMcpServer = this._onUninstallMcpServer.event;
95 >
96 > private _onDidUninstallMcpServer = this._register(new Emitter<DidUninstallMcpServerEvent>());
97 > readonly onDidUninstallMcpServer = this._onDidUninstallMcpServer.event;
98 >
99 > private readonly _onInstallMcpServerInCurrentProfile = this._register(new Emitter<InstallWorkbenchMcpServerEvent>());
100 > readonly onInstallMcpServerInCurrentProfile = this._onInstallMcpServerInCurrentProfile.event;
101 >
102 > private readonly _onDidInstallMcpServersInCurrentProfile = this._register(new Emitter<readonly IWorkbenchMcpServerInstallResult[]>());
103 > readonly onDidInstallMcpServersInCurrentProfile = this._onDidInstallMcpServersInCurrentProfile.event;
104 >
105 > private readonly _onDidUpdateMcpServersInCurrentProfile = this._register(new Emitter<readonly IWorkbenchMcpServerInstallResult[]>());
106 > readonly onDidUpdateMcpServersInCurrentProfile = this._onDidUpdateMcpServersInCurrentProfile.event;
107 >
108 > private readonly _onUninstallMcpServerInCurrentProfile = this._register(new Emitter<UninstallWorkbenchMcpServerEvent>());
109 > readonly onUninstallMcpServerInCurrentProfile = this._onUninstallMcpServerInCurrentProfile.event;
110 >
111 > private readonly _onDidUninstallMcpServerInCurrentProfile = this._register(new Emitter<DidUninstallWorkbenchMcpServerEvent>());
112 > readonly onDidUninstallMcpServerInCurrentProfile = this._onDidUninstallMcpServerInCurrentProfile.event;
113 >
114 > private readonly _onDidChangeProfile = this._register(new Emitter<void>());
115 > readonly onDidChangeProfile = this._onDidChangeProfile.event;
116 >
117 > private readonly workspaceMcpManagementService: IMcpManagementService;
118 > private readonly remoteMcpManagementService: IMcpManagementService | undefined;
119 >
120 > constructor(
121 private readonly mcpManagementService: IMcpManagementService,
122 @IAllowedMcpServersService allowedMcpServersService: IAllowedMcpServersService,
237 }));
238 }
240 > private createInstallMcpServerResultsFromEvent(e: readonly InstallMcpServerResult[], scope: LocalMcpServerScope): { mcpServerInstallResult: IWorkbenchMcpServerInstallResult[]; mcpServerInstallResultInCurrentProfile: IWorkbenchMcpServerInstallResult[] } {
241 const mcpServerInstallResult: IWorkbenchMcpServerInstallResult[] = [];
242 const mcpServerInstallResultInCurrentProfile: IWorkbenchMcpServerInstallResult[] = [];
254 return { mcpServerInstallResult, mcpServerInstallResultInCurrentProfile };
255 }
257 > private async handleRemoteInstallMcpServerResultsFromEvent(e: readonly InstallMcpServerResult[], emitter: Emitter<readonly InstallMcpServerResult[]>, currentProfileEmitter: Emitter<readonly IWorkbenchMcpServerInstallResult[]>): Promise<void> {
258 const mcpServerInstallResult: IWorkbenchMcpServerInstallResult[] = [];
259 const mcpServerInstallResultInCurrentProfile: IWorkbenchMcpServerInstallResult[] = [];
275 }
276 }
278 > async getInstalled(): Promise<IWorkbenchLocalMcpServer[]> {
279 const installed: IWorkbenchLocalMcpServer[] = [];
280 const [userServers, remoteServers, workspaceServers] = await Promise.all([
296 return installed;
297 }
299 > private toWorkspaceMcpServer(server: ILocalMcpServer, scope: LocalMcpServerScope): IWorkbenchLocalMcpServer {
300 return { ...server, id: `mcp.config.${this.getConfigId(server, scope)}.${server.name}`, scope };
301 }
303 > private getConfigId(server: ILocalMcpServer, scope: LocalMcpServerScope): string {
304 if (scope === LocalMcpServerScope.User) {
305 return USER_CONFIG_ID;
326 return 'unknown';
327 }
329 > async install(server: IInstallableMcpServer, options?: IWorkbencMcpServerInstallOptions): Promise<IWorkbenchLocalMcpServer> {
330 options = options ?? {};
331
357 return this.toWorkspaceMcpServer(result, LocalMcpServerScope.User);
358 }
360 > async installFromGallery(server: IGalleryMcpServer, options?: IWorkbencMcpServerInstallOptions): Promise<IWorkbenchLocalMcpServer> {
361 options = options ?? {};
362
390 return this.toWorkspaceMcpServer(result, LocalMcpServerScope.User);
391 }
393 > async updateMetadata(local: IWorkbenchLocalMcpServer, server: IGalleryMcpServer, profileLocation: URI): Promise<IWorkbenchLocalMcpServer> {
394 if (local.scope === LocalMcpServerScope.Workspace) {
395 const result = await this.workspaceMcpManagementService.updateMetadata(local, server, profileLocation);
408 return this.toWorkspaceMcpServer(result, LocalMcpServerScope.User);
409 }
411 > async uninstall(server: IWorkbenchLocalMcpServer): Promise<void> {
412 if (server.scope === LocalMcpServerScope.Workspace) {
413 return this.workspaceMcpManagementService.uninstall(server);
423 return this.mcpManagementService.uninstall(server, { mcpResource: this.userDataProfileService.currentProfile.mcpResource });
424 }
426 > private async getRemoteMcpResource(mcpResource?: URI): Promise<URI | undefined> {
427 if (!mcpResource && this.userDataProfileService.currentProfile.isDefault) {
428 return undefined;
437 return profile?.mcpResource;
438 }
440 >
441 > class WorkspaceMcpResourceManagementService extends AbstractMcpResourceManagementService {
442 >
443 > constructor(
444 mcpResource: URI,
445 target: McpResourceTarget,
453 super(mcpResource, target, mcpGalleryService, fileService, uriIdentityService, logService, mcpResourceScannerService, allowedMcpServersService);
454 }
456 > override async installFromGallery(server: IGalleryMcpServer, options?: InstallOptions): Promise<ILocalMcpServer> {
457 this.logService.trace('MCP Management Service: installGallery', server.name, server.galleryUrl);
458
493 }
494 }
496 > override updateMetadata(): Promise<ILocalMcpServer> {
497 throw new Error('Not supported');
498 }
500 > protected override installFromUri(): Promise<ILocalMcpServer> {
501 throw new Error('Not supported');
502 }
504 > protected override async getLocalServerInfo(name: string, mcpServerConfig: IMcpServerConfiguration): Promise<ILocalMcpServerInfo | undefined> {
505 if (!mcpServerConfig.gallery) {
506 return undefined;
525 };
526 }
528 > override canInstall(server: IGalleryMcpServer | IInstallableMcpServer): true | IMarkdownString {
529 throw new Error('Not supported');
530 }
532 >
533 > class WorkspaceMcpManagementService extends AbstractMcpManagementService implements IMcpManagementService {
534 >
535 > private readonly _onInstallMcpServer = this._register(new Emitter<InstallMcpServerEvent>());
536 > readonly onInstallMcpServer = this._onInstallMcpServer.event;
537 >
538 > private readonly _onDidInstallMcpServers = this._register(new Emitter<readonly InstallMcpServerResult[]>());
539 > readonly onDidInstallMcpServers = this._onDidInstallMcpServers.event;
540 >
541 > private readonly _onDidUpdateMcpServers = this._register(new Emitter<readonly InstallMcpServerResult[]>());
542 > readonly onDidUpdateMcpServers = this._onDidUpdateMcpServers.event;
543 >
544 > private readonly _onUninstallMcpServer = this._register(new Emitter<UninstallMcpServerEvent>());
545 > readonly onUninstallMcpServer = this._onUninstallMcpServer.event;
546 >
547 > private readonly _onDidUninstallMcpServer = this._register(new Emitter<DidUninstallMcpServerEvent>());
548 > readonly onDidUninstallMcpServer = this._onDidUninstallMcpServer.event;
549 >
550 > private allMcpServers: ILocalMcpServer[] = [];
551 >
552 > private workspaceConfiguration?: URI | null;
553 > private readonly workspaceMcpManagementServices = new ResourceMap<{ service: WorkspaceMcpResourceManagementService } & IDisposable>();
554 >
555 > constructor(
556 @IAllowedMcpServersService allowedMcpServersService: IAllowedMcpServersService,
557 @IUriIdentityService private readonly uriIdentityService: IUriIdentityService,
563 this.initialize();
564 }
566 > private async initialize(): Promise<void> {
567 try {
568 await this.onDidChangeWorkbenchState();
574 }
575 }
577 > private async onDidChangeWorkbenchState(): Promise<void> {
578 if (this.workspaceConfiguration) {
579 await this.removeWorkspaceService(this.workspaceConfiguration);
584 }
585 }
587 > private async onDidChangeWorkspaceFolders(e: IWorkspaceFoldersChangeEvent): Promise<void> {
588 try {
589 await Promise.allSettled(e.removed.map(folder => this.removeWorkspaceService(folder.toResource(WORKSPACE_STANDALONE_CONFIGURATIONS[MCP_CONFIGURATION_KEY]))));
597 }
598 }
600 > private async addWorkspaceService(mcpResource: URI, target: McpResourceTarget): Promise<void> {
601 if (this.workspaceMcpManagementServices.has(mcpResource)) {
602 return;
651 this.workspaceMcpManagementServices.set(mcpResource, { service, dispose: () => disposables.dispose() });
652 }
654 > private async removeWorkspaceService(mcpResource: URI): Promise<void> {
655 const serviceItem = this.workspaceMcpManagementServices.get(mcpResource);
656 if (serviceItem) {
671 }
672 }
674 > async getInstalled(): Promise<ILocalMcpServer[]> {
675 return this.allMcpServers;
676 }
678 > async install(server: IInstallableMcpServer, options?: InstallOptions): Promise<ILocalMcpServer> {
679 if (!options?.mcpResource) {
680 throw new Error('MCP resource is required');
688 return mcpManagementServiceItem.service.install(server, options);
689 }
691 > async uninstall(server: ILocalMcpServer, options?: UninstallOptions): Promise<void> {
692 const mcpResource = server.mcpResource;
693
699 return mcpManagementServiceItem.service.uninstall(server, options);
700 }
702 > installFromGallery(gallery: IGalleryMcpServer, options?: InstallOptions): Promise<ILocalMcpServer> {
703 if (!options?.mcpResource) {
704 throw new Error('MCP resource is required');
712 return mcpManagementServiceItem.service.installFromGallery(gallery, options);
713 }
715 > updateMetadata(): Promise<ILocalMcpServer> {
716 throw new Error('Not supported');
717 }
719 > override dispose(): void {
720 this.workspaceMcpManagementServices.forEach(service => service.dispose());
721 this.workspaceMcpManagementServices.clear();
722 super.dispose();
723 }
src/vs/platform/mcp/common/mcpManagementIpc.ts 67 introduced LOC · 15 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- mcpManagementIpc.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Emitter, Event } from '../../../base/common/event.js';
7 > import { cloneAndChange } from '../../../base/common/objects.js';
8 > import { URI, UriComponents } from '../../../base/common/uri.js';
9 > import { DefaultURITransformer, IURITransformer, transformAndReviveIncomingURIs } from '../../../base/common/uriIpc.js';
10 > import { IChannel, IServerChannel } from '../../../base/parts/ipc/common/ipc.js';
11 > import { ILogService } from '../../log/common/log.js';
12 > import { RemoteAgentConnectionContext } from '../../remote/common/remoteAgentEnvironment.js';
13 > import { DidUninstallMcpServerEvent, IGalleryMcpServer, ILocalMcpServer, IMcpManagementService, IInstallableMcpServer, InstallMcpServerEvent, InstallMcpServerResult, InstallOptions, UninstallMcpServerEvent, UninstallOptions, IAllowedMcpServersService } from './mcpManagement.js';
14 > import { AbstractMcpManagementService } from './mcpManagementService.js';
15 >
16 > function transformIncomingURI(uri: UriComponents, transformer: IURITransformer | null): URI;
17 > function transformIncomingURI(uri: UriComponents | undefined, transformer: IURITransformer | null): URI | undefined;
18 function transformIncomingURI(uri: UriComponents | undefined, transformer: IURITransformer | null): URI | undefined {
19 return uri ? URI.revive(transformer ? transformer.transformIncoming(uri) : uri) : undefined;
20 }
22 function transformIncomingServer(mcpServer: ILocalMcpServer, transformer: IURITransformer | null): ILocalMcpServer {
23 transformer = transformer ? transformer : DefaultURITransformer;
26 return { ...transformed, ...{ manifest } };
27 }
29 function transformIncomingOptions<O extends { mcpResource?: UriComponents }>(options: O | undefined, transformer: IURITransformer | null): O | undefined {
30 return options?.mcpResource ? transformAndReviveIncomingURIs(options, transformer ?? DefaultURITransformer) : options;
31 }
33 function transformOutgoingExtension(extension: ILocalMcpServer, transformer: IURITransformer | null): ILocalMcpServer {
34 return transformer ? cloneAndChange(extension, value => value instanceof URI ? transformer.transformOutgoingURI(value) : undefined) : extension;
35 }
37 function transformOutgoingURI(uri: URI, transformer: IURITransformer | null): URI {
38 return transformer ? transformer.transformOutgoingURI(uri) : uri;
39 }
41 > export class McpManagementChannel<TContext = RemoteAgentConnectionContext | string> implements IServerChannel<TContext> {
42 > readonly onInstallMcpServer: Event<InstallMcpServerEvent>;
43 > readonly onDidInstallMcpServers: Event<readonly InstallMcpServerResult[]>;
44 > readonly onDidUpdateMcpServers: Event<readonly InstallMcpServerResult[]>;
45 > readonly onUninstallMcpServer: Event<UninstallMcpServerEvent>;
46 > readonly onDidUninstallMcpServer: Event<DidUninstallMcpServerEvent>;
47 >
48 > constructor(private service: IMcpManagementService, private getUriTransformer: (requestContext: TContext) => IURITransformer | null) {
49 this.onInstallMcpServer = Event.buffer(service.onInstallMcpServer, 'onInstallMcpServer', true);
50 this.onDidInstallMcpServers = Event.buffer(service.onDidInstallMcpServers, 'onDidInstallMcpServers', true);
53 this.onDidUninstallMcpServer = Event.buffer(service.onDidUninstallMcpServer, 'onDidUninstallMcpServer', true);
54 }
56 > listen<T>(context: TContext, event: string): Event<T> {
57 const uriTransformer = this.getUriTransformer(context);
58 switch (event) {
92 throw new Error('Invalid listen');
93 }
95 > async call<T>(context: TContext, command: string, args?: unknown): Promise<T> {
96 const uriTransformer: IURITransformer | null = this.getUriTransformer(context);
97 const argsArray = Array.isArray(args) ? args : [];
117 throw new Error('Invalid call');
118 }
120 >
121 > export class McpManagementChannelClient extends AbstractMcpManagementService implements IMcpManagementService {
122 >
123 > declare readonly _serviceBrand: undefined;
124 >
125 > private readonly _onInstallMcpServer = this._register(new Emitter<InstallMcpServerEvent>());
126 > get onInstallMcpServer() { return this._onInstallMcpServer.event; }
127 >
128 > private readonly _onDidInstallMcpServers = this._register(new Emitter<readonly InstallMcpServerResult[]>());
129 > get onDidInstallMcpServers() { return this._onDidInstallMcpServers.event; }
130 >
131 > private readonly _onUninstallMcpServer = this._register(new Emitter<UninstallMcpServerEvent>());
132 > get onUninstallMcpServer() { return this._onUninstallMcpServer.event; }
133 >
134 > private readonly _onDidUninstallMcpServer = this._register(new Emitter<DidUninstallMcpServerEvent>());
135 > get onDidUninstallMcpServer() { return this._onDidUninstallMcpServer.event; }
136 >
137 > private readonly _onDidUpdateMcpServers = this._register(new Emitter<InstallMcpServerResult[]>());
138 > get onDidUpdateMcpServers() { return this._onDidUpdateMcpServers.event; }
139 >
140 > constructor(
141 private readonly channel: IChannel,
142 @IAllowedMcpServersService allowedMcpServersService: IAllowedMcpServersService,
150 this._register(this.channel.listen<DidUninstallMcpServerEvent>('onDidUninstallMcpServer')(e => this._onDidUninstallMcpServer.fire(({ ...e, mcpResource: transformIncomingURI(e.mcpResource, null) }))));
151 }
153 > install(server: IInstallableMcpServer, options?: InstallOptions): Promise<ILocalMcpServer> {
154 return Promise.resolve(this.channel.call<ILocalMcpServer>('install', [server, options])).then(local => transformIncomingServer(local, null));
155 }
157 > installFromGallery(extension: IGalleryMcpServer, installOptions?: InstallOptions): Promise<ILocalMcpServer> {
158 return Promise.resolve(this.channel.call<ILocalMcpServer>('installFromGallery', [extension, installOptions])).then(local => transformIncomingServer(local, null));
159 }
161 > uninstall(extension: ILocalMcpServer, options?: UninstallOptions): Promise<void> {
162 return Promise.resolve(this.channel.call<void>('uninstall', [extension, options]));
163 }
165 > getInstalled(mcpResource?: URI): Promise<ILocalMcpServer[]> {
166 return Promise.resolve(this.channel.call<ILocalMcpServer[]>('getInstalled', [mcpResource]))
167 .then(servers => servers.map(server => transformIncomingServer(server, null)));
168 }
170 > updateMetadata(local: ILocalMcpServer, gallery: IGalleryMcpServer, mcpResource?: URI): Promise<ILocalMcpServer> {
171 return Promise.resolve(this.channel.call<ILocalMcpServer>('updateMetadata', [local, gallery, mcpResource])).then(local => transformIncomingServer(local, null));
172 }
src/vs/workbench/services/userDataProfile/common/remoteUserDataProfiles.ts 59 introduced LOC · 11 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- remoteUserDataProfiles.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Disposable } from '../../../../base/common/lifecycle.js';
7 > import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js';
8 > import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js';
9 > import { DidChangeProfilesEvent, IUserDataProfile, IUserDataProfilesService } from '../../../../platform/userDataProfile/common/userDataProfile.js';
10 > import { IRemoteAgentService } from '../../remote/common/remoteAgentService.js';
11 > import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js';
12 > import { IStringDictionary } from '../../../../base/common/collections.js';
13 > import { ILogService } from '../../../../platform/log/common/log.js';
14 > import { IUserDataProfileService } from './userDataProfile.js';
15 > import { distinct } from '../../../../base/common/arrays.js';
16 > import { IWorkbenchEnvironmentService } from '../../environment/common/environmentService.js';
17 > import { UserDataProfilesService } from '../../../../platform/userDataProfile/common/userDataProfileIpc.js';
18 > import { ErrorNoTelemetry } from '../../../../base/common/errors.js';
19 >
20 > const associatedRemoteProfilesKey = 'associatedRemoteProfiles';
21 >
22 > export const IRemoteUserDataProfilesService = createDecorator<IRemoteUserDataProfilesService>('IRemoteUserDataProfilesService');
23 > export interface IRemoteUserDataProfilesService {
24 > readonly _serviceBrand: undefined;
25 > getRemoteProfiles(): Promise<readonly IUserDataProfile[]>;
26 > getRemoteProfile(localProfile: IUserDataProfile): Promise<IUserDataProfile>;
27 > }
28 >
29 > class RemoteUserDataProfilesService extends Disposable implements IRemoteUserDataProfilesService {
30 >
31 > readonly _serviceBrand: undefined;
32 >
33 > private readonly initPromise: Promise<void>;
34 >
35 > private remoteUserDataProfilesService: IUserDataProfilesService | undefined;
36 >
37 > constructor(
38 @IWorkbenchEnvironmentService private readonly environmentService: IWorkbenchEnvironmentService,
39 @IRemoteAgentService private readonly remoteAgentService: IRemoteAgentService,
46 this.initPromise = this.init();
47 }
49 > private async init(): Promise<void> {
50 const connection = this.remoteAgentService.getConnection();
51 if (!connection) {
69 this.cleanUp();
70 }
72 > private async onDidChangeLocalProfiles(e: DidChangeProfilesEvent): Promise<void> {
73 for (const profile of e.removed) {
74 const remoteProfile = this.remoteUserDataProfilesService?.profiles.find(p => p.id === profile.id);
78 }
79 }
81 > async getRemoteProfiles(): Promise<readonly IUserDataProfile[]> {
82 await this.initPromise;
83
88 return this.remoteUserDataProfilesService.profiles;
89 }
91 > async getRemoteProfile(localProfile: IUserDataProfile): Promise<IUserDataProfile> {
92 await this.initPromise;
93
98 return this.getAssociatedRemoteProfile(localProfile, this.remoteUserDataProfilesService);
99 }
101 > private async getAssociatedRemoteProfile(localProfile: IUserDataProfile, remoteUserDataProfilesService: IUserDataProfilesService): Promise<IUserDataProfile> {
102 // If the local profile is the default profile, return the remote default profile
103 if (localProfile.isDefault) {
115 return profile;
116 }
118 > private getAssociatedRemoteProfiles(): string[] {
119 if (this.environmentService.remoteAuthority) {
120 const remotes = this.parseAssociatedRemoteProfiles();
123 return [];
124 }
126 > private setAssociatedRemoteProfiles(profiles: string[]): void {
127 if (this.environmentService.remoteAuthority) {
128 const remotes = this.parseAssociatedRemoteProfiles();
140 }
141 }
143 > private parseAssociatedRemoteProfiles(): IStringDictionary<string[]> {
144 if (this.environmentService.remoteAuthority) {
145 const value = this.storageService.get(associatedRemoteProfilesKey, StorageScope.APPLICATION);
152 return {};
153 }
155 > private async cleanUp(): Promise<void> {
156 const associatedRemoteProfiles: string[] = [];
157 for (const profileId of this.getAssociatedRemoteProfiles()) {
175 this.setAssociatedRemoteProfiles(associatedRemoteProfiles);
176 }
178 > }
179 >
180 > registerSingleton(IRemoteUserDataProfilesService, RemoteUserDataProfilesService, InstantiationType.Delayed);
src/vs/platform/userDataProfile/common/userDataProfileIpc.ts 55 introduced LOC · 14 ranges

Open complete file

1 > /*--------------------------------------------------------------------------------------------- userDataProfileIpc.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Emitter, Event } from '../../../base/common/event.js';
7 > import { IChannel, IServerChannel } from '../../../base/parts/ipc/common/ipc.js';
8 > import { URI, UriDto } from '../../../base/common/uri.js';
9 > import { DidChangeProfilesEvent, IUserDataProfile, IUserDataProfileOptions, IUserDataProfilesService, IUserDataProfileUpdateOptions, reviveProfile } from './userDataProfile.js';
10 > import { IAnyWorkspaceIdentifier } from '../../workspace/common/workspace.js';
11 > import { IURITransformer, transformIncomingURIs, transformOutgoingURIs } from '../../../base/common/uriIpc.js';
12 > import { Disposable } from '../../../base/common/lifecycle.js';
13 >
14 > export class RemoteUserDataProfilesServiceChannel implements IServerChannel {
15 >
16 > constructor(
17 private readonly service: IUserDataProfilesService,
18 private readonly getUriTransformer: (requestContext: any) => IURITransformer
19 ) { }
21 > listen(context: any, event: string): Event<any> {
22 const uriTransformer = this.getUriTransformer(context);
23 switch (event) {
33 throw new Error(`Invalid listen ${event}`);
34 }
36 > async call(context: any, command: string, args?: any): Promise<any> {
37 const uriTransformer = this.getUriTransformer(context);
38 switch (command) {
53 throw new Error(`Invalid call ${command}`);
54 }
56 >
57 > export class UserDataProfilesService extends Disposable implements IUserDataProfilesService {
58 >
59 > readonly _serviceBrand: undefined;
60 >
61 > get defaultProfile(): IUserDataProfile { return this.profiles[0]; }
62 > private _profiles: IUserDataProfile[] = [];
63 > get profiles(): IUserDataProfile[] { return this._profiles; }
64 >
65 > private readonly _onDidChangeProfiles = this._register(new Emitter<DidChangeProfilesEvent>());
66 > readonly onDidChangeProfiles = this._onDidChangeProfiles.event;
67 >
68 > readonly onDidResetWorkspaces: Event<void>;
69 >
70 > constructor(
71 profiles: readonly UriDto<IUserDataProfile>[],
72 readonly profilesHome: URI,
84 this.onDidResetWorkspaces = this.channel.listen<void>('onDidResetWorkspaces');
85 }
87 > async createNamedProfile(name: string, options?: IUserDataProfileOptions, workspaceIdentifier?: IAnyWorkspaceIdentifier): Promise<IUserDataProfile> {
88 const result = await this.channel.call<UriDto<IUserDataProfile>>('createNamedProfile', [name, options, workspaceIdentifier]);
89 return reviveProfile(result, this.profilesHome.scheme);
90 }
92 > async createProfile(id: string, name: string, options?: IUserDataProfileOptions, workspaceIdentifier?: IAnyWorkspaceIdentifier): Promise<IUserDataProfile> {
93 const result = await this.channel.call<UriDto<IUserDataProfile>>('createProfile', [id, name, options, workspaceIdentifier]);
94 return reviveProfile(result, this.profilesHome.scheme);
95 }
97 > async createTransientProfile(workspaceIdentifier?: IAnyWorkspaceIdentifier): Promise<IUserDataProfile> {
98 const result = await this.channel.call<UriDto<IUserDataProfile>>('createTransientProfile', [workspaceIdentifier]);
99 return reviveProfile(result, this.profilesHome.scheme);
100 }
102 > async setProfileForWorkspace(workspaceIdentifier: IAnyWorkspaceIdentifier, profile: IUserDataProfile): Promise<void> {
103 await this.channel.call<UriDto<IUserDataProfile>>('setProfileForWorkspace', [workspaceIdentifier, profile]);
104 }
106 > removeProfile(profile: IUserDataProfile): Promise<void> {
107 return this.channel.call('removeProfile', [profile]);
108 }
110 > async updateProfile(profile: IUserDataProfile, updateOptions: IUserDataProfileUpdateOptions): Promise<IUserDataProfile> {
111 const result = await this.channel.call<UriDto<IUserDataProfile>>('updateProfile', [profile, updateOptions]);
112 return reviveProfile(result, this.profilesHome.scheme);
113 }
115 > resetWorkspaces(): Promise<void> {
116 return this.channel.call('resetWorkspaces');
117 }
119 > cleanUp(): Promise<void> {
120 return this.channel.call('cleanUp');
121 }
123 > cleanUpTransientProfiles(): Promise<void> {
124 return this.channel.call('cleanUpTransientProfiles');
125 }
src/vs/platform/mcp/common/mcpGalleryManifest.ts 50 introduced LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- mcpGalleryManifest.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import { Event } from '../../../base/common/event.js';
7 > import { createDecorator } from '../../instantiation/common/instantiation.js';
8 >
9 > export const enum McpGalleryResourceType {
10 > McpServersQueryService = 'McpServersQueryService',
11 > McpServerWebUri = 'McpServerWebUriTemplate',
12 > McpServerVersionUri = 'McpServerVersionUriTemplate',
13 > McpServerIdUri = 'McpServerIdUriTemplate',
14 > McpServerLatestVersionUri = 'McpServerLatestVersionUriTemplate',
15 > McpServerNamedResourceUri = 'McpServerNamedResourceUriTemplate',
16 > PublisherUriTemplate = 'PublisherUriTemplate',
17 > ContactSupportUri = 'ContactSupportUri',
18 > PrivacyPolicyUri = 'PrivacyPolicyUri',
19 > TermsOfServiceUri = 'TermsOfServiceUri',
20 > ReportUri = 'ReportUri',
21 > }
22 >
23 > export type McpGalleryManifestResource = {
24 > readonly id: string;
25 > readonly type: string;
26 > };
27 >
28 > export interface IMcpGalleryManifest {
29 > readonly version: string;
30 > readonly url: string;
31 > readonly resources: readonly McpGalleryManifestResource[];
32 > }
33 >
34 > export const enum McpGalleryManifestStatus {
35 > Available = 'available',
36 > Unavailable = 'unavailable'
37 > }
38 >
39 > export const IMcpGalleryManifestService = createDecorator<IMcpGalleryManifestService>('IMcpGalleryManifestService');
40 >
41 > export interface IMcpGalleryManifestService {
42 > readonly _serviceBrand: undefined;
43 >
44 > readonly mcpGalleryManifestStatus: McpGalleryManifestStatus;
45 > readonly onDidChangeMcpGalleryManifestStatus: Event<McpGalleryManifestStatus>;
46 > readonly onDidChangeMcpGalleryManifest: Event<IMcpGalleryManifest | null>;
47 > getMcpGalleryManifest(): Promise<IMcpGalleryManifest | null>;
48 > }
49 >
50 > export function getMcpGalleryManifestResourceUri(manifest: IMcpGalleryManifest, type: string): string | undefined {
51 const [name, version] = type.split('/');
52 for (const resource of manifest.resources) {
src/vs/workbench/contrib/mcp/common/modelContextProtocol.ts 6 introduced LOC · 1 range

Open complete file

1 > /*--------------------------------------------------------------------------------------------- modelContextProtocol.ts
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > export { MCP } from '../../../../platform/mcp/common/modelContextProtocol.js';