### Install project dependencies Source: https://ts.sdk.modelcontextprotocol.io/ Install all necessary dependencies from the SDK repository root. ```bash npm install ``` -------------------------------- ### Run interactive client example Source: https://ts.sdk.modelcontextprotocol.io/ Execute the interactive client example in a separate terminal. ```bash npx tsx src/examples/client/simpleStreamableHttp.ts ``` -------------------------------- ### Install MCP SDK dependencies Source: https://ts.sdk.modelcontextprotocol.io/ Install the SDK and its required peer dependency, Zod. ```bash npm install @modelcontextprotocol/sdk zod ``` -------------------------------- ### Run Streamable HTTP server example Source: https://ts.sdk.modelcontextprotocol.io/ Execute the simple Streamable HTTP server example using tsx. ```bash npx tsx src/examples/server/simpleStreamableHttp.ts ``` -------------------------------- ### InMemoryTransport.start() Source: https://ts.sdk.modelcontextprotocol.io/api/inMemory.html Starts processing messages on the transport. ```APIDOC ## start() ### Description Starts processing messages. This should be called after callbacks are installed. Note: This is typically called implicitly by Client or Server classes. ### Returns - **Promise** ``` -------------------------------- ### Elicitation Input Stream Example Source: https://ts.sdk.modelcontextprotocol.io/api/experimental.html Demonstrates initiating an elicitation request with task-augmented execution for long-running flows. ```typescript const stream = server.experimental.tasks.elicitInputStream({ mode: 'url', message: 'Please authenticate', elicitationId: 'auth-123', url: 'https://example.com/auth' }, { task: { ttl: 300000 } // Task-augmented for long-running auth flow }); ``` -------------------------------- ### Initialize Server with JSON Schema Validators Source: https://ts.sdk.modelcontextprotocol.io/api/server.html Examples of initializing a server instance using either the default Ajv validator or the @cfworker/json-schema validator. ```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() } ); ``` -------------------------------- ### connect(transport) Source: https://ts.sdk.modelcontextprotocol.io/api/shared/protocol.html Attaches to the given transport, starts it, and begins listening for messages. The protocol assumes ownership of the transport instance. ```APIDOC ## connect(transport) ### Description Attaches to the given transport, starts it, and starts listening for messages. The Protocol object assumes ownership of the Transport. ### Parameters - **transport** (Transport) - Required - The transport instance to connect to. ``` -------------------------------- ### listTasks() Source: https://ts.sdk.modelcontextprotocol.io/api/shared/protocol.html Lists tasks, optionally starting from a pagination cursor. ```APIDOC ## listTasks(cursor?) ### Description Lists tasks, optionally starting from a pagination cursor. ### Parameters - **cursor** (string) - Optional - Optional cursor for pagination ### Returns - **Promise<{ nextCursor?: string; tasks: object[]; }>** - An object containing the tasks array and an optional nextCursor ``` -------------------------------- ### listTasks(cursor?, sessionId?) Source: https://ts.sdk.modelcontextprotocol.io/api/experimental.html Lists tasks, optionally starting from a pagination cursor. ```APIDOC ## listTasks(cursor?, sessionId?) ### Description Lists tasks, optionally starting from a pagination cursor. ### Parameters - **cursor** (string) - Optional - Optional cursor for pagination - **sessionId** (string) - Optional - Optional session ID for binding the query to a specific session ### Returns - **Promise** (object) - An object containing the tasks array and an optional nextCursor. ``` -------------------------------- ### listTasks(cursor?, _sessionId?) Source: https://ts.sdk.modelcontextprotocol.io/api/experimental.html Lists tasks, optionally starting from a pagination cursor. ```APIDOC ## listTasks(cursor?, _sessionId?) ### Description Lists tasks, optionally starting from a pagination cursor. ### Parameters - **cursor** (string) - Optional - Optional cursor for pagination - **_sessionId** (string) - Optional ### Returns - **Promise<{ nextCursor?: string; tasks: object[]; }>** - An object containing the tasks array and an optional nextCursor ``` -------------------------------- ### Implement a long-running task handler Source: https://ts.sdk.modelcontextprotocol.io/api/experimental.html Example of registering a tool with a handler that implements createTask, getTask, and getTaskResult for background processing. ```typescript server.experimental.tasks.registerToolTask('long-computation', { description: 'Performs a long computation', inputSchema: { input: z.string() }, execution: { taskSupport: 'required' } }, { createTask: async (args, extra) => { const task = await extra.taskStore.createTask({ ttl: 300000 }); startBackgroundWork(task.taskId, args); return { task }; }, getTask: async (args, extra) => { return extra.taskStore.getTask(extra.taskId); }, getTaskResult: async (args, extra) => { return extra.taskStore.getTaskResult(extra.taskId); } }); ``` -------------------------------- ### getInstructions() Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Retrieves server instructions after initialization. ```APIDOC ## getInstructions() ### Description Returns the server's instructions if they have been populated after initialization. ### Returns - **string | undefined** - The instructions string or undefined if not available. ``` -------------------------------- ### new Client(clientInfo, options) Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Initializes a new instance of the MCP Client with the specified client information and optional configuration. ```APIDOC ## Constructor: new Client(clientInfo, options) ### Description Initializes this client with the given name and version information. The client will automatically begin the initialization flow with the server when connect() is called. ### Parameters #### _clientInfo - **name** (string) - Required - Intended for programmatic or logical use. - **version** (string) - Required - The version of the client implementation. - **description** (string) - Optional - A human-readable description of the implementation. - **title** (string) - Optional - A human-readable title for UI contexts. - **websiteUrl** (string) - Optional - URL of the website for this implementation. - **icons** (object[]) - Optional - A set of sized icons for UI display. #### options - **options** (ClientOptions) - Optional - Configuration options for the client. ``` -------------------------------- ### Server Constructor Source: https://ts.sdk.modelcontextprotocol.io/api/server.html Initializes a new MCP server instance with the specified server information and optional configuration. ```APIDOC ## Constructor ### Description Initializes this server with the given name and version information. ### Signature new Server(_serverInfo, options?) ### Parameters - **_serverInfo** (object) - Required - Server metadata including name, version, and optional fields like description, icons, title, and websiteUrl. - **options** (ServerOptions) - Optional - Additional configuration options for the server. ``` -------------------------------- ### fallbackRequestHandler Source: https://ts.sdk.modelcontextprotocol.io/api/client.html A handler to invoke for any request types that do not have their own handler installed. ```APIDOC ## fallbackRequestHandler ### Description A handler to invoke for any request types that do not have their own handler installed. ### Parameters - **request** (object) - The request object containing id, jsonrpc, method, and optional params. - **extra** (RequestHandlerExtra) - Additional request handler context. ### Returns - **Promise** - A promise resolving to the request result. ``` -------------------------------- ### connect(transport, options?) Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Initializes the client connection using a specified transport. ```APIDOC ## connect(transport, options?) ### Description Attaches to the given transport, starts it, and begins listening for messages. The client assumes ownership of the transport. ### Parameters - **transport** (Transport) - The transport instance to connect to. - **options** (RequestOptions, optional) - Connection options. ``` -------------------------------- ### createFetchWithInit() Source: https://ts.sdk.modelcontextprotocol.io/api/shared/transport.html Creates a fetch function that includes base RequestInit options, ensuring requests inherit settings like credentials, mode, and headers. ```APIDOC ## createFetchWithInit(baseFetch?, baseInit?) ### 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 - **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 ``` -------------------------------- ### Configure Client with JSON Schema Validator Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Demonstrates how to initialize a client with different JSON schema validator implementations. ```typescript // ajv const client = new Client( { name: 'my-client', version: '1.0.0' }, { capabilities: {}, jsonSchemaValidator: new AjvJsonSchemaValidator() } ); // @cfworker/json-schema const client = new Client( { name: 'my-client', version: '1.0.0' }, { capabilities: {}, jsonSchemaValidator: new CfWorkerJsonSchemaValidator() } ); ``` -------------------------------- ### getServerVersion() Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Retrieves the server's name and version information after initialization. ```APIDOC ## getServerVersion() ### Description Returns information about the connected MCP server, including its name and version. This method is available after the client has successfully initialized. ### Returns - **Object | undefined** - An object containing the server's `name` (string) and `version` (string), along with optional fields like `description`, `icons`, `title`, and `websiteUrl`. ``` -------------------------------- ### getServerCapabilities() Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Retrieves the capabilities reported by the MCP server after initialization has completed. ```APIDOC ## getServerCapabilities() ### Description Returns the server's reported capabilities, including support for completions, logging, prompts, resources, tasks, and tools. This method is available after the client has successfully initialized. ### Returns - **Object | undefined** - The server capabilities object containing optional fields for completions, experimental features, extensions, logging, prompts, resources, tasks, and tools. ``` -------------------------------- ### listPrompts() Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Retrieves a list of available prompts from the server, supporting optional pagination and metadata. ```APIDOC ## listPrompts() ### Description Retrieves a list of available prompts from the server. Supports pagination via a cursor and optional metadata for task tracking or progress notifications. ### Parameters - **params** (object) - Optional - **cursor** (string) - Optional: An opaque token representing the current pagination position. - **_meta** (object) - Optional - **io.modelcontextprotocol/related-task** (object) - Optional: Links the request to a specific task ID. - **progressToken** (string | number) - Optional: Token for out-of-band progress notifications. - **options** (RequestOptions) - Optional ### Returns - **Promise** (object) - A promise resolving to an object containing the list of prompts, an optional nextCursor, and metadata. ``` -------------------------------- ### Configure Client List Changed Handlers Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Shows how to register handlers for tool and prompt update notifications. ```typescript const client = new Client( { name: 'my-client', version: '1.0.0' }, { listChanged: { tools: { onChanged: (error, tools) => { if (error) { console.error('Failed to refresh tools:', error); return; } console.log('Tools updated:', tools); } }, prompts: { onChanged: (error, prompts) => console.log('Prompts updated:', prompts) } } } ); ``` -------------------------------- ### Capture Stack Trace Source: https://ts.sdk.modelcontextprotocol.io/api/types.html Demonstrates how to create a .stack property on an object and how to use constructorOpt to omit specific frames from the stack trace. ```javascript const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` ```javascript function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` -------------------------------- ### Configure Server Logging and Filtering Source: https://ts.sdk.modelcontextprotocol.io/server.html Initialize the McpServer with logging capabilities to enable automatic log level filtering based on client requests. ```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 ``` -------------------------------- ### server.registerPrompt Source: https://ts.sdk.modelcontextprotocol.io/server.html Registers a new prompt template on the server that clients can list and invoke. ```APIDOC ## server.registerPrompt(name, promptDefinition, promptHandler) ### Description Registers a reusable prompt template. The handler function receives the arguments and returns a set of messages to be sent to the model. ### Parameters - **name** (string) - Required - The unique identifier for the prompt. - **promptDefinition** (object) - Required - Contains metadata including title, description, and argsSchema (using Zod). - **promptHandler** (function) - Required - A function that takes arguments and returns a prompt message structure. ### Example ```typescript server.registerPrompt( 'review-code', { title: 'Code Review', description: 'Review code for best practices', argsSchema: { code: z.string() } }, ({ code }) => ({ messages: [{ role: 'user', content: { type: 'text', text: `Please review: ${code}` } }] }) ); ``` -------------------------------- ### getPrompt(params, options?) Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Retrieves a prompt definition from the server. ```APIDOC ## getPrompt(params, options?) ### Description Fetches a specific prompt from the server based on the provided parameters. ### Parameters - **params** (object) - The parameters required to identify the prompt. - **options** (RequestOptions, optional) - Request configuration options. ### Returns - **Promise** - Returns the prompt object containing messages and an optional description. ``` -------------------------------- ### getClientVersion() Source: https://ts.sdk.modelcontextprotocol.io/api/server.html Retrieves information about the client's name and version after initialization has completed. ```APIDOC ## getClientVersion() ### Description Returns the client's metadata, including name, version, and optional UI-related information like icons and website URL. ### Returns - **description** (string) - Optional human-readable description. - **icons** (object[]) - Optional set of sized icons. - **name** (string) - The client name. - **title** (string) - Human-readable title for UI contexts. - **version** (string) - The client version. - **websiteUrl** (string) - Optional URL for the implementation. ``` -------------------------------- ### Inspect Server Capabilities Source: https://ts.sdk.modelcontextprotocol.io/protocol.html Check supported server capabilities after establishing a connection. ```typescript await client.connect(transport); const caps = client.getServerCapabilities(); if (caps?.tools) { const tools = await client.listTools(); } if (caps?.resources?.subscribe) { // server supports resource subscriptions } ``` -------------------------------- ### listTools() Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Lists the tools available on the server, optionally using a pagination cursor. ```APIDOC ## listTools(params?, options?) ### Description Lists the tools available on the server. Supports pagination via a cursor and optional metadata for task tracking or progress reporting. ### Parameters - **params** (object) - Optional - **cursor** (string) - An opaque token representing the current pagination position. - **_meta** (object) - Metadata for the request. - **io.modelcontextprotocol/related-task** (object) - Related task information. - **taskId** (string) - The ID of the related task. - **progressToken** (string | number) - Token for out-of-band progress notifications. - **options** (RequestOptions) - Optional request configuration. ### Returns - **Promise** (object) - A promise resolving to an object containing the list of tools and an optional nextCursor. ``` -------------------------------- ### Create a message stream with experimental tasks Source: https://ts.sdk.modelcontextprotocol.io/api/experimental.html Demonstrates how to initiate a message stream using the experimental task API and handle various message types including progress, task status, and final results. ```typescript const stream = server.experimental.tasks.createMessageStream({ messages: [{ role: 'user', content: { type: 'text', text: 'Hello' } }], maxTokens: 100 }, { onprogress: (progress) => { // Handle streaming tokens via progress notifications console.log('Progress:', progress.message); } }); for await (const message of stream) { switch (message.type) { case 'taskCreated': console.log('Task created:', message.task.taskId); break; case 'taskStatus': console.log('Task status:', message.task.status); break; case 'result': console.log('Final result:', message.result); break; case 'error': console.error('Error:', message.error); break; } } ``` -------------------------------- ### sampling/create Source: https://ts.sdk.modelcontextprotocol.io/api/server.html Requests LLM sampling from the client. This method allows the server to specify model preferences, system prompts, and tool configurations for the sampling process. ```APIDOC ## sampling/create ### Description Requests LLM sampling from the client. The client may choose to modify or omit certain parameters like model preferences or system prompts. ### Parameters - **messages** (object[]) - Required - The list of messages to be processed by the LLM. - **maxTokens** (number) - Required - The requested maximum number of tokens to sample. - **_meta** (object) - Optional - Metadata including progress tokens or related task IDs. - **includeContext** ("none" | "thisServer" | "allServers") - Optional - Request to include context from MCP servers. Default is "none". - **metadata** (object) - Optional - Provider-specific metadata to pass to the LLM. - **modelPreferences** (object) - Optional - Preferences for model selection including cost, intelligence, and speed priorities. - **stopSequences** (string[]) - Optional - Sequences that stop the generation. - **systemPrompt** (string) - Optional - An optional system prompt for the sampling. - **task** (object) - Optional - Configuration for task-augmented execution. - **temperature** (number) - Optional - Sampling temperature. - **toolChoice** (object) - Optional - Controls tool usage mode ("auto", "required", "none"). - **tools** (object[]) - Optional - Tools available for the model to use. ``` -------------------------------- ### createMessage(params, options?) Source: https://ts.sdk.modelcontextprotocol.io/api/server.html Request LLM sampling from the client. ```APIDOC ## createMessage(params, options?) ### Description Request LLM sampling from the client (without tools). Returns single content block for backwards compatibility. ### Parameters - **params** (CreateMessageRequestParamsBase) - Required - **options** (RequestOptions) - Optional ### Returns - **Promise** - Returns the sampled message content. ``` -------------------------------- ### complete(params, options?) Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Requests completion suggestions from the server based on provided arguments or references. ```APIDOC ## complete(params, options?) ### Description Requests completion suggestions for arguments or references from the server. ### Parameters - **params** (object) - The completion request parameters. - **options** (RequestOptions, optional) - Request configuration options. ### Returns - **Promise** - Returns an object containing completion values, including 'values' (string array) and optional metadata. ``` -------------------------------- ### getClientCapabilities() Source: https://ts.sdk.modelcontextprotocol.io/api/server.html Retrieves the client's reported capabilities after the initialization process has completed. ```APIDOC ## getClientCapabilities() ### Description Returns the client's reported capabilities. This method should only be called after initialization has completed. ### Returns - **Object** - An object containing the client's capabilities, including elicitation, experimental, extensions, roots, sampling, and tasks support. ``` -------------------------------- ### Initialize a Typed MCP Server Source: https://ts.sdk.modelcontextprotocol.io/api/server.html Configure a server with custom Zod schemas for requests, notifications, and results to ensure type safety. ```typescript // Custom schemas const CustomRequestSchema = RequestSchema.extend({...}) const CustomNotificationSchema = NotificationSchema.extend({...}) const CustomResultSchema = ResultSchema.extend({...}) // Type aliases type CustomRequest = z.infer type CustomNotification = z.infer type CustomResult = z.infer // Create typed server const server = new Server({ name: "CustomServer", version: "1.0.0" }) ``` -------------------------------- ### listRoots() Source: https://ts.sdk.modelcontextprotocol.io/api/server.html Lists the roots available to the server. ```APIDOC ## listRoots() ### Description Lists the roots available to the server. This method can accept optional parameters for meta-information and request options. ### Parameters - **params** (object) - Optional - Parameters including _meta information. - **options** (RequestOptions) - Optional - Request configuration options. ### Returns - **Promise** - A promise resolving to an object containing the list of roots and optional meta-information. ``` -------------------------------- ### Request completions from client Source: https://ts.sdk.modelcontextprotocol.io/server.html Demonstrates how a client requests autocomplete values for a specific prompt argument. ```typescript const result = await client.complete({ ref: { type: 'ref/prompt', name: 'greet' }, argument: { name: 'name', value: 'Al' } }); console.log(result.completion.values); // ['Alice'] ``` -------------------------------- ### Return Image and Audio Tool Results Source: https://ts.sdk.modelcontextprotocol.io/server.html Returns non-text content from tools using base64-encoded data and specific MIME types. ```typescript // e.g. const chartPngBase64 = fs.readFileSync('chart.png').toString('base64'); server.registerTool('generate-chart', { description: 'Generate a chart image' }, async () => ({ content: [ { type: 'image', data: chartPngBase64, mimeType: 'image/png' } ] })); // e.g. const audioBase64 = fs.readFileSync('speech.wav').toString('base64'); server.registerTool( 'text-to-speech', { description: 'Convert text to speech', inputSchema: { text: z.string() } }, async ({ text }) => ({ content: [ { type: 'audio', data: audioBase64, mimeType: 'audio/wav' } ] }) ); ``` -------------------------------- ### getAllTasks() Source: https://ts.sdk.modelcontextprotocol.io/api/experimental.html Retrieves all tasks currently in the store, primarily for debugging purposes. ```APIDOC ## getAllTasks() ### Description Get all tasks (useful for debugging). ### Returns - **Array** (object[]) - A list of all tasks. ``` -------------------------------- ### registerCapabilities() Source: https://ts.sdk.modelcontextprotocol.io/api/server.html Registers new capabilities for the server. ```APIDOC ## registerCapabilities() ### Description Registers new capabilities. This can only be called before connecting to a transport. The new capabilities will be merged with any existing capabilities. ### Parameters - **capabilities** (object) - Required - The capabilities to register, including completions, experimental, extensions, and logging settings. ### Returns - **void** ``` -------------------------------- ### Configure Client Capabilities Source: https://ts.sdk.modelcontextprotocol.io/protocol.html Define client capabilities during the Client constructor initialization. ```typescript const client = new Client( { name: 'my-client', version: '1.0.0' }, { capabilities: { roots: { listChanged: true }, sampling: {}, elicitation: { form: {} } } } ); ``` -------------------------------- ### listResources() Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Retrieves a list of available resources from the server, supporting optional pagination and metadata. ```APIDOC ## listResources() ### Description Retrieves a list of available resources from the server. Supports pagination via a cursor and optional metadata for task tracking or progress notifications. ### Parameters - **params** (object) - Optional - **cursor** (string) - Optional: An opaque token representing the current pagination position. - **_meta** (object) - Optional - **io.modelcontextprotocol/related-task** (object) - Optional: Links the request to a specific task ID. - **progressToken** (string | number) - Optional: Token for out-of-band progress notifications. - **options** (RequestOptions) - Optional ### Returns - **Promise** (object) - A promise resolving to an object containing the list of resources, an optional nextCursor, and metadata. ``` -------------------------------- ### completable Source: https://ts.sdk.modelcontextprotocol.io/server.html Wraps an argument schema to provide autocomplete suggestions to the client. ```APIDOC ## completable(schema, completionProvider) ### Description Wraps a Zod schema to enable argument completion. The completionProvider function receives the partial input and returns an array of matching suggestions. ### Parameters - **schema** (ZodSchema) - Required - The base schema for the argument. - **completionProvider** (function) - Required - A function that takes the partial value and returns an array of strings. ### Example ```typescript import { completable } from '@modelcontextprotocol/sdk/server/completable.js'; argsSchema: { name: completable(z.string(), value => ['Alice', 'Bob'].filter(n => n.startsWith(value))) } ``` -------------------------------- ### createMessage(params, options?) Source: https://ts.sdk.modelcontextprotocol.io/api/server.html Requests LLM sampling from the client with tool support. This method returns content that may be a single block or an array, supporting parallel tool calls. ```APIDOC ## createMessage(params, options?) ### Description Requests LLM sampling from the client with tool support. Returns content that may be a single block or array (for parallel tool calls). ### Parameters - **params** (CreateMessageRequestParamsWithTools) - Required - The parameters for the message creation request. - **options** (RequestOptions) - Optional - Additional request options. ### Returns - **Promise** - A promise that resolves to the message response containing the model, role, and content blocks. ``` -------------------------------- ### Implement argument completions Source: https://ts.sdk.modelcontextprotocol.io/server.html Uses the completable wrapper to provide autocomplete suggestions for prompt arguments. ```typescript import { completable } from '@modelcontextprotocol/sdk/server/completable.js'; server.registerPrompt( 'greet', { title: 'Greeting', description: 'Generate a greeting', argsSchema: { name: completable(z.string(), value => { // Return suggestions matching the partial input const names = ['Alice', 'Bob', 'Charlie']; return names.filter(n => n.toLowerCase().startsWith(value.toLowerCase())); }) } }, ({ name }) => ({ messages: [{ role: 'user', content: { type: 'text', text: `Hello, ${name}!` } }] }) ); ``` -------------------------------- ### SUPPORTED_PROTOCOL_VERSIONS Constant Source: https://ts.sdk.modelcontextprotocol.io/api/types.html Array of strings representing the protocol versions supported by the SDK. ```typescript const SUPPORTED_PROTOCOL_VERSIONS : string[] ``` -------------------------------- ### request(request, resultSchema, options?) Source: https://ts.sdk.modelcontextprotocol.io/api/server.html Sends a request and waits for a response. ```APIDOC ## request(request, resultSchema, options?) ### Description Sends a request and waits for a response. Do not use this method to emit notifications; use notification() instead. ### Parameters - **request** (RequestT | ServerRequest) - Required - The request object to send. - **resultSchema** (T) - Required - The schema to validate the result. - **options** (RequestOptions) - Optional - Additional request options. ### Returns - **Promise>** - A promise that resolves to the result. ``` -------------------------------- ### Register a basic prompt Source: https://ts.sdk.modelcontextprotocol.io/server.html Defines a prompt template with a text-based user message. ```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}` } } ] }) ); ``` -------------------------------- ### listResourceTemplates() Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Retrieves a list of available resource templates from the server, supporting optional pagination and metadata. ```APIDOC ## listResourceTemplates() ### Description Retrieves a list of available resource templates from the server. Supports pagination via a cursor and optional metadata for task tracking or progress notifications. ### Parameters - **params** (object) - Optional - **cursor** (string) - Optional: An opaque token representing the current pagination position. - **_meta** (object) - Optional - **io.modelcontextprotocol/related-task** (object) - Optional: Links the request to a specific task ID. - **progressToken** (string | number) - Optional: Token for out-of-band progress notifications. - **options** (RequestOptions) - Optional ### Returns - **Promise** (object) - A promise resolving to an object containing the list of resource templates, an optional nextCursor, and metadata. ``` -------------------------------- ### Register a Tool Source: https://ts.sdk.modelcontextprotocol.io/server.html Registers a tool with input and output schemas to allow LLMs to interact with server functionality. ```typescript 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 }; } ); ``` -------------------------------- ### sampling/createMessage Source: https://ts.sdk.modelcontextprotocol.io/api/types.html A request from the server to sample an LLM via the client. The client has full discretion over model selection and should inform the user before sampling to allow for human-in-the-loop approval. ```APIDOC ## sampling/createMessage ### Description 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. ### Parameters - **method** (string) - Required - Must be "sampling/createMessage" - **params** (object) - Required - Contains the sampling configuration including messages, maxTokens, and optional model preferences or tools. ``` -------------------------------- ### experimental Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Access experimental features. ```APIDOC ## experimental ### Description Access experimental features. WARNING: These APIs are experimental and may change without notice. ### Returns - **object** - An object containing experimental features, such as tasks. ``` -------------------------------- ### Connect to a local server using StdioClientTransport Source: https://ts.sdk.modelcontextprotocol.io/client.html Use StdioClientTransport to spawn and communicate with a local server process via stdin/stdout. ```typescript import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'; const transport = new StdioClientTransport({ command: 'node', args: ['server.js'], env: { NODE_ENV: 'production' }, cwd: '/path/to/server' }); const client = new Client({ name: 'my-client', version: '1.0.0' }); await client.connect(transport); // connect() calls transport.start() automatically, spawning the child process ``` -------------------------------- ### Register a binary resource Source: https://ts.sdk.modelcontextprotocol.io/server.html Register a resource that returns binary data using base64 encoding. ```typescript server.registerResource('logo', 'images://logo.png', { title: 'Logo', mimeType: 'image/png' }, async uri => ({ contents: [{ uri: uri.href, blob: logoPngBase64 }] })); ``` -------------------------------- ### registerToolTask Source: https://ts.sdk.modelcontextprotocol.io/api/experimental.html Registers a new tool that supports task-based execution. This allows for long-running operations that can be managed via task lifecycle methods. ```APIDOC ## registerToolTask(name, toolDefinition, handler) ### Description Registers a tool with task support. The handler provides methods for creating, retrieving, and getting results for tasks. ### Parameters - **name** (string) - The unique name of the tool. - **toolDefinition** (object) - Configuration including description, inputSchema, and execution settings. - **handler** (object) - Implementation of `createTask`, `getTask`, and `getTaskResult` methods. ### Example ```typescript server.experimental.tasks.registerToolTask('long-computation', { description: 'Performs a long computation', inputSchema: { input: z.string() }, execution: { taskSupport: 'required' } }, { createTask: async (args, extra) => { const task = await extra.taskStore.createTask({ ttl: 300000 }); startBackgroundWork(task.taskId, args); return { task }; }, getTask: async (args, extra) => { return extra.taskStore.getTask(extra.taskId); }, getTaskResult: async (args, extra) => { return extra.taskStore.getTaskResult(extra.taskId); } }); ``` ``` -------------------------------- ### Register a text resource Source: https://ts.sdk.modelcontextprotocol.io/server.html Register a static resource that provides text data to clients. ```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' }] }) ); ``` -------------------------------- ### server.experimental.tasks.elicitInputStream Source: https://ts.sdk.modelcontextprotocol.io/api/experimental.html Initiates an elicitation request to the user, optionally using task-augmented execution for long-running processes. ```APIDOC ## server.experimental.tasks.elicitInputStream ### Description Initiates an elicitation request, such as prompting a user to navigate to a URL for authentication. If the task parameter is provided, the request is executed in a task-augmented mode, returning a task result immediately. ### Parameters - **params** (object) - Required - The elicitation request parameters. - **elicitationId** (string) - Required - Unique ID for the elicitation. - **message** (string) - Required - Explanation for the user. - **mode** ("url") - Required - The mode of elicitation. - **url** (string) - Required - The URL for user navigation. - **task** (object) - Optional - Task augmentation settings. - **ttl** (number) - Optional - Time-to-live for the task. - **options** (RequestOptions) - Optional - Additional request options. ### Returns - **AsyncGenerator** - Yields ResponseMessage objects containing the action (cancel, accept, decline) and optional content. ### Example ```typescript const stream = server.experimental.tasks.elicitInputStream({ mode: 'url', message: 'Please authenticate', elicitationId: 'auth-123', url: 'https://example.com/auth' }, { task: { ttl: 300000 } }); ``` ``` -------------------------------- ### Inspect Negotiated Protocol Version Source: https://ts.sdk.modelcontextprotocol.io/protocol.html Retrieve the negotiated protocol version and server capabilities after connection. ```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 }, ... } ``` -------------------------------- ### Pagination Source: https://ts.sdk.modelcontextprotocol.io/protocol.html Supports cursor-based pagination for list methods. ```APIDOC ## Pagination ### Description List methods (listTools, listPrompts, listResources, listResourceTemplates) support cursor-based pagination. Use the nextCursor from a response to fetch subsequent pages. ### Parameters - **cursor** (string) - Optional - The cursor string returned from the previous page response. ``` -------------------------------- ### assertToolsCallTaskCapability() Source: https://ts.sdk.modelcontextprotocol.io/api/experimental.html Asserts that task creation is supported for tools/call. ```APIDOC ## assertToolsCallTaskCapability(requests, method, entityName) ### Description Asserts that task creation is supported for tools/call. Used by Client.assertTaskCapability and Server.assertTaskHandlerCapability. ### Parameters - **requests** (TaskRequestsCapability | undefined) - The task requests capability object - **method** (string) - The method being checked - **entityName** ("Server" | "Client") - 'Server' or 'Client' for error messages ### Returns - **void** ### Throws - Error if the capability is not supported ``` -------------------------------- ### assertClientRequestTaskCapability() Source: https://ts.sdk.modelcontextprotocol.io/api/experimental.html Asserts that task creation is supported for sampling/createMessage or elicitation/create. ```APIDOC ## assertClientRequestTaskCapability(requests, method, entityName) ### Description Asserts that task creation is supported for sampling/createMessage or elicitation/create. Used by Server.assertTaskCapability and Client.assertTaskHandlerCapability. ### Parameters - **requests** (TaskRequestsCapability | undefined) - The task requests capability object - **method** (string) - The method being checked - **entityName** ("Server" | "Client") - 'Server' or 'Client' for error messages ### Returns - **void** ### Throws - Error if the capability is not supported ``` -------------------------------- ### Handle resource subscriptions Source: https://ts.sdk.modelcontextprotocol.io/server.html Register handlers for subscription and unsubscription requests to track client interest in resources. ```typescript import { SubscribeRequestSchema, UnsubscribeRequestSchema } from '@modelcontextprotocol/sdk/types.js'; const subscriptions = new Set(); server.server.setRequestHandler(SubscribeRequestSchema, async request => { subscriptions.add(request.params.uri); return {}; }); server.server.setRequestHandler(UnsubscribeRequestSchema, async request => { subscriptions.delete(request.params.uri); return {}; }); ``` -------------------------------- ### callTool() with Progress Source: https://ts.sdk.modelcontextprotocol.io/protocol.html Executes a tool and handles progress notifications via an onprogress callback. ```APIDOC ## callTool() ### Description Executes a tool and optionally tracks progress using the onprogress callback. ### Parameters - **onprogress** (function) - Optional - Callback function to handle progress updates containing progress, total, and message fields. - **timeout** (number) - Optional - Timeout for the tool call. - **resetTimeoutOnProgress** (boolean) - Optional - Whether to reset the timeout when progress is received. ``` -------------------------------- ### mergeCapabilities() Source: https://ts.sdk.modelcontextprotocol.io/api/shared/protocol.html Merges base server capabilities with additional capabilities, useful for configuring client-server interactions. ```APIDOC ## mergeCapabilities(base, additional) ### Description Merges a base set of server capabilities with additional capabilities. This is used to combine capability definitions when initializing or updating connections. ### Parameters - **base** (object) - Required - The base server capabilities object. - **additional** (Partial) - Required - The additional capabilities to merge into the base. ### Returns - **object** - The merged capabilities object containing combined completions, experimental, extensions, logging, prompts, resources, tasks, and tools configurations. ``` -------------------------------- ### DEFAULT_NEGOTIATED_PROTOCOL_VERSION Constant Source: https://ts.sdk.modelcontextprotocol.io/api/types.html The default protocol version string used for negotiation. ```typescript const DEFAULT_NEGOTIATED_PROTOCOL_VERSION : "2025-03-26" = '2025-03-26' ``` -------------------------------- ### Register a prompt with image content Source: https://ts.sdk.modelcontextprotocol.io/server.html Includes image data in the prompt message using base64 encoding. ```typescript server.registerPrompt( 'analyze-image', { title: 'Analyze Image', description: 'Analyze an image', argsSchema: { imageBase64: z.string() } }, ({ imageBase64 }) => ({ messages: [ { role: 'user', content: { type: 'image', data: imageBase64, mimeType: 'image/png' } } ] }) ); ``` -------------------------------- ### Initialize Stdio Transport Source: https://ts.sdk.modelcontextprotocol.io/server.html Configures an MCP server to communicate over stdin/stdout for local child process integrations. ```typescript import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; const server = new McpServer({ name: 'my-server', version: '1.0.0' }); // ... register tools, resources, prompts ... const transport = new StdioServerTransport(); await server.connect(transport); ``` -------------------------------- ### Define Custom Client Types Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Extend base schemas and create a typed client instance to support custom request, notification, and result types. ```typescript // Custom schemas const CustomRequestSchema = RequestSchema.extend({...}) const CustomNotificationSchema = NotificationSchema.extend({...}) const CustomResultSchema = ResultSchema.extend({...}) // Type aliases type CustomRequest = z.infer type CustomNotification = z.infer type CustomResult = z.infer // Create typed client const client = new Client({ name: "CustomClient", version: "1.0.0" }) ``` -------------------------------- ### Register a dynamic resource template Source: https://ts.sdk.modelcontextprotocol.io/server.html Use ResourceTemplate to handle dynamic URI patterns with parameters. ```typescript import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'; server.registerResource('user-profile', new ResourceTemplate('users://{userId}/profile', { list: undefined }), { title: 'User Profile', mimeType: 'application/json' }, async (uri, { userId }) => ({ contents: [ { uri: uri.href, text: JSON.stringify(await getUser(userId)) } ] })); ``` -------------------------------- ### ping() Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Sends a ping request to the server to check connectivity. ```APIDOC ## ping(options?) ### Description Sends a ping request to the server to verify the connection is active. ### Parameters - **options** (RequestOptions) - Optional request configuration. ### Returns - **Promise** (object) - A promise resolving to an object containing optional metadata. ``` -------------------------------- ### createTask(taskParams, requestId, request, sessionId?) Source: https://ts.sdk.modelcontextprotocol.io/api/experimental.html Creates a new task with the given creation parameters and original request. Returns the created task object containing status, timestamps, and TTL information. ```APIDOC ## createTask(taskParams, requestId, request, sessionId?) ### Description Creates a new task with the given creation parameters and original request. The implementation generates a unique taskId and createdAt timestamp. ### Parameters - **taskParams** (CreateTaskOptions) - Required - The task creation parameters (ttl, pollInterval). - **requestId** (RequestId) - Required - The JSON-RPC request ID. - **request** (object) - Required - The original request that triggered task creation. - **sessionId** (string) - Optional - Session ID for binding the task to a specific session. ### Returns - **Promise** - The created task object containing taskId, status, createdAt, lastUpdatedAt, pollInterval, statusMessage, and ttl. ``` -------------------------------- ### request() Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Sends a request to the server and waits for a response. This should not be used for notifications. ```APIDOC ## request(request, resultSchema, options?) ### Description Sends a request and waits for a response. Do not use this method to emit notifications; use notification() instead. ### Parameters - **request** (RequestT | ClientRequest) - Required - The request object to send. - **resultSchema** (AnySchema) - Required - The schema to validate the result against. - **options** (RequestOptions) - Optional - Additional request options. ``` -------------------------------- ### Register root handlers for filesystem access Source: https://ts.sdk.modelcontextprotocol.io/client.html Declare the roots capability and provide a handler to expose filesystem locations to the server. ```typescript import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { ListRootsRequestSchema } from '@modelcontextprotocol/sdk/types.js'; const client = new Client({ name: 'my-client', version: '1.0.0' }, { capabilities: { roots: { listChanged: true } } }); client.setRequestHandler(ListRootsRequestSchema, async () => { return { roots: [ { uri: 'file:///home/user/project', name: 'My Project' }, { uri: 'file:///home/user/data', name: 'Data Directory' } ] }; }); ``` -------------------------------- ### createTask(taskParams, requestId, request, _sessionId?) Source: https://ts.sdk.modelcontextprotocol.io/api/experimental.html Creates a new task with the given creation parameters and original request. The implementation generates a unique taskId and createdAt timestamp. ```APIDOC ## createTask(taskParams, requestId, request, _sessionId?) ### Description Creates a new task with the given creation parameters and original request. The implementation must generate a unique taskId and createdAt timestamp. ### Parameters - **taskParams** (CreateTaskOptions) - Required - The task creation parameters from the request (ttl, pollInterval). - **requestId** (RequestId) - Required - The JSON-RPC request ID. - **request** (object) - Required - The original request that triggered task creation. - **_sessionId** (string) - Optional - The session identifier. ### Returns - **Promise** (object) - The created task object containing taskId, status, createdAt, lastUpdatedAt, ttl, pollInterval, and statusMessage. ``` -------------------------------- ### Register a prompt with embedded resources Source: https://ts.sdk.modelcontextprotocol.io/server.html Embeds resource content directly into the prompt message. ```typescript server.registerPrompt( 'summarize-doc', { title: 'Summarize Document', description: 'Summarize a document resource' }, () => ({ messages: [ { role: 'user', content: { type: 'resource', resource: { uri: 'docs://readme', mimeType: 'text/plain', text: 'Document content here...' } } } ] }) ); ``` -------------------------------- ### ModelHintSchema Source: https://ts.sdk.modelcontextprotocol.io/api/types.html Schema for providing hints during model selection. ```typescript const ModelHintSchema : ZodObject<{ name: ZodOptional; }, $strip> ``` -------------------------------- ### createMessage(params, options?) Source: https://ts.sdk.modelcontextprotocol.io/api/server.html The createMessage method is used to initiate or continue a message exchange within the Model Context Protocol server. ```APIDOC ## createMessage(params, options?) ### Description Initiates or continues a message exchange within the MCP server. This method returns a Promise that resolves to the message response. ### Signature `createMessage(params: object, options?: object): Promise` ### Parameters - **params** (object) - Required - The parameters required to create the message. - **options** (object) - Optional - Additional configuration options for the request. ``` -------------------------------- ### getSupportedElicitationModes(capabilities) Source: https://ts.sdk.modelcontextprotocol.io/api/client.html Determines which elicitation modes (form or URL) are supported based on the provided client capabilities. ```APIDOC ## getSupportedElicitationModes(capabilities) ### Description Evaluates client capabilities to determine supported elicitation modes. Form mode is supported by default if the capability object is empty, while URL mode requires explicit declaration. ### Parameters - **capabilities** (object) - Required - The client's elicitation capabilities. ### Returns - **object** - An object containing boolean flags: - **supportsFormMode** (boolean) - **supportsUrlMode** (boolean) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.