了解MCP如何连接客户端、服务器和LLM
class Protocol<Request, Notification, Result> { // 处理传入请求 setRequestHandler<T>(schema: T, handler: (request: T, extra: RequestHandlerExtra) => Promise<Result>): void // 处理传入通知 setNotificationHandler<T>(schema: T, handler: (notification: T) => Promise<void>): void // 发送请求并等待响应 request<T>(request: Request, schema: T, options?: RequestOptions): Promise<T> // 发送单向通知 notification(notification: Notification): Promise<void> }
Protocol
Client
Server
interface Request { method: string; params?: { ... }; }
interface Result { [key: string]: unknown; }
interface Error { code: number; message: string; data?: unknown; }
interface Notification { method: string; params?: { ... }; }
initialize
initialized
close()
enum ErrorCode { // 标准JSON-RPC错误代码 ParseError = -32700, InvalidRequest = -32600, MethodNotFound = -32601, InvalidParams = -32602, InternalError = -32603 }
import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: { resources: {} } }); // 处理请求 server.setRequestHandler(ListResourcesRequestSchema, async () => { return { resources: [ { uri: "example://resource", name: "Example Resource" } ] }; }); // 连接传输 const transport = new StdioServerTransport(); await server.connect(transport);