### Install Project Dependencies Source: https://ts.sdk.modelcontextprotocol.io/index.html Installs all project dependencies from the SDK repository root using npm. This is a prerequisite for running examples. ```bash npm install Copy ``` -------------------------------- ### Run Streamable HTTP Client Example Source: https://ts.sdk.modelcontextprotocol.io/index.html Launches the interactive Streamable HTTP client example in a separate terminal using tsx. This client connects to the running MCP server. ```bash npx tsx src/examples/client/simpleStreamableHttp.ts Copy ``` -------------------------------- ### Transport start() Method Source: https://ts.sdk.modelcontextprotocol.io/interfaces/shared_transport.Transport.html Initiates message processing and any necessary connection setup. Ensure callbacks are set before calling this method to prevent message loss. ```typescript start(): Promise ``` -------------------------------- ### Run Streamable HTTP Server Example Source: https://ts.sdk.modelcontextprotocol.io/index.html Executes the simple Streamable HTTP server example using tsx. This server demonstrates tools, resources, prompts, sampling, elicitation, tasks, and logging. ```bash npx tsx src/examples/server/simpleStreamableHttp.ts Copy ``` -------------------------------- ### connect Source: https://ts.sdk.modelcontextprotocol.io/classes/shared_protocol.Protocol.html Attaches to the given transport, starts it, and starts listening for messages. ```APIDOC ## connect ### Description Attaches to the given transport, starts it, and starts listening for messages. ### Method POST ### Endpoint /connect ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **transport** (Transport) - Required - The transport to attach to. ### Request Example ```json { "transport": { /* Transport object details */ } } ``` ### Response #### Success Response (200) - None #### Response Example ```json {} ``` ``` -------------------------------- ### ServerOptions Usage Example Source: https://ts.sdk.modelcontextprotocol.io/types/server.ServerOptions.html Illustrates how to instantiate a Server with different JSON schema validators. ```APIDOC #### Example ```typescript // ajv (default) const server = new Server( { name: 'my-server', version: '1.0.0' }, { capabilities: {} jsonSchemaValidator: new AjvJsonSchemaValidator() } ); // @cfworker/json-schema const server = new Server( { name: 'my-server', version: '1.0.0' }, { capabilities: {}, jsonSchemaValidator: new CfWorkerJsonSchemaValidator() } ); ``` ``` -------------------------------- ### start Source: https://ts.sdk.modelcontextprotocol.io/classes/inMemory.InMemoryTransport.html Starts message processing on the transport. ```APIDOC ## start ### Description Starts processing messages on the transport, including any connection steps that might need to be taken. This method should only be called after callbacks are installed, or else messages may be lost. NOTE: This method should not be called explicitly when using Client, Server, or Protocol classes, as they will implicitly call start(). ### Method start(): Promise ### Returns - Promise: A promise that resolves when the transport has started processing messages. ``` -------------------------------- ### Install MCP TypeScript SDK Source: https://ts.sdk.modelcontextprotocol.io/index.html Installs the MCP TypeScript SDK and its peer dependency Zod using npm. Ensure you have Node.js and npm installed. ```bash npm install @modelcontextprotocol/sdk zod Copy ``` -------------------------------- ### connect Source: https://ts.sdk.modelcontextprotocol.io/classes/server.Server.html Attaches to the given transport, starts it, and starts listening for messages. The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. ```APIDOC ## connect ### Description Attaches to the given transport, starts it, and starts listening for messages. The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. ### Method * connect(transport: Transport): Promise ### Parameters #### Path Parameters * **transport** (Transport) - Required - The transport to connect to. ### Returns Promise ``` -------------------------------- ### connect Source: https://ts.sdk.modelcontextprotocol.io/classes/client.Client.html Attaches to the given transport, starts it, and begins listening for messages. The Protocol object assumes ownership of the Transport. ```APIDOC ## connect ### Description Attaches to the given transport, starts it, and starts listening for messages. The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. ### Method connect(transport: Transport, options?: RequestOptions): Promise ### Parameters #### Path Parameters * transport: Transport * `Optional`options: RequestOptions #### Returns Promise ``` -------------------------------- ### Client Constructor Source: https://ts.sdk.modelcontextprotocol.io/classes/client.Client.html Initializes a new MCP client instance. The client automatically starts the initialization flow when the connect() method is called. It can be used with custom request, notification, and result types by extending the base types and passing them as type parameters. ```APIDOC ## constructor ### Description Initializes this client with the given name and version information. ### Parameters * `_clientInfo` (object) - Required - Information about the client, including its name and version. * `name` (string) - Required - The name of the client. * `version` (string) - Required - The version of the client. * `description` (string) - Optional - A description of the client. * `icons` (array) - Optional - An array of icons for the client. * `title` (string) - Optional - The title of the client. * `websiteUrl` (string) - Optional - The website URL of the client. * `options` (ClientOptions) - Optional - Additional options for the client. ### Returns * `Client` - An instance of the Client class. ``` -------------------------------- ### Register a Minimal Prompt Source: https://ts.sdk.modelcontextprotocol.io/documents/server.html Register a reusable prompt template on the server for consistent model interactions. This minimal example defines a prompt for code review. ```typescript server.registerPrompt( 'review-code', { title: 'Code Review', description: 'Review code for best practices and potential issues', argsSchema: { code: z.string() } }, ({ code }) => ({ messages: [ { role: 'user', content: { type: 'text', text: `Please review this code:\n\n${code}` } } ] }) ); ``` -------------------------------- ### Capture Stack Trace Example Source: https://ts.sdk.modelcontextprotocol.io/classes/types.UrlElicitationRequiredError.html Creates a .stack property on an object. The optional constructorOpt argument can be used to omit frames from the stack trace. ```javascript const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` -------------------------------- ### getInstructions Source: https://ts.sdk.modelcontextprotocol.io/classes/client.Client.html After initialization has completed, this may be populated with information about the server's instructions. ```APIDOC ## getInstructions ### Description After initialization has completed, this may be populated with information about the server's instructions. ### Method getInstructions(): string | undefined ### Returns string | undefined ``` -------------------------------- ### Initialize Source: https://ts.sdk.modelcontextprotocol.io/variables/types.ClientRequestSchema.html Initializes the client connection with the server, providing necessary capabilities and information. ```APIDOC ## POST /initialize ### Description Initializes the client connection, providing capabilities and client information. ### Method POST ### Endpoint /initialize ### Request Body - **method** (string) - Required - Must be 'initialize'. - **params** (object) - Required - **_meta** (object) - Optional - Metadata for the request. - **capabilities** (object) - Required - Client capabilities. - **elicitation** (object) - Optional - **experimental** (object) - Optional - Key-value pairs for experimental features. - **extensions** (object) - Optional - Key-value pairs for extensions. - **roots** (object) - Optional - **sampling** (object) - Optional - **tasks** (object) - Optional - **clientInfo** (object) - Required - Information about the client. - **description** (string) - Optional - **icons** (array) - Optional - **name** (string) - Required - **title** (string) - Optional - **version** (string) - Required - **websiteUrl** (string) - Optional - **protocolVersion** (string) - Required - The protocol version. ``` -------------------------------- ### Client Constructor Source: https://ts.sdk.modelcontextprotocol.io/classes/client.Client.html Initializes a new instance of the Client class. It accepts client information and optional options to configure the client's behavior and appearance. ```APIDOC ## Client Constructor ### Description Initializes a new instance of the Client class. ### Parameters * `_clientInfo`: { description?: string; icons?: { mimeType?: string; sizes?: string[]; src: string; theme?: "light" | "dark" }[]; name: string; title?: string; version: string; websiteUrl?: string } * `Optional`description?: string - An optional human-readable description of what this implementation does. * `Optional`icons?: { mimeType?: string; sizes?: string[]; src: string; theme?: "light" | "dark" }[] - Optional set of sized icons that the client can display in a user interface. * `name`: string - Intended for programmatic or logical use, but used as a display name in past specs or fallback. * `Optional`title?: string - Intended for UI and end-user contexts — optimized to be human-readable and easily understood. * `version`: string - The version of the client implementation. * `Optional`websiteUrl?: string - An optional URL of the website for this implementation. * `Optional`options: ClientOptions - Optional configuration options for the client. ``` -------------------------------- ### Server Constructor Source: https://ts.sdk.modelcontextprotocol.io/classes/server.Server.html Initializes the MCP server with essential information like name and version. Optional server info and options can be provided. ```typescript new Server( _serverInfo: { description?: string; icons?: { mimeType?: string; sizes?: string[]; src: string; theme?: "light" | "dark"; }[]; name: string; title?: string; version: string; websiteUrl?: string; }, options?: ServerOptions, ): Server ``` -------------------------------- ### getTask Source: https://ts.sdk.modelcontextprotocol.io/interfaces/shared_protocol.RequestTaskStore.html Gets the current status of a task. ```APIDOC ## getTask ### Description Gets the current status of a task. ### Method getTask ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters #### Path Parameters * taskId (string) - Required - The task identifier ### Request Example ```json { "taskId": "task-12345" } ``` ### Response #### Success Response (200) - createdAt (string) - The timestamp when the task was created. - lastUpdatedAt (string) - The timestamp when the task was last updated. - pollInterval? (number) - Optional interval for polling task status. - status (string) - The current status of the task. Possible values: "working", "input_required", "completed", "failed", "cancelled". - statusMessage? (string) - Optional message describing the task status. - taskId (string) - The unique identifier for the task. - ttl (number | null) - The time-to-live for the task, or null if not set. #### Response Example ```json { "createdAt": "2023-10-27T10:00:00Z", "lastUpdatedAt": "2023-10-27T10:05:00Z", "pollInterval": 5000, "status": "working", "taskId": "task-12345", "ttl": 3600 } ``` #### Throws If the task does not exist ``` -------------------------------- ### getTask Source: https://ts.sdk.modelcontextprotocol.io/interfaces/experimental.TaskStore.html Gets the current status of a task. ```APIDOC ## getTask ### Description Gets the current status of a task. ### Method getTask ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **taskId** (string) - Required - The task identifier * **sessionId** (string) - Optional - Optional session ID for binding the query to a specific session ### Request Example None provided in source. ### Response #### Success Response (200) * **createdAt** (string) - Description * **lastUpdatedAt** (string) - Description * **pollInterval** (number) - Optional - Description * **status** (string) - Description. Possible values: "working", "input_required", "completed", "failed", "cancelled" * **statusMessage** (string) - Optional - Description * **taskId** (string) - Description * **ttl** (number | null) - Description #### Response Example None provided in source. * **null** - Description ``` -------------------------------- ### Prompts Get Source: https://ts.sdk.modelcontextprotocol.io/variables/types.ClientRequestSchema.html Retrieves a specific prompt by its name. ```APIDOC ## POST /prompts/get ### Description Retrieves a specific prompt by its name. ### Method POST ### Endpoint /prompts/get ### Request Body - **method** (string) - Required - Must be 'prompts/get'. - **params** (object) - Required - **_meta** (object) - Optional - Metadata for the request. - **arguments** (object) - Optional - Key-value pairs of arguments for the prompt. - **name** (string) - Required - The name of the prompt. ``` -------------------------------- ### Registering a Prompt with Completions Source: https://ts.sdk.modelcontextprotocol.io/documents/server.html Demonstrates how to register a prompt with argument schema that supports completions using the `completable` wrapper. This allows clients to receive autocomplete suggestions as users type. ```APIDOC ## Register Prompt with Completions ### Description Registers a prompt that supports argument completions. Clients can use this to offer autocomplete suggestions. ### Method `server.registerPrompt(name, options, handler)` ### Parameters #### Prompt Name - **name** (string) - The unique name of the prompt. #### Options - **title** (string) - Human-readable title for the prompt. - **description** (string) - Description of the prompt's purpose. - **argsSchema** (object) - Schema for prompt arguments. Use `completable` for fields that support completion. - **fieldName**: `completable(z.type(), suggestionFunction)` - `z.type()`: The Zod schema for the argument. - `suggestionFunction`: A function that takes the partial input value and returns an array of matching suggestions. #### Handler - `({ arg1, arg2, ... }) => ({ messages: [...] })` - A function that receives the resolved arguments and returns the messages to be sent. ### Request Example (Client-side completion) ```typescript const result = await client.complete({ ref: { type: 'ref/prompt', name: 'greet' }, argument: { name: 'name', value: 'Al' } }); console.log(result.completion.values); // ['Alice'] ``` ``` -------------------------------- ### createFetchWithInit Source: https://ts.sdk.modelcontextprotocol.io/functions/shared_transport.createFetchWithInit.html Creates a fetch function that includes base RequestInit options. This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. ```APIDOC ## Function createFetchWithInit ### Description Creates a fetch function that includes base RequestInit options. This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. ### Parameters #### Path Parameters - **baseFetch** (FetchLike) - Optional - The base fetch function to wrap (defaults to global fetch) - **baseInit** (RequestInit) - Optional - The base RequestInit to merge with each request ### Returns - **FetchLike** - A wrapped fetch function that merges base options with call-specific options ``` -------------------------------- ### listTasks Source: https://ts.sdk.modelcontextprotocol.io/interfaces/shared_protocol.RequestTaskStore.html Lists tasks, optionally starting from a pagination cursor. ```APIDOC ## listTasks ### Description Lists tasks, optionally starting from a pagination cursor. ### Method listTasks ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters #### Path Parameters * `Optional` cursor: string - Optional cursor for pagination ### Request Example ```json { "cursor": "some-cursor-string" } ``` ### Response #### Success Response (200) - nextCursor? (string) - Optional cursor for the next page of results. - tasks (array) - An array of task objects. - createdAt (string) - The timestamp when the task was created. - lastUpdatedAt (string) - The timestamp when the task was last updated. - pollInterval? (number) - Optional interval for polling task status. - status (string) - The current status of the task. Possible values: "working", "input_required", "completed", "failed", "cancelled". - statusMessage? (string) - Optional message describing the task status. - taskId (string) - The unique identifier for the task. - ttl (number | null) - The time-to-live for the task, or null if not set. #### Response Example ```json { "nextCursor": "next-cursor-string", "tasks": [ { "createdAt": "2023-10-27T10:00:00Z", "lastUpdatedAt": "2023-10-27T10:05:00Z", "pollInterval": 5000, "status": "working", "taskId": "task-12345", "ttl": 3600 }, { "createdAt": "2023-10-27T09:55:00Z", "lastUpdatedAt": "2023-10-27T09:55:00Z", "status": "completed", "taskId": "task-67890", "ttl": null } ] } ``` ``` -------------------------------- ### listTasks Source: https://ts.sdk.modelcontextprotocol.io/classes/experimental.InMemoryTaskStore.html Lists tasks, optionally starting from a pagination cursor. ```APIDOC ## listTasks ### Description Lists tasks, optionally starting from a pagination cursor. ### Method listTasks(cursor?: string, _sessionId?: string) ### Parameters #### Path Parameters * **cursor** (string) - Optional - Optional cursor for pagination * **_sessionId** (string) - Optional ### Returns Promise<{ nextCursor?: string; tasks: { createdAt: string; lastUpdatedAt: string; pollInterval?: number; status: "working" | "input_required" | "completed" | "failed" | "cancelled"; statusMessage?: string; taskId: string; ttl: number | null; }[]; }> - An object containing the tasks array and an optional nextCursor ``` -------------------------------- ### Server Initialization with Logging Capability Source: https://ts.sdk.modelcontextprotocol.io/documents/server.html Initialize an `McpServer` with the `logging` capability enabled. This allows the server to send log messages and automatically filter them based on the client's requested log level. ```typescript const server = new McpServer({ name: 'my-server', version: '1.0.0' }, { capabilities: { logging: {} } }); // Client requests: only show 'warning' and above // (handled automatically by the Server) // These will be sent or suppressed based on the client's requested level: await server.sendLoggingMessage({ level: 'debug', data: 'verbose detail' }); // suppressed await server.sendLoggingMessage({ level: 'warning', data: 'something is off' }); // sent await server.sendLoggingMessage({ level: 'error', data: 'something broke' }); // sent ``` -------------------------------- ### Register a Basic Resource Source: https://ts.sdk.modelcontextprotocol.io/documents/server.html Register a resource with a URI, title, description, and MIME type. The handler function returns the resource content. ```typescript server.registerResource( 'config', 'config://app', { title: 'Application Config', description: 'Application configuration data', mimeType: 'text/plain' }, async uri => ({ contents: [{ uri: uri.href, text: 'App configuration here' }] }) ); ``` -------------------------------- ### GetTaskPayloadRequestSchema Source: https://ts.sdk.modelcontextprotocol.io/variables/types.GetTaskPayloadRequestSchema.html Schema definition for the request to get a task's payload. ```APIDOC ## GetTaskPayloadRequestSchema ### Description A request to get the result of a specific task. ### Request Body - **method** (string) - Required - Must be "tasks/result". - **params** (object) - Required - - **_meta** (object) - Optional - - **io.modelcontextprotocol/related-task** (object) - Optional - - **taskId** (string) - Required - - **progressToken** (string | number) - Optional - - **taskId** (string) - Required - ``` -------------------------------- ### listTasks Source: https://ts.sdk.modelcontextprotocol.io/classes/server.Server.html Lists tasks, optionally starting from a pagination cursor. This is an experimental feature. ```APIDOC ## listTasks ### Description Lists tasks, optionally starting from a pagination cursor. This is an experimental feature. ### Method listTasks ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (object) - Optional parameters for listing tasks, including a cursor for pagination. - **cursor** (string) - Optional cursor for pagination. - **options** (RequestOptions) - Optional request options. ### Request Example ```json { "params": { "cursor": "string" }, "options": {} } ``` ### Response #### Success Response (200) - **_meta** (_meta object) - Optional metadata for the response. - **nextCursor** (string) - The cursor for the next page of results. - **tasks** (array of objects) - A list of tasks, each with creation and update timestamps, status, and other details. #### Response Example ```json { "_meta": { "io.modelcontextprotocol/related-task": { "taskId": "string" }, "progressToken": "string | number" }, "nextCursor": "string", "tasks": [ { "createdAt": "string", "lastUpdatedAt": "string", "pollInterval": "number", "status": "working | input_required | completed | failed | cancelled", "statusMessage": "string", "taskId": "string", "ttl": "number | null" } ] } ``` ``` -------------------------------- ### getClientVersion Source: https://ts.sdk.modelcontextprotocol.io/classes/server.Server.html After initialization, this method returns information about the client's name and version, including its description, icons, name, title, version, and website URL. ```APIDOC ## getClientVersion ### Description After initialization has completed, this will be populated with information about the client's name and version. ### Returns ```typescript | { description?: string; icons?: { mimeType?: string; sizes?: string[]; src: string; theme?: "light" | "dark"; }[]; name: string; title?: string; version: string; websiteUrl?: string; } | undefined ``` ``` -------------------------------- ### Accessing Experimental Server Tasks Source: https://ts.sdk.modelcontextprotocol.io/classes/experimental.ExperimentalServerTasks.html Demonstrates how to access the experimental task features from a server instance. Use this for low-level server interactions. ```typescript const stream = server.experimental.tasks.requestStream(request, schema, options); ``` -------------------------------- ### Using CfWorkerJsonSchemaValidator with Server Source: https://ts.sdk.modelcontextprotocol.io/types/server.ServerOptions.html Example of initializing a Server with CfWorkerJsonSchemaValidator for JSON schema validation. ```typescript // @cfworker/json-schema const server = new Server( { name: 'my-server', version: '1.0.0' }, { capabilities: {}, jsonSchemaValidator: new CfWorkerJsonSchemaValidator() } ); ``` -------------------------------- ### listTasks Source: https://ts.sdk.modelcontextprotocol.io/interfaces/experimental.TaskStore.html Lists tasks, optionally starting from a pagination cursor and binding the query to a specific session. ```APIDOC ## listTasks ### Description Lists tasks, optionally starting from a pagination cursor. ### Method GET (assumed, based on listing operation) ### Endpoint /tasks ### Parameters #### Query Parameters - **cursor** (string) - Optional - Optional cursor for pagination - **sessionId** (string) - Optional - Optional session ID for binding the query to a specific session #### Response ##### Success Response (200) - **nextCursor** (string) - Optional - An optional cursor for the next page of results. - **tasks** (Array) - An array of task objects. - **createdAt** (string) - The timestamp when the task was created. - **lastUpdatedAt** (string) - The timestamp when the task was last updated. - **pollInterval** (number) - Optional - The interval in seconds for polling the task status. - **status** (string) - The current status of the task. Possible values: "working", "input_required", "completed", "failed", "cancelled". - **statusMessage** (string) - Optional - A diagnostic message for the task's status. - **taskId** (string) - The unique identifier for the task. - **ttl** (number | null) - The time-to-live for the task in seconds, or null if not set. ##### Response Example ```json { "nextCursor": "next-page-cursor", "tasks": [ { "createdAt": "2023-01-01T10:00:00Z", "lastUpdatedAt": "2023-01-01T10:05:00Z", "status": "completed", "taskId": "task-123", "ttl": 3600 } ] } ``` ``` -------------------------------- ### Connect and Inspect Server Version and Capabilities Source: https://ts.sdk.modelcontextprotocol.io/documents/protocol.html Connect to the server and retrieve the negotiated protocol version and server capabilities. This is handled automatically by `client.connect()`. ```typescript await client.connect(transport); const serverVersion = client.getServerVersion(); // { name: 'my-server', version: '1.0.0' } const serverCaps = client.getServerCapabilities(); // { tools: { listChanged: true }, resources: { subscribe: true }, ... } ``` -------------------------------- ### listTasks Source: https://ts.sdk.modelcontextprotocol.io/classes/client.Client.html Lists tasks, optionally starting from a pagination cursor. Use `client.experimental.tasks.listTasks()` to access this method. ```APIDOC ## listTasks ### Description Lists tasks, optionally starting from a pagination cursor. ### Method `client.experimental.tasks.listTasks()` ### Parameters #### Path Parameters None #### Query Parameters * `params` (object) - Optional * `cursor` (string) - Optional * `options` (RequestOptions) - Optional ### Request Example ```json { "params": { "cursor": "some_cursor" } } ``` ### Response #### Success Response (200) * `_meta` (object) - Optional * `nextCursor` (string) - Optional * `tasks` (array) - Required * `createdAt` (string) - Required * `lastUpdatedAt` (string) - Required * `pollInterval` (number) - Optional * `status` (string) - Required (working, input_required, completed, failed, cancelled) * `statusMessage` (string) - Optional * `taskId` (string) - Required * `ttl` (number | null) - Optional #### Response Example ```json { "nextCursor": "another_cursor", "tasks": [ { "createdAt": "2023-01-01T10:00:00Z", "lastUpdatedAt": "2023-01-01T10:05:00Z", "status": "completed", "taskId": "task-123", "ttl": 3600 } ] } ``` ``` -------------------------------- ### Server Constructor Source: https://ts.sdk.modelcontextprotocol.io/classes/server.Server.html Initializes a new instance of the Server class with server information and optional options. This constructor is intended for advanced use cases and allows for custom request, notification, and result types. ```APIDOC ## constructor ### Description Initializes this server with the given name and version information. ### Signature ```typescript new Server( _serverInfo: { description?: string; icons?: { mimeType?: string; sizes?: string[]; src: string; theme?: "light" | "dark"; }[]; name: string; title?: string; version: string; websiteUrl?: string; }, options?: ServerOptions ): Server ``` ### Type Parameters * `RequestT` extends `Request` * `NotificationT` extends `Notification` * `ResultT` extends `Result` ### Parameters * `_serverInfo` - An object containing information about the server, including its name, version, and optional description, icons, title, and website URL. * `options` - Optional server options. ``` -------------------------------- ### listTasks Source: https://ts.sdk.modelcontextprotocol.io/classes/shared_protocol.Protocol.html Lists tasks, optionally starting from a pagination cursor. Use `client.experimental.tasks.listTasks()` to access this method. ```APIDOC ## listTasks(params?: { cursor?: string }, options?: RequestOptions): Promise<{ _meta?: { "io.modelcontextprotocol/related-task"?: { taskId: string }; progressToken?: string | number; [key: string]: unknown; }; nextCursor?: string; tasks: { createdAt: string; lastUpdatedAt: string; pollInterval?: number; status: | "working" | "input_required" | "completed" | "failed" | "cancelled"; statusMessage?: string; taskId: string; ttl: number | null; }[]; [key: string]: unknown; }> ``` -------------------------------- ### Client.getServerCapabilities Source: https://ts.sdk.modelcontextprotocol.io/classes/client.Client.html Retrieves the server's reported capabilities after initialization. This information includes available features like completions, logging, prompts, resources, tasks, and tools. ```APIDOC ## getServerCapabilities ### Description After initialization has completed, this will be populated with the server's reported capabilities. ### Method `getServerCapabilities(): Promise | undefined` ### Parameters None ### Returns `Promise | undefined` - An object containing the server's capabilities, or undefined if not yet available. **ServerCapabilities Structure:** ```json { "completions": "object", "experimental": "{ [key: string]: object }", "extensions": "{ [key: string]: object }", "logging": "object", "prompts": "{ listChanged?: boolean }", "resources": "{ listChanged?: boolean; subscribe?: boolean }", "tasks": { "cancel": "object", "list": "object", "requests": { "tools": { "call": "object", "[key: string]: unknown" }, "[key: string]: unknown" }, "[key: string]: unknown" }, "tools": "{ listChanged?: boolean }" } ``` ``` -------------------------------- ### Using AjvJsonSchemaValidator with Server Source: https://ts.sdk.modelcontextprotocol.io/types/server.ServerOptions.html Example of initializing a Server with the default AjvJsonSchemaValidator for JSON schema validation. ```typescript // ajv (default) const server = new Server( { name: 'my-server', version: '1.0.0' }, { capabilities: {} jsonSchemaValidator: new AjvJsonSchemaValidator() } ); ``` -------------------------------- ### Experimental Server Tasks Parameters Source: https://ts.sdk.modelcontextprotocol.io/classes/experimental.ExperimentalServerTasks.html This section outlines the parameters that can be used when interacting with experimental server tasks. These include options for controlling model behavior, providing context, and specifying tool usage. ```APIDOC ## Experimental Server Tasks Parameters ### Description This section outlines the parameters that can be used when interacting with experimental server tasks. These include options for controlling model behavior, providing context, and specifying tool usage. ### Parameters * **Optional** `metadata`?: object Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. * **Optional** `modelPreferences`?: { `costPriority`?: number; `hints`?: { name?: string }[]; `intelligencePriority`?: number; `speedPriority`?: number; } The server's preferences for which model to select. The client MAY modify or omit this request. * **Optional** `costPriority`?: number How much to prioritize cost when selecting a model. * **Optional** `hints`?: { name?: string }[] Optional hints to use for model selection. * **Optional** `intelligencePriority`?: number How much to prioritize intelligence and capabilities when selecting a model. * **Optional** `speedPriority`?: number How much to prioritize sampling speed (latency) when selecting a model. * **Optional** `stopSequences`?: string[] * **Optional** `systemPrompt`?: string An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. * **Optional** `task`?: { ttl?: number } If specified, the caller is requesting task-augmented execution for this request. The request will return a CreateTaskResult immediately, and the actual result can be retrieved later via tasks/result. Task augmentation is subject to capability negotiation - receivers MUST declare support for task augmentation of specific request types in their capabilities. * **Optional** `temperature`?: number * **Optional** `toolChoice`?: { mode?: "required" | "none" | "auto" } Controls how the model uses tools. The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. Default is `{ mode: "auto" }`. * **Optional** `mode`?: "required" | "none" | "auto" Controls when tools are used: * "auto": Model decides whether to use tools (default) * "required": Model MUST use at least one tool before completing * "none": Model MUST NOT use any tools * **Optional** `tools`?: { `_meta`?: { [key: string]: unknown }; `annotations`?: { destructiveHint?: boolean; idempotentHint?: boolean; openWorldHint?: boolean; readOnlyHint?: boolean; title?: string; }; `description`?: string; `execution`?: { taskSupport?: "optional" | "required" | "forbidden" }; `icons`?: { mimeType?: string; sizes?: string[]; src: string; theme?: "light" | "dark"; }[]; `inputSchema`: { properties?: { [key: string]: object }; required?: string[]; type: "object"; [key: string]: unknown; }; `outputSchema`?: { properties?: { [key: string]: object }; required?: string[]; type: "object"; [key: string]: unknown; }; `name`: string; `title`?: string; }[] Tools that the model may use during generation. The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. * **Optional** `options`: RequestOptions Optional request options (timeout, signal, task creation params, onprogress, etc.) ``` -------------------------------- ### getTask Source: https://ts.sdk.modelcontextprotocol.io/classes/shared_protocol.Protocol.html Experimental method to get the current status of a task. Use `client.experimental.tasks.getTask()` to access this method. ```APIDOC ## getTask ### Description Gets the current status of a task. ### Method GET ### Endpoint /experimental/tasks/{taskId} ### Parameters #### Path Parameters - **taskId** (string) - Required - The ID of the task to retrieve. #### Query Parameters - None #### Request Body - **_meta** (object) - Optional - Metadata about the request. - **io.modelcontextprotocol/related-task** (object) - Optional - If specified, this request is related to the provided task. - **taskId** (string) - Required - The ID of the related task. - **progressToken** (string | number) - Optional - If specified, the caller is requesting out-of-band progress notifications. - **options** (RequestOptions) - Optional - Request options. ### Request Example ```json { "_meta": { "io.modelcontextprotocol/related-task": { "taskId": "string" }, "progressToken": "string | number" }, "options": {} } ``` ### Response #### Success Response (200) - **_meta** (object) - Optional - Metadata about the request. - **io.modelcontextprotocol/related-task** (object) - Optional - If specified, this request is related to the provided task. - **taskId** (string) - Required - The ID of the related task. - **progressToken** (string | number) - Optional - If specified, the caller is requesting out-of-band progress notifications. - **createdAt** (string) - Required - The timestamp when the task was created. - **lastUpdatedAt** (string) - Required - The timestamp when the task was last updated. - **pollInterval** (number) - Optional - The interval in seconds to poll for task status. - **status** (string) - Required - The current status of the task. Possible values: "working", "input_required", "completed", "failed", "cancelled". - **statusMessage** (string) - Optional - A message describing the current status. - **taskId** (string) - Required - The ID of the task. - **ttl** (number | null) - Optional - The time-to-live in seconds for the task. #### Response Example ```json { "_meta": { "io.modelcontextprotocol/related-task": { "taskId": "string" }, "progressToken": "string | number" }, "createdAt": "string", "lastUpdatedAt": "string", "pollInterval": 0, "status": "completed", "statusMessage": "string", "taskId": "string", "ttl": 0 } ``` ``` -------------------------------- ### getServerVersion Source: https://ts.sdk.modelcontextprotocol.io/classes/client.Client.html Retrieves information about the server's name and version after initialization. ```APIDOC ## getServerVersion ### Description After initialization has completed, this will be populated with information about the server's name and version. ### Method `getServerVersion()` ### Returns - `object` | `undefined` - `description`?: `string` - `icons`?: `array` - `mimeType`?: `string` - `sizes`?: `array` - `src`: `string` - `theme`?: `"light" | "dark"` - `name`: `string` - `title`?: `string` - `version`: `string` - `websiteUrl`?: `string` ``` -------------------------------- ### ExperimentalClientTasks Constructor Source: https://ts.sdk.modelcontextprotocol.io/classes/experimental.ExperimentalClientTasks.html Initializes a new instance of the ExperimentalClientTasks class. ```APIDOC ## constructor * new ExperimentalClientTasks( _client: Client ): ExperimentalClientTasks ### Parameters * _client: Client ### Returns ExperimentalClientTasks ``` -------------------------------- ### assertCanSetRequestHandler Source: https://ts.sdk.modelcontextprotocol.io/classes/client.Client.html Asserts that a request handler has not already been set for the given method, preparing for a new one to be installed. ```APIDOC ## assertCanSetRequestHandler ### Description Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. ### Method Signature assertCanSetRequestHandler(method: string): void ### Parameters #### Parameters - **method** (string) - Description: The method to check for an existing request handler. ``` -------------------------------- ### Registering a Tool Source: https://ts.sdk.modelcontextprotocol.io/documents/server.html Register a tool with a name, configuration (including input/output schemas), and an async function to execute the tool's logic. The function should return content and optionally structured content. ```APIDOC ## registerTool ### Description Registers a tool that clients (like LLMs) can invoke. ### Method `server.registerTool(name, toolDefinition, handler)` ### Parameters #### Path Parameters - **name** (string) - Required - The unique identifier for the tool. - **toolDefinition** (object) - Required - Defines the tool's properties. - **title** (string) - Optional - A human-readable title for the tool. - **description** (string) - Required - A description of what the tool does. - **inputSchema** (object) - Optional - Defines the expected input structure using a schema (e.g., Zod). - **outputSchema** (object) - Optional - Defines the expected output structure using a schema (e.g., Zod). #### Handler Function - **handler** (async function) - Required - The function that executes the tool's logic. It receives input parameters based on `inputSchema` and should return an object containing: - **content** (array) - Required - An array of content items (e.g., text, image, audio, resource). - **structuredContent** (any) - Optional - The structured output of the tool. - **isError** (boolean) - Optional - Set to true if the tool execution resulted in an error. ### Request Example ```javascript server.registerTool( 'calculate-bmi', { title: 'BMI Calculator', description: 'Calculate Body Mass Index', inputSchema: { weightKg: z.number(), heightM: z.number() }, outputSchema: { bmi: z.number() } }, async ({ weightKg, heightM }) => { const output = { bmi: weightKg / (heightM * heightM) }; return { content: [{ type: 'text', text: JSON.stringify(output) }], structuredContent: output }; } ); ``` ``` -------------------------------- ### assertCanSetRequestHandler Source: https://ts.sdk.modelcontextprotocol.io/classes/server.Server.html Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. ```APIDOC ## assertCanSetRequestHandler ### Description Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. ### Method * assertCanSetRequestHandler(method: string): void ### Parameters #### Path Parameters * **method** (string) - Required - The method to check. ### Returns void ``` -------------------------------- ### ProtocolOptions Source: https://ts.sdk.modelcontextprotocol.io/types/shared_protocol.ProtocolOptions.html Defines optional configuration settings for initializing the protocol, allowing customization of notification handling, task polling, capability enforcement, and message queuing. ```APIDOC ## Type Alias ProtocolOptions Additional initialization options. type ProtocolOptions = { debouncedNotificationMethods?: string[]; defaultTaskPollInterval?: number; enforceStrictCapabilities?: boolean; maxTaskQueueSize?: number; taskMessageQueue?: TaskMessageQueue; taskStore?: TaskStore; } ### Properties * **debouncedNotificationMethods** (`string[]`): An array of notification method names that should be automatically debounced. Notifications with methods in this list will be coalesced if they occur in the same tick of the event loop. Example: `['notifications/tools/list_changed']`. * **defaultTaskPollInterval** (`number`): Default polling interval (in milliseconds) for task status checks when no `pollInterval` is provided by the server. Defaults to 5000ms if not specified. * **enforceStrictCapabilities** (`boolean`): Whether to restrict emitted requests to only those that the remote side has indicated that they can handle through their advertised capabilities. Defaults to `false` for backwards compatibility. * **maxTaskQueueSize** (`number`): Maximum number of messages that can be queued per task for side-channel delivery. If undefined, the queue size is unbounded. When the limit is exceeded, the `TaskMessageQueue` implementation's `enqueue()` method will throw an error. * **taskMessageQueue** (`TaskMessageQueue`): Optional task message queue implementation for managing server-initiated messages that will be delivered through the tasks/result response stream. * **taskStore** (`TaskStore`): Optional task storage implementation. If provided, enables task-related request handlers and provides task storage capabilities to request handlers. ``` -------------------------------- ### Implement jsonSchemaValidator Interface Source: https://ts.sdk.modelcontextprotocol.io/interfaces/validation.jsonSchemaValidator.html Example of how to implement the jsonSchemaValidator interface. This class provides a validator function that checks input against a schema. ```typescript class MyValidatorProvider implements jsonSchemaValidator { getValidator(schema: JsonSchemaType): JsonSchemaValidator { // Compile/cache validator from schema return (input: unknown) => { // Validate input against schema if (valid) { return { valid: true, data: input as T, errorMessage: undefined }; } else { return { valid: false, data: undefined, errorMessage: 'Error details' }; } }; } } ``` -------------------------------- ### createTask Source: https://ts.sdk.modelcontextprotocol.io/interfaces/experimental.ToolTaskHandler.html Initiates a new task and returns its initial state. ```APIDOC ## createTask ### Description Creates a new task. ### Method (Implicitly a method call within the SDK) ### Parameters (Refer to the `BaseToolCallback` type for detailed parameter structure) ### Request Example (Example structure for the task object would be provided here if available in source) ### Response #### Success Response Returns the initial state of the created task, including its ID and status. #### Response Example (Example structure for the task object would be provided here if available in source) ``` -------------------------------- ### Get Task Status Source: https://ts.sdk.modelcontextprotocol.io/classes/experimental.ExperimentalClientTasks.html Retrieves the current status of a specified task. Requires the taskId and optionally accepts request options. ```typescript const taskStatus = await client.experimental.tasks.getTask(taskId); ``` -------------------------------- ### InMemoryTaskStore Constructor Source: https://ts.sdk.modelcontextprotocol.io/classes/experimental.InMemoryTaskStore.html Initializes a new instance of the InMemoryTaskStore. This is an experimental feature. ```APIDOC ## constructor * new InMemoryTaskStore(): InMemoryTaskStore `Experimental` #### Returns InMemoryTaskStore ``` -------------------------------- ### Getting Display Names Source: https://ts.sdk.modelcontextprotocol.io/documents/server.html Explains how to obtain human-readable display names for tools, resources, and prompts using the `getDisplayName` utility function. ```APIDOC ## Get Display Name ### Description Provides a utility function to compute the correct display name for tools, resources, and prompts, supporting both modern `title` fields and older `annotations.title`. ### Function `getDisplayName(item)` ### Parameters - **item** (object) - An object representing a tool, resource, or prompt, which may contain `title` or `annotations.title` fields. ### Usage ```typescript import { getDisplayName } from '@modelcontextprotocol/sdk/shared/metadataUtils.js'; // Assuming 'promptObject' has a 'title' or 'annotations.title' field const displayName = getDisplayName(promptObject); ``` ``` -------------------------------- ### Get Task Result Source: https://ts.sdk.modelcontextprotocol.io/classes/experimental.ExperimentalServerTasks.html Retrieves the result of a completed task. Optionally, provide a Zod schema to validate the result's structure. ```typescript const taskResult = await server.experimental.tasks.getTaskResult('your-task-id', yourResultSchema); ```