@modelcontextprotocol/sdk
Advanced tools
Comparing version
@@ -8,3 +8,3 @@ import { Protocol, ProtocolOptions, RequestOptions } from "../shared/protocol.js"; | ||
*/ | ||
capabilities: ClientCapabilities; | ||
capabilities?: ClientCapabilities; | ||
}; | ||
@@ -44,3 +44,9 @@ /** | ||
*/ | ||
constructor(_clientInfo: Implementation, options: ClientOptions); | ||
constructor(_clientInfo: Implementation, options?: ClientOptions); | ||
/** | ||
* Registers new capabilities. This can only be called before connecting to a transport. | ||
* | ||
* The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). | ||
*/ | ||
registerCapabilities(capabilities: ClientCapabilities): void; | ||
protected assertCapability(capability: keyof ServerCapabilities, method: string): void; | ||
@@ -47,0 +53,0 @@ connect(transport: Transport): Promise<void>; |
@@ -36,6 +36,18 @@ "use strict"; | ||
constructor(_clientInfo, options) { | ||
var _a; | ||
super(options); | ||
this._clientInfo = _clientInfo; | ||
this._capabilities = options.capabilities; | ||
this._capabilities = (_a = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a !== void 0 ? _a : {}; | ||
} | ||
/** | ||
* Registers new capabilities. This can only be called before connecting to a transport. | ||
* | ||
* The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). | ||
*/ | ||
registerCapabilities(capabilities) { | ||
if (this.transport) { | ||
throw new Error("Cannot register capabilities after connecting to transport"); | ||
} | ||
this._capabilities = (0, protocol_js_1.mergeCapabilities)(this._capabilities, capabilities); | ||
} | ||
assertCapability(capability, method) { | ||
@@ -42,0 +54,0 @@ var _a; |
@@ -7,3 +7,3 @@ import { Protocol, ProtocolOptions, RequestOptions } from "../shared/protocol.js"; | ||
*/ | ||
capabilities: ServerCapabilities; | ||
capabilities?: ServerCapabilities; | ||
/** | ||
@@ -52,3 +52,9 @@ * Optional instructions describing how to use the server and its features. | ||
*/ | ||
constructor(_serverInfo: Implementation, options: ServerOptions); | ||
constructor(_serverInfo: Implementation, options?: ServerOptions); | ||
/** | ||
* Registers new capabilities. This can only be called before connecting to a transport. | ||
* | ||
* The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). | ||
*/ | ||
registerCapabilities(capabilities: ServerCapabilities): void; | ||
protected assertCapabilityForMethod(method: RequestT["method"]): void; | ||
@@ -55,0 +61,0 @@ protected assertNotificationCapability(method: (ServerNotification | NotificationT)["method"]): void; |
@@ -36,9 +36,21 @@ "use strict"; | ||
constructor(_serverInfo, options) { | ||
var _a; | ||
super(options); | ||
this._serverInfo = _serverInfo; | ||
this._capabilities = options.capabilities; | ||
this._instructions = options.instructions; | ||
this._capabilities = (_a = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a !== void 0 ? _a : {}; | ||
this._instructions = options === null || options === void 0 ? void 0 : options.instructions; | ||
this.setRequestHandler(types_js_1.InitializeRequestSchema, (request) => this._oninitialize(request)); | ||
this.setNotificationHandler(types_js_1.InitializedNotificationSchema, () => { var _a; return (_a = this.oninitialized) === null || _a === void 0 ? void 0 : _a.call(this); }); | ||
} | ||
/** | ||
* Registers new capabilities. This can only be called before connecting to a transport. | ||
* | ||
* The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). | ||
*/ | ||
registerCapabilities(capabilities) { | ||
if (this.transport) { | ||
throw new Error("Cannot register capabilities after connecting to transport"); | ||
} | ||
this._capabilities = (0, protocol_js_1.mergeCapabilities)(this._capabilities, capabilities); | ||
} | ||
assertCapabilityForMethod(method) { | ||
@@ -45,0 +57,0 @@ var _a, _b; |
import { ZodLiteral, ZodObject, ZodType, z } from "zod"; | ||
import { Notification, Progress, Request, Result } from "../types.js"; | ||
import { ClientCapabilities, Notification, Progress, Request, Result, ServerCapabilities } from "../types.js"; | ||
import { Transport } from "./transport.js"; | ||
@@ -145,2 +145,6 @@ /** | ||
/** | ||
* Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. | ||
*/ | ||
assertCanSetRequestHandler(method: string): void; | ||
/** | ||
* Registers a handler to invoke when this protocol object receives a notification with the given method. | ||
@@ -158,2 +162,3 @@ * | ||
} | ||
export declare function mergeCapabilities<T extends ServerCapabilities | ClientCapabilities>(base: T, additional: T): T; | ||
//# sourceMappingURL=protocol.d.ts.map |
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.Protocol = exports.DEFAULT_REQUEST_TIMEOUT_MSEC = void 0; | ||
exports.mergeCapabilities = mergeCapabilities; | ||
const types_js_1 = require("../types.js"); | ||
@@ -286,2 +287,10 @@ /** | ||
/** | ||
* Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. | ||
*/ | ||
assertCanSetRequestHandler(method) { | ||
if (this._requestHandlers.has(method)) { | ||
throw new Error(`A request handler for ${method} already exists, which would be overridden`); | ||
} | ||
} | ||
/** | ||
* Registers a handler to invoke when this protocol object receives a notification with the given method. | ||
@@ -302,2 +311,13 @@ * | ||
exports.Protocol = Protocol; | ||
function mergeCapabilities(base, additional) { | ||
return Object.entries(additional).reduce((acc, [key, value]) => { | ||
if (value && typeof value === "object") { | ||
acc[key] = acc[key] ? { ...acc[key], ...value } : value; | ||
} | ||
else { | ||
acc[key] = value; | ||
} | ||
return acc; | ||
}, { ...base }); | ||
} | ||
//# sourceMappingURL=protocol.js.map |
@@ -8,3 +8,3 @@ import { Protocol, ProtocolOptions, RequestOptions } from "../shared/protocol.js"; | ||
*/ | ||
capabilities: ClientCapabilities; | ||
capabilities?: ClientCapabilities; | ||
}; | ||
@@ -44,3 +44,9 @@ /** | ||
*/ | ||
constructor(_clientInfo: Implementation, options: ClientOptions); | ||
constructor(_clientInfo: Implementation, options?: ClientOptions); | ||
/** | ||
* Registers new capabilities. This can only be called before connecting to a transport. | ||
* | ||
* The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). | ||
*/ | ||
registerCapabilities(capabilities: ClientCapabilities): void; | ||
protected assertCapability(capability: keyof ServerCapabilities, method: string): void; | ||
@@ -47,0 +53,0 @@ connect(transport: Transport): Promise<void>; |
@@ -1,2 +0,2 @@ | ||
import { Protocol, } from "../shared/protocol.js"; | ||
import { mergeCapabilities, Protocol, } from "../shared/protocol.js"; | ||
import { CallToolResultSchema, CompleteResultSchema, EmptyResultSchema, GetPromptResultSchema, InitializeResultSchema, LATEST_PROTOCOL_VERSION, ListPromptsResultSchema, ListResourcesResultSchema, ListResourceTemplatesResultSchema, ListToolsResultSchema, ReadResourceResultSchema, SUPPORTED_PROTOCOL_VERSIONS, } from "../types.js"; | ||
@@ -33,6 +33,18 @@ /** | ||
constructor(_clientInfo, options) { | ||
var _a; | ||
super(options); | ||
this._clientInfo = _clientInfo; | ||
this._capabilities = options.capabilities; | ||
this._capabilities = (_a = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a !== void 0 ? _a : {}; | ||
} | ||
/** | ||
* Registers new capabilities. This can only be called before connecting to a transport. | ||
* | ||
* The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). | ||
*/ | ||
registerCapabilities(capabilities) { | ||
if (this.transport) { | ||
throw new Error("Cannot register capabilities after connecting to transport"); | ||
} | ||
this._capabilities = mergeCapabilities(this._capabilities, capabilities); | ||
} | ||
assertCapability(capability, method) { | ||
@@ -39,0 +51,0 @@ var _a; |
@@ -7,3 +7,3 @@ import { Protocol, ProtocolOptions, RequestOptions } from "../shared/protocol.js"; | ||
*/ | ||
capabilities: ServerCapabilities; | ||
capabilities?: ServerCapabilities; | ||
/** | ||
@@ -52,3 +52,9 @@ * Optional instructions describing how to use the server and its features. | ||
*/ | ||
constructor(_serverInfo: Implementation, options: ServerOptions); | ||
constructor(_serverInfo: Implementation, options?: ServerOptions); | ||
/** | ||
* Registers new capabilities. This can only be called before connecting to a transport. | ||
* | ||
* The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). | ||
*/ | ||
registerCapabilities(capabilities: ServerCapabilities): void; | ||
protected assertCapabilityForMethod(method: RequestT["method"]): void; | ||
@@ -55,0 +61,0 @@ protected assertNotificationCapability(method: (ServerNotification | NotificationT)["method"]): void; |
@@ -1,2 +0,2 @@ | ||
import { Protocol, } from "../shared/protocol.js"; | ||
import { mergeCapabilities, Protocol, } from "../shared/protocol.js"; | ||
import { CreateMessageResultSchema, EmptyResultSchema, InitializedNotificationSchema, InitializeRequestSchema, LATEST_PROTOCOL_VERSION, ListRootsResultSchema, SUPPORTED_PROTOCOL_VERSIONS, } from "../types.js"; | ||
@@ -33,9 +33,21 @@ /** | ||
constructor(_serverInfo, options) { | ||
var _a; | ||
super(options); | ||
this._serverInfo = _serverInfo; | ||
this._capabilities = options.capabilities; | ||
this._instructions = options.instructions; | ||
this._capabilities = (_a = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a !== void 0 ? _a : {}; | ||
this._instructions = options === null || options === void 0 ? void 0 : options.instructions; | ||
this.setRequestHandler(InitializeRequestSchema, (request) => this._oninitialize(request)); | ||
this.setNotificationHandler(InitializedNotificationSchema, () => { var _a; return (_a = this.oninitialized) === null || _a === void 0 ? void 0 : _a.call(this); }); | ||
} | ||
/** | ||
* Registers new capabilities. This can only be called before connecting to a transport. | ||
* | ||
* The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). | ||
*/ | ||
registerCapabilities(capabilities) { | ||
if (this.transport) { | ||
throw new Error("Cannot register capabilities after connecting to transport"); | ||
} | ||
this._capabilities = mergeCapabilities(this._capabilities, capabilities); | ||
} | ||
assertCapabilityForMethod(method) { | ||
@@ -42,0 +54,0 @@ var _a, _b; |
import { ZodLiteral, ZodObject, ZodType, z } from "zod"; | ||
import { Notification, Progress, Request, Result } from "../types.js"; | ||
import { ClientCapabilities, Notification, Progress, Request, Result, ServerCapabilities } from "../types.js"; | ||
import { Transport } from "./transport.js"; | ||
@@ -145,2 +145,6 @@ /** | ||
/** | ||
* Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. | ||
*/ | ||
assertCanSetRequestHandler(method: string): void; | ||
/** | ||
* Registers a handler to invoke when this protocol object receives a notification with the given method. | ||
@@ -158,2 +162,3 @@ * | ||
} | ||
export declare function mergeCapabilities<T extends ServerCapabilities | ClientCapabilities>(base: T, additional: T): T; | ||
//# sourceMappingURL=protocol.d.ts.map |
@@ -283,2 +283,10 @@ import { CancelledNotificationSchema, ErrorCode, McpError, PingRequestSchema, ProgressNotificationSchema, } from "../types.js"; | ||
/** | ||
* Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. | ||
*/ | ||
assertCanSetRequestHandler(method) { | ||
if (this._requestHandlers.has(method)) { | ||
throw new Error(`A request handler for ${method} already exists, which would be overridden`); | ||
} | ||
} | ||
/** | ||
* Registers a handler to invoke when this protocol object receives a notification with the given method. | ||
@@ -298,2 +306,13 @@ * | ||
} | ||
export function mergeCapabilities(base, additional) { | ||
return Object.entries(additional).reduce((acc, [key, value]) => { | ||
if (value && typeof value === "object") { | ||
acc[key] = acc[key] ? { ...acc[key], ...value } : value; | ||
} | ||
else { | ||
acc[key] = value; | ||
} | ||
return acc; | ||
}, { ...base }); | ||
} | ||
//# sourceMappingURL=protocol.js.map |
{ | ||
"name": "@modelcontextprotocol/sdk", | ||
"version": "1.2.0", | ||
"version": "1.3.0", | ||
"description": "Model Context Protocol implementation for TypeScript", | ||
@@ -51,3 +51,4 @@ "license": "MIT", | ||
"raw-body": "^3.0.0", | ||
"zod": "^3.23.8" | ||
"zod": "^3.23.8", | ||
"zod-to-json-schema": "^3.24.1" | ||
}, | ||
@@ -54,0 +55,0 @@ "devDependencies": { |
416
README.md
@@ -1,4 +0,24 @@ | ||
# MCP TypeScript SDK  | ||
# MCP TypeScript SDK   | ||
TypeScript implementation of the [Model Context Protocol](https://modelcontextprotocol.io) (MCP), providing both client and server capabilities for integrating with LLM surfaces. | ||
## Table of Contents | ||
- [Overview](#overview) | ||
- [Installation](#installation) | ||
- [Quickstart](#quickstart) | ||
- [What is MCP?](#what-is-mcp) | ||
- [Core Concepts](#core-concepts) | ||
- [Server](#server) | ||
- [Resources](#resources) | ||
- [Tools](#tools) | ||
- [Prompts](#prompts) | ||
- [Running Your Server](#running-your-server) | ||
- [Development Mode](#development-mode) | ||
- [Claude Desktop Integration](#claude-desktop-integration) | ||
- [Direct Execution](#direct-execution) | ||
- [Examples](#examples) | ||
- [Echo Server](#echo-server) | ||
- [SQLite Explorer](#sqlite-explorer) | ||
- [Advanced Usage](#advanced-usage) | ||
- [Low-Level Server](#low-level-server) | ||
- [Writing MCP Clients](#writing-mcp-clients) | ||
- [Server Capabilities](#server-capabilities) | ||
@@ -22,87 +42,318 @@ ## Overview | ||
### Creating a Client | ||
Let's create a simple MCP server that exposes a calculator tool and some data: | ||
```typescript | ||
import { Client } from "@modelcontextprotocol/sdk/client/index.js"; | ||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; | ||
import { | ||
ListResourcesRequestSchema, | ||
ReadResourceRequestSchema, | ||
} from "@modelcontextprotocol/sdk/types.js"; | ||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; | ||
import { z } from "zod"; | ||
const transport = new StdioClientTransport({ | ||
command: "path/to/server", | ||
// Create an MCP server | ||
const server = new McpServer({ | ||
name: "Demo", | ||
version: "1.0.0" | ||
}); | ||
const client = new Client({ | ||
name: "example-client", | ||
version: "1.0.0", | ||
}, { | ||
capabilities: {} | ||
// Add an addition tool | ||
server.tool("add", | ||
{ a: z.number(), b: z.number() }, | ||
async ({ a, b }) => ({ | ||
content: [{ type: "text", text: String(a + b) }] | ||
}) | ||
); | ||
// Add a dynamic greeting resource | ||
server.resource( | ||
"greeting", | ||
"greeting://{name}", | ||
async (uri, { name }) => ({ | ||
contents: [{ | ||
uri: uri.href, | ||
text: `Hello, ${name}!` | ||
}] | ||
}) | ||
); | ||
``` | ||
## What is MCP? | ||
The [Model Context Protocol (MCP)](https://modelcontextprotocol.io) lets you build servers that expose data and functionality to LLM applications in a secure, standardized way. Think of it like a web API, but specifically designed for LLM interactions. MCP servers can: | ||
- Expose data through **Resources** (think of these sort of like GET endpoints; they are used to load information into the LLM's context) | ||
- Provide functionality through **Tools** (sort of like POST endpoints; they are used to execute code or otherwise produce a side effect) | ||
- Define interaction patterns through **Prompts** (reusable templates for LLM interactions) | ||
- And more! | ||
## Core Concepts | ||
### Server | ||
The McpServer is your core interface to the MCP protocol. It handles connection management, protocol compliance, and message routing: | ||
```typescript | ||
const server = new McpServer({ | ||
name: "My App", | ||
version: "1.0.0" | ||
}); | ||
``` | ||
await client.connect(transport); | ||
### Resources | ||
// List available resources | ||
const resources = await client.request( | ||
{ method: "resources/list" }, | ||
ListResourcesResultSchema | ||
Resources are how you expose data to LLMs. They're similar to GET endpoints in a REST API - they provide data but shouldn't perform significant computation or have side effects: | ||
```typescript | ||
// Static resource | ||
server.resource( | ||
"config", | ||
"config://app", | ||
async (uri) => ({ | ||
contents: [{ | ||
uri: uri.href, | ||
text: "App configuration here" | ||
}] | ||
}) | ||
); | ||
// Read a specific resource | ||
const resourceContent = await client.request( | ||
// Dynamic resource with parameters | ||
server.resource( | ||
"user-profile", | ||
"users://{userId}/profile", | ||
async (uri, { userId }) => ({ | ||
contents: [{ | ||
uri: uri.href, | ||
text: `Profile data for user ${userId}` | ||
}] | ||
}) | ||
); | ||
``` | ||
### Tools | ||
Tools let LLMs take actions through your server. Unlike resources, tools are expected to perform computation and have side effects: | ||
```typescript | ||
// Simple tool with parameters | ||
server.tool( | ||
"calculate-bmi", | ||
{ | ||
method: "resources/read", | ||
params: { | ||
uri: "file:///example.txt" | ||
} | ||
weightKg: z.number(), | ||
heightM: z.number() | ||
}, | ||
ReadResourceResultSchema | ||
async ({ weightKg, heightM }) => ({ | ||
content: [{ | ||
type: "text", | ||
text: String(weightKg / (heightM * heightM)) | ||
}] | ||
}) | ||
); | ||
// Async tool with external API call | ||
server.tool( | ||
"fetch-weather", | ||
{ city: z.string() }, | ||
async ({ city }) => { | ||
const response = await fetch(`https://api.weather.com/${city}`); | ||
const data = await response.text(); | ||
return { | ||
content: [{ type: "text", text: data }] | ||
}; | ||
} | ||
); | ||
``` | ||
### Creating a Server | ||
### Prompts | ||
Prompts are reusable templates that help LLMs interact with your server effectively: | ||
```typescript | ||
server.prompt( | ||
"review-code", | ||
{ code: z.string() }, | ||
({ code }) => ({ | ||
messages: [{ | ||
role: "user", | ||
content: { | ||
type: "text", | ||
text: `Please review this code:\n\n${code}` | ||
} | ||
}] | ||
}) | ||
); | ||
``` | ||
## Examples | ||
### Echo Server | ||
A simple server demonstrating resources, tools, and prompts: | ||
```typescript | ||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; | ||
import { z } from "zod"; | ||
const server = new McpServer({ | ||
name: "Echo", | ||
version: "1.0.0" | ||
}); | ||
server.resource( | ||
"echo", | ||
"echo://{message}", | ||
async (uri, { message }) => ({ | ||
contents: [{ | ||
uri: uri.href, | ||
text: `Resource echo: ${message}` | ||
}] | ||
}) | ||
); | ||
server.tool( | ||
"echo", | ||
{ message: z.string() }, | ||
async ({ message }) => ({ | ||
content: [{ type: "text", text: `Tool echo: ${message}` }] | ||
}) | ||
); | ||
server.prompt( | ||
"echo", | ||
{ message: z.string() }, | ||
({ message }) => ({ | ||
messages: [{ | ||
role: "user", | ||
content: { | ||
type: "text", | ||
text: `Please process this message: ${message}` | ||
} | ||
}] | ||
}) | ||
); | ||
``` | ||
### SQLite Explorer | ||
A more complex example showing database integration: | ||
```typescript | ||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; | ||
import sqlite3 from "sqlite3"; | ||
import { promisify } from "util"; | ||
import { z } from "zod"; | ||
const server = new McpServer({ | ||
name: "SQLite Explorer", | ||
version: "1.0.0" | ||
}); | ||
// Helper to create DB connection | ||
const getDb = () => { | ||
const db = new sqlite3.Database("database.db"); | ||
return { | ||
all: promisify<string, any[]>(db.all.bind(db)), | ||
close: promisify(db.close.bind(db)) | ||
}; | ||
}; | ||
server.resource( | ||
"schema", | ||
"schema://main", | ||
async (uri) => { | ||
const db = getDb(); | ||
try { | ||
const tables = await db.all( | ||
"SELECT sql FROM sqlite_master WHERE type='table'" | ||
); | ||
return { | ||
contents: [{ | ||
uri: uri.href, | ||
text: tables.map((t: {sql: string}) => t.sql).join("\n") | ||
}] | ||
}; | ||
} finally { | ||
await db.close(); | ||
} | ||
} | ||
); | ||
server.tool( | ||
"query", | ||
{ sql: z.string() }, | ||
async ({ sql }) => { | ||
const db = getDb(); | ||
try { | ||
const results = await db.all(sql); | ||
return { | ||
content: [{ | ||
type: "text", | ||
text: JSON.stringify(results, null, 2) | ||
}] | ||
}; | ||
} catch (err: unknown) { | ||
const error = err as Error; | ||
return { | ||
content: [{ | ||
type: "text", | ||
text: `Error: ${error.message}` | ||
}], | ||
isError: true | ||
}; | ||
} finally { | ||
await db.close(); | ||
} | ||
} | ||
); | ||
``` | ||
## Advanced Usage | ||
### Low-Level Server | ||
For more control, you can use the low-level Server class directly: | ||
```typescript | ||
import { Server } from "@modelcontextprotocol/sdk/server/index.js"; | ||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; | ||
import { | ||
ListResourcesRequestSchema, | ||
ReadResourceRequestSchema, | ||
ListPromptsRequestSchema, | ||
GetPromptRequestSchema | ||
} from "@modelcontextprotocol/sdk/types.js"; | ||
const server = new Server({ | ||
name: "example-server", | ||
version: "1.0.0", | ||
}, { | ||
capabilities: { | ||
resources: {} | ||
const server = new Server( | ||
{ | ||
name: "example-server", | ||
version: "1.0.0" | ||
}, | ||
{ | ||
capabilities: { | ||
prompts: {} | ||
} | ||
} | ||
}); | ||
); | ||
server.setRequestHandler(ListResourcesRequestSchema, async () => { | ||
server.setRequestHandler(ListPromptsRequestSchema, async () => { | ||
return { | ||
resources: [ | ||
{ | ||
uri: "file:///example.txt", | ||
name: "Example Resource", | ||
}, | ||
], | ||
prompts: [{ | ||
name: "example-prompt", | ||
description: "An example prompt template", | ||
arguments: [{ | ||
name: "arg1", | ||
description: "Example argument", | ||
required: true | ||
}] | ||
}] | ||
}; | ||
}); | ||
server.setRequestHandler(ReadResourceRequestSchema, async (request) => { | ||
if (request.params.uri === "file:///example.txt") { | ||
return { | ||
contents: [ | ||
{ | ||
uri: "file:///example.txt", | ||
mimeType: "text/plain", | ||
text: "This is the content of the example resource.", | ||
}, | ||
], | ||
}; | ||
} else { | ||
throw new Error("Resource not found"); | ||
server.setRequestHandler(GetPromptRequestSchema, async (request) => { | ||
if (request.params.name !== "example-prompt") { | ||
throw new Error("Unknown prompt"); | ||
} | ||
return { | ||
description: "Example prompt", | ||
messages: [{ | ||
role: "user", | ||
content: { | ||
type: "text", | ||
text: "Example prompt text" | ||
} | ||
}] | ||
}; | ||
}); | ||
@@ -114,2 +365,51 @@ | ||
### Writing MCP Clients | ||
The SDK provides a high-level client interface: | ||
```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"] | ||
}); | ||
const client = new Client( | ||
{ | ||
name: "example-client", | ||
version: "1.0.0" | ||
}, | ||
{ | ||
capabilities: { | ||
prompts: {}, | ||
resources: {}, | ||
tools: {} | ||
} | ||
} | ||
); | ||
await client.connect(transport); | ||
// List prompts | ||
const prompts = await client.listPrompts(); | ||
// Get a prompt | ||
const prompt = await client.getPrompt("example-prompt", { | ||
arg1: "value" | ||
}); | ||
// List resources | ||
const resources = await client.listResources(); | ||
// Read a resource | ||
const resource = await client.readResource("file:///example.txt"); | ||
// Call a tool | ||
const result = await client.callTool("example-tool", { | ||
arg1: "value" | ||
}); | ||
``` | ||
## Documentation | ||
@@ -116,0 +416,0 @@ |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
3340208
4.54%133
22.02%63501
2.98%426
238.1%2
-33.33%4
33.33%+ Added
+ Added