跳到主要内容

MCP 服务器构建

收藏0

从零写一个 MCP 服务器:怎么定义工具、选传输方式、处理错误与认证,附 Python 与 Node 两套服务器写法、评估方法和最佳实践。

让 AI 安装

星光尘缘LV2最新版本 0.1.0更新于 2026-11-14下载 0 次

reference/node_mcp_server_v2.md

34.3 KB查看排版效果
1# Node/TypeScript MCP Server Implementation Guide (SDK v2)
2
3This guide covers building MCP servers with **v2 of the MCP TypeScript SDK** (`@modelcontextprotocol/server`), the current stable release. If the project already depends on the v1 package `@modelcontextprotocol/sdk`, use the [v1 guide](./node_mcp_server.md) or migrate first (see [Migrating a v1 Server](#migrating-a-v1-server)).
4
5Code patterns are adapted from the [MCP TypeScript SDK examples](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples). The full v2 documentation index is `https://ts.sdk.modelcontextprotocol.io/v2/llms.txt`; every page is also served as markdown at its `.md` URL.
6
7---
8
9## Quick Reference
10
11### Install
12
13```bash
14npm install @modelcontextprotocol/server zod
15npm install @modelcontextprotocol/express @modelcontextprotocol/node express # Streamable HTTP only
16npm install -D @modelcontextprotocol/client typescript tsx @types/node @types/express
17```
18
19### A Server in One Screen
20
21```typescript
22import { McpServer } from "@modelcontextprotocol/server";
23import { serveStdio } from "@modelcontextprotocol/server/stdio";
24import * as z from "zod/v4";
25
26function createServer(): McpServer {
27 const server = new McpServer({ name: "example-mcp-server", version: "1.0.0" });
28
29 server.registerTool(
30 "example_greet",
31 {
32 title: "Greet",
33 description: "Greet someone by name",
34 inputSchema: z.object({ name: z.string().describe("Who to greet") }),
35 annotations: { readOnlyHint: true }
36 },
37 async ({ name }) => ({ content: [{ type: "text", text: `Hello, ${name}!` }] })
38 );
39
40 return server;
41}
42
43serveStdio(createServer);
44console.error("example-mcp-server running on stdio"); // stderr: stdout carries the protocol
45```
46
47### v1 → v2 at a Glance
48
49Most published examples and training data show v1 code. Translate it before use:
50
51| v1 (`@modelcontextprotocol/sdk`) | v2 |
52|---|---|
53| `import ... from "@modelcontextprotocol/sdk/server/mcp.js"` | `import ... from "@modelcontextprotocol/server"` |
54| `import ... from "@modelcontextprotocol/sdk/server/stdio.js"` | `import ... from "@modelcontextprotocol/server/stdio"` |
55| `zod ^3`, `import { z } from "zod"` | `zod ^4.2.0`, `import * as z from "zod/v4"` |
56| `inputSchema: { q: z.string() }` (raw shape) | `inputSchema: z.object({ q: z.string() })` |
57| `server.tool(...)`, `server.resource(...)`, `server.prompt(...)` | Removed: use `registerTool`, `registerResource`, `registerPrompt` |
58| `new StdioServerTransport()` + `server.connect(transport)` | `serveStdio(createServer)` (`StdioServerTransport` from `@modelcontextprotocol/server/stdio` also still works) |
59| Per-request `StreamableHTTPServerTransport` + `express.json()` | `createMcpHandler(createServer)` + `createMcpExpressApp()` + `toNodeHandler()` |
60| Handler `extra.signal`, `extra.authInfo` | Handler `ctx.mcpReq.signal`, `ctx.http?.authInfo` |
61| `McpError`, `ErrorCode` | `ProtocolError`, `ProtocolErrorCode` |
62| Node.js 18+ | Node.js 20+ |
63
64Do not use imports from `@modelcontextprotocol/sdk/...`, raw-shape schemas, Zod 3 or `zod/v3`, hand-wired `StreamableHTTPServerTransport` instances, or a shared `McpServer` instance returned from the factory (one created at module scope and reused across HTTP requests) in a v2 server.
65
66---
67
68## Project Setup
69
70```
71{service}-mcp-server/
72├── package.json
73├── tsconfig.json
74├── README.md
75├── src/
76│ ├── index.ts # createServer() factory and transport selection
77│ ├── api.ts # Upstream API client and error messages
78│ ├── tools/ # One registerXxxTools(server) function per domain
79│ └── constants.ts # API_BASE_URL, CHARACTER_LIMIT
80├── scripts/
81│ └── smoke.ts # Self-check client (see Verify Your Server)
82└── dist/ # Build output (entry point: dist/index.js)
83```
84
85Name the package and server `{service}-mcp-server` (lowercase, hyphens, no version numbers), e.g. `github-mcp-server`, `jira-mcp-server`.
86
87### package.json
88
89```json
90{
91 "name": "{service}-mcp-server",
92 "version": "1.0.0",
93 "description": "MCP server for the {Service} API",
94 "type": "module",
95 "bin": { "{service}-mcp-server": "dist/index.js" },
96 "files": ["dist"],
97 "scripts": {
98 "build": "tsc",
99 "start": "node dist/index.js",
100 "dev": "tsx watch src/index.ts",
101 "smoke": "tsx scripts/smoke.ts"
102 },
103 "engines": { "node": ">=20.3" },
104 "dependencies": {
105 "@modelcontextprotocol/express": "^2.0.2",
106 "@modelcontextprotocol/node": "^2.1.1",
107 "@modelcontextprotocol/server": "^2.3.1",
108 "express": "^5.1.0",
109 "zod": "^4.2.0"
110 },
111 "devDependencies": {
112 "@modelcontextprotocol/client": "^2.3.1",
113 "@types/express": "^5.0.0",
114 "@types/node": "^24.0.0",
115 "tsx": "^4.19.2",
116 "typescript": "^5.9.3"
117 }
118}
119```
120
121- `bin` plus the `#!/usr/bin/env node` line at the top of `src/index.ts` let hosts launch the server with `npx -y {service}-mcp-server`
122- A stdio-only server can drop `express`, `@types/express`, and the two adapter packages
123- Keep `zod` at `^4.2.0` or later: v2 does not support Zod 3, and Zod 4.0–4.1 schemas fail to type-check in `registerTool`. If the server runs anyway (`tsx` skips type-checking), the SDK logs a fallback warning and, before 4.1.13, drops `.describe()` text from the advertised schemas
124
125### tsconfig.json
126
127```json
128{
129 "compilerOptions": {
130 "target": "ES2022",
131 "module": "Node16",
132 "moduleResolution": "Node16",
133 "lib": ["ES2022"],
134 "outDir": "./dist",
135 "rootDir": "./src",
136 "strict": true,
137 "esModuleInterop": true,
138 "skipLibCheck": true,
139 "forceConsistentCasingInFileNames": true,
140 "declaration": true,
141 "sourceMap": true
142 },
143 "include": ["src/**/*"]
144}
145```
146
147---
148
149## The Server Factory
150
151Write a `createServer()` function that builds a fresh `McpServer` and registers every tool, resource, and prompt on it. You never call it yourself: the transport entry points do.
152
153- `serveStdio(createServer)` calls it once for the stdio connection
154- `createMcpHandler(createServer)` calls it once **per HTTP request**, so the HTTP server keeps no state between requests and scales horizontally as-is
155- Register everything inside the factory, never on a shared instance outside it
156- Return a new `McpServer` from every call. A factory that returns one shared instance passes manual tests and the self-check script, because they send one request at a time. A request that arrives while another is being served fails with `-32603` "Internal server error", and the cause goes only to the handler's `onerror` option
157- Keep the factory cheap: create API clients, connection pools, caches, and configuration once at module scope and close over them
158- Behind `createMcpHandler`, the factory receives the request context: `createMcpHandler(({ authInfo }) => ...)` builds an instance for one authenticated caller
159
160One file can serve both transports; the [complete example](#complete-example) picks one from the `TRANSPORT` environment variable.
161
162## Calling the Upstream API
163
164Put the upstream API client at module scope, in one `apiRequest` helper that every tool calls. Node 20+ has `fetch` built in. The core of the [complete example](#complete-example)'s helper:
165
166```typescript
167const response = await fetch(url, {
168 headers: { Authorization: `Bearer ${API_KEY}`, Accept: "application/json" },
169 // Aborts when the client cancels the call, or after 30 seconds
170 signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)])
171});
172if (!response.ok) throw new ApiError(response.status);
173```
174
175- Send whatever the API requires (API key, `User-Agent`, version header) here, in one place
176- Tool handlers pass `ctx.mcpReq.signal`, so a cancelled call also cancels its upstream request
177- Map HTTP statuses and timeouts to messages that say how to recover (`httpErrorMessage` in the complete example): "Rate limit exceeded. Wait a minute before making more requests."
178- `ApiError` takes its message from `httpErrorMessage` and keeps the HTTP status, so a caller can treat a 404 differently from a 401 or a 429
179- Tool handlers can let these errors propagate: the SDK turns anything a tool handler throws into an `isError: true` result whose text is the error's `message`
180
181---
182
183## Designing Tools
184
185### Names and Descriptions
186
187- Use snake_case, action-oriented names with a service prefix: `slack_send_message`, `github_create_issue`, `asana_list_tasks`
188- The `description` is what the model reads to decide when and how to call the tool. Say what it does, what it returns, when to use a sibling tool instead, and give one or two example requests. JSDoc comments are not extracted
189- Give every tool a `title` (display name), `description`, `inputSchema` (if it takes arguments), and `annotations`
190
191### Annotations
192
193Annotations are hints for clients, for example to auto-approve read-only tools or to confirm destructive ones. They never change how the SDK runs the tool.
194
195| Annotation | Set to `true` when the tool... |
196|---|---|
197| `readOnlyHint` | does not modify anything |
198| `destructiveHint` | may delete or overwrite data |
199| `idempotentHint` | can be repeated with the same arguments with no extra effect |
200| `openWorldHint` | talks to an external system (most API tools) |
201
202### Input Schemas
203
204`inputSchema` is a Zod object schema: `z.object({...})`, or `z.strictObject({...})` to reject unknown arguments. From that one schema the SDK derives the JSON Schema clients see, validates arguments before your handler runs, and infers the handler's argument types (no annotation needed).
205
206```typescript
207const SearchInput = z.strictObject({
208 query: z.string().min(2).max(200).describe("Text to match against user names and emails"),
209 limit: z.number().int().min(1).max(100).default(20).describe("Maximum number of users to return"),
210 offset: z.number().int().min(0).default(0).describe("Number of matches to skip, for pagination"),
211 response_format: z.enum(ResponseFormat).default(ResponseFormat.MARKDOWN)
212 .describe("'markdown' for readable text, 'json' for structured data")
213});
214```
215
216- `.describe()` text becomes the argument's JSON Schema `description`, the only documentation the model gets for it
217- Fields with `.default()` are optional for the caller and always present in the handler's arguments
218- Arguments that fail validation never reach the handler; the client gets an `isError: true` result such as `Input validation error: Invalid arguments for tool example_search_users: query: Too small: expected string to have >=2 characters`
219- Zod 4 replaced some v3 APIs: `z.strictObject({...})` instead of `.strict()`, `z.enum(MyTsEnum)` instead of `z.nativeEnum`, and `z.email()` / `z.url()` / `z.uuid()` instead of `z.string().email()` and similar
220
221### Output: Markdown, JSON, and structuredContent
222
223Let the caller choose the format with a `response_format` argument:
224
225- **Markdown** (default): readable text for the model. Headers and lists, human-readable dates, display names with IDs in parentheses, no verbose metadata
226- **JSON**: complete data for programmatic use, with consistent field names
227
228When a result includes `structuredContent`, the spec says it SHOULD also include the same data serialized as JSON in a text block. So:
229
230- In JSON mode, return the data as `structuredContent` and its `JSON.stringify` as the text
231- In Markdown mode, return only the Markdown text
232- Declare `outputSchema` only on tools whose output is always JSON. With an `outputSchema`, every successful result must include matching `structuredContent`, or the SDK replaces it with an output validation error
233- The advertised `outputSchema` disallows extra fields, so build `structuredContent` from the schema, e.g. `UserSchema.parse(raw)`, which also validates the upstream data
234
235### Pagination
236
237List and search tools take `limit` and `offset` and return where the next page starts:
238
239```typescript
240const nextOffset = offset + users.length;
241const hasMore = data.total > nextOffset;
242const page = {
243 total: data.total,
244 count: users.length,
245 offset,
246 users,
247 has_more: hasMore,
248 ...(hasMore ? { next_offset: nextOffset } : {})
249};
250```
251
252In Markdown mode, end the text with how to get more, e.g. `More results: call again with offset=20.`
253
254### Character Limit
255
256Cap responses with a `CHARACTER_LIMIT` (25,000 characters is a good default). Stay under it by returning **fewer items**, never by cutting text: `next_offset` then points at the first item left out, and the JSON text still matches `structuredContent`. Measure the text the tool sends, not an intermediate value: pretty-printing and the page fields count too.
257
258```typescript
259let users = data.users;
260let result = render(users);
261while (users.length > 1 && result.text.length > CHARACTER_LIMIT) {
262 users = users.slice(0, Math.ceil(users.length / 2));
263 result = render(users);
264}
265```
266
267`render(users)` builds the page and its text in the requested format; see the [complete example](#complete-example).
268
269### Errors
270
271MCP has two error channels:
272
273- **Tool errors** are tool results with `isError: true`. The model reads them, so the text should say how to recover. A tool handler produces them by returning `isError: true`, or by throwing: the thrown error's `message` becomes the result text
274- **Protocol errors** are JSON-RPC error responses handled by the client application; the model never sees them. Resource and prompt callbacks have no `isError` channel, so they throw `ProtocolError` (see [Resources and Prompts](#resources-and-prompts))
275
276---
277
278## Complete Example
279
280One file, two tools, both transports. `example_search_users` shows pagination, the character limit, and the two output formats; `example_get_user` shows an `outputSchema`.
281
282```typescript
283#!/usr/bin/env node
284/**
285 * MCP server for the Example API.
286 * Serves stdio by default, Streamable HTTP when TRANSPORT=http.
287 */
288import { createMcpExpressApp } from "@modelcontextprotocol/express";
289import { toNodeHandler } from "@modelcontextprotocol/node";
290import { createMcpHandler, McpServer } from "@modelcontextprotocol/server";
291import { serveStdio } from "@modelcontextprotocol/server/stdio";
292import * as z from "zod/v4";
293
294const API_BASE_URL = "https://api.example.com/v1";
295const API_KEY = process.env.EXAMPLE_API_KEY;
296const CHARACTER_LIMIT = 25_000;
297
298if (!API_KEY) {
299 console.error("EXAMPLE_API_KEY environment variable is required");
300 process.exit(1);
301}
302
303// ---- Upstream API client: module scope, shared by every server instance ----
304
305async function apiRequest<T>(
306 path: string,
307 params: Record<string, string | number>,
308 signal: AbortSignal
309): Promise<T> {
310 const url = new URL(`${API_BASE_URL}/${path}`);
311 for (const [key, value] of Object.entries(params)) url.searchParams.set(key, String(value));
312
313 let response: Response;
314 try {
315 response = await fetch(url, {
316 headers: { Authorization: `Bearer ${API_KEY}`, Accept: "application/json" },
317 // Aborts when the client cancels the call, or after 30 seconds
318 signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)])
319 });
320 } catch (error) {
321 if (error instanceof DOMException && error.name === "TimeoutError") {
322 throw new Error("The Example API did not respond within 30 seconds. Try again, or narrow the query.");
323 }
324 throw error;
325 }
326 if (!response.ok) throw new ApiError(response.status);
327 return (await response.json()) as T;
328}
329
330// Thrown errors reach the model as the tool result's text, so say how to recover
331function httpErrorMessage(status: number): string {
332 switch (status) {
333 case 401:
334 return "The Example API rejected the API key. Check that EXAMPLE_API_KEY is valid.";
335 case 403:
336 return "Permission denied: this API key cannot access that resource.";
337 case 404:
338 return "Not found. Check the ID; example_search_users returns valid user IDs.";
339 case 429:
340 return "Rate limit exceeded. Wait a minute before making more requests.";
341 default:
342 return `The Example API returned HTTP ${status}.`;
343 }
344}
345
346// Keeps the HTTP status so callers can tell a 404 from other failures
347class ApiError extends Error {
348 constructor(readonly status: number) {
349 super(httpErrorMessage(status));
350 }
351}
352
353// ---- Schemas and formatting ----
354
355enum ResponseFormat {
356 MARKDOWN = "markdown",
357 JSON = "json"
358}
359
360const UserSchema = z.object({
361 id: z.string(),
362 name: z.string(),
363 email: z.string(),
364 team: z.string().optional(),
365 active: z.boolean()
366});
367
368type User = z.infer<typeof UserSchema>;
369
370const UserPageSchema = z.object({
371 users: z.array(UserSchema),
372 total: z.number()
373});
374
375function formatUser(user: User): string {
376 const lines = [`## ${user.name} (${user.id})`, `- Email: ${user.email}`];
377 if (user.team) lines.push(`- Team: ${user.team}`);
378 if (!user.active) lines.push("- Inactive");
379 return lines.join("\n");
380}
381
382// ---- Server factory: serveStdio calls it per connection, createMcpHandler per HTTP request ----
383
384function createServer(): McpServer {
385 const server = new McpServer({ name: "example-mcp-server", version: "1.0.0" });
386
387 server.registerTool(
388 "example_search_users",
389 {
390 title: "Search Users",
391 description: `Search Example users by name or email.
392
393Returns one page of matches. When more matches exist, the result says so and gives next_offset; call again with that offset for the next page.
394
395Examples:
396 - "Find people on the marketing team" -> query="marketing"
397 - "Look up [email protected]" -> query="[email protected]"
398Use example_get_user instead when you already have a user ID.`,
399 inputSchema: z.strictObject({
400 query: z.string().min(2).max(200).describe("Text to match against user names and emails"),
401 limit: z.number().int().min(1).max(100).default(20).describe("Maximum number of users to return"),
402 offset: z.number().int().min(0).default(0).describe("Number of matches to skip, for pagination"),
403 response_format: z.enum(ResponseFormat).default(ResponseFormat.MARKDOWN)
404 .describe("'markdown' for readable text, 'json' for structured data")
405 }),
406 annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
407 },
408 async ({ query, limit, offset, response_format }, ctx) => {
409 const raw = await apiRequest<unknown>("users/search", { q: query, limit, offset }, ctx.mcpReq.signal);
410 const data = UserPageSchema.parse(raw); // Validates the upstream data and drops fields outside the schema
411
412 // Builds the page for these users and its text in the requested format
413 const render = (users: User[]) => {
414 const nextOffset = offset + users.length;
415 const hasMore = data.total > nextOffset;
416 const page = {
417 total: data.total,
418 count: users.length,
419 offset,
420 users,
421 has_more: hasMore,
422 ...(hasMore ? { next_offset: nextOffset } : {})
423 };
424 if (response_format === ResponseFormat.JSON) return { page, text: JSON.stringify(page, null, 2) };
425 const lines = [`# Users matching '${query}'`, `Showing ${users.length} of ${data.total}.`, ""];
426 lines.push(users.map(formatUser).join("\n\n"));
427 if (hasMore) lines.push("", `More results: call again with offset=${nextOffset}.`);
428 return { page, text: lines.join("\n") };
429 };
430
431 // Stay under CHARACTER_LIMIT by returning fewer users; next_offset then points at the first one left out
432 let users = data.users;
433 let result = render(users);
434 while (users.length > 1 && result.text.length > CHARACTER_LIMIT) {
435 users = users.slice(0, Math.ceil(users.length / 2));
436 result = render(users);
437 }
438
439 if (response_format === ResponseFormat.JSON) {
440 return { content: [{ type: "text", text: result.text }], structuredContent: result.page };
441 }
442 if (users.length === 0) {
443 return { content: [{ type: "text", text: `No users match '${query}'. Try a shorter or different query.` }] };
444 }
445 return { content: [{ type: "text", text: result.text }] };
446 }
447 );
448
449 server.registerTool(
450 "example_get_user",
451 {
452 title: "Get User",
453 description: "Get one Example user by ID. Use example_search_users to find IDs.",
454 inputSchema: z.strictObject({
455 user_id: z.string().min(1).describe("User ID, e.g. 'U123456789'")
456 }),
457 outputSchema: UserSchema,
458 annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
459 },
460 async ({ user_id }, ctx) => {
461 const raw = await apiRequest<unknown>(`users/${encodeURIComponent(user_id)}`, {}, ctx.mcpReq.signal);
462 const user = UserSchema.parse(raw); // Validates the upstream data and drops fields outside the schema
463 return {
464 content: [{ type: "text", text: JSON.stringify(user, null, 2) }],
465 structuredContent: user
466 };
467 }
468 );
469
470 return server;
471}
472
473// ---- Transport selection ----
474
475if (process.env.TRANSPORT === "http") {
476 const handler = createMcpHandler(createServer);
477 const app = createMcpExpressApp(); // express.json() plus Host/Origin checks for localhost
478 const nodeHandler = toNodeHandler(handler);
479 app.all("/mcp", (req, res) => void nodeHandler(req, res, req.body));
480
481 const port = Number(process.env.PORT ?? 3000);
482 app.listen(port, "127.0.0.1", () => {
483 console.error(`example-mcp-server listening on http://127.0.0.1:${port}/mcp`);
484 });
485} else {
486 serveStdio(createServer);
487 console.error("example-mcp-server running on stdio");
488}
489```
490
491---
492
493## Serving
494
495### stdio (Local Servers)
496
497`serveStdio(createServer)` reads requests on stdin and writes responses on stdout. Never write to stdout yourself: one `console.log` corrupts the JSON-RPC stream. Log with `console.error`.
498
499### Streamable HTTP (Remote Servers)
500
501`createMcpHandler(createServer)` returns a web-standard handler; `toNodeHandler` adapts it to Express:
502
503```typescript
504const handler = createMcpHandler(createServer);
505const app = createMcpExpressApp();
506const nodeHandler = toNodeHandler(handler);
507app.all("/mcp", (req, res) => void nodeHandler(req, res, req.body));
508app.listen(3000, "127.0.0.1");
509```
510
511- It serves clients on the 2026-07-28 protocol revision and older 2025-era clients from the same factory, with no sessions for either
512- `createMcpExpressApp()` installs `express.json()` and validates `Host` and `Origin` headers on localhost binds, which blocks DNS rebinding attacks. When binding all interfaces, name the hosts you serve: `createMcpExpressApp({ host: "0.0.0.0", allowedHosts: ["mcp.example.com"] })`
513- Hono and Fastify adapters are `@modelcontextprotocol/hono` and `@modelcontextprotocol/fastify`
514- On web-standard runtimes (Cloudflare Workers, Deno, Bun), `export default handler` is the whole mount; put Host/Origin checks in front as described in the [web-standard docs](https://ts.sdk.modelcontextprotocol.io/v2/serving/web-standard.md)
515
516### Authentication
517
518The handler verifies no tokens. For a server exposed beyond localhost, put `requireBearerAuth` in front of the route:
519
520```typescript
521import { createMcpExpressApp, requireBearerAuth, type OAuthTokenVerifier } from "@modelcontextprotocol/express";
522import { OAuthError, OAuthErrorCode, type AuthInfo } from "@modelcontextprotocol/server";
523
524const serverUrl = new URL("https://mcp.example.com/mcp");
525
526const verifier: OAuthTokenVerifier = {
527 async verifyAccessToken(token): Promise<AuthInfo> {
528 // Replace with JWT verification or token introspection against your authorization server
529 const claims = await verifyWithYourAuthServer(token);
530 if (!claims) throw new OAuthError(OAuthErrorCode.InvalidToken, "Unknown or expired token");
531 return {
532 token,
533 clientId: claims.clientId,
534 scopes: claims.scopes,
535 expiresAt: claims.exp, // Required: tokens without an expiry are rejected
536 resource: new URL(claims.aud) // Compared with expectedResource below
537 };
538 }
539};
540
541const app = createMcpExpressApp({ host: "0.0.0.0", allowedHosts: ["mcp.example.com"] });
542const requireAuth = requireBearerAuth({ verifier, requiredScopes: ["mcp"], expectedResource: serverUrl });
543app.all("/mcp", requireAuth, (req, res) => void nodeHandler(req, res, req.body));
544```
545
546- `expectedResource` accepts only tokens issued for this server, so a token meant for another service is refused
547- The verified `AuthInfo` reaches the factory as `createMcpHandler(({ authInfo }) => ...)` and tool handlers as `ctx.http?.authInfo` (undefined on stdio)
548- Serving OAuth discovery metadata and per-tool scopes are covered by the [oauth](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/oauth) and [scoped-tools](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/scoped-tools) examples and the [authorization docs](https://ts.sdk.modelcontextprotocol.io/v2/serving/authorization.md)
549
550**Transport selection:** stdio for local tools a host launches as a subprocess; Streamable HTTP for remote services and multiple clients.
551
552---
553
554## Resources and Prompts
555
556Resources expose read-only data at a URI that the client application reads and attaches as context. Prompts are message templates a user invokes by name. Tools are for anything the model should call, including operations with side effects.
557
558```typescript
559import { completable, ProtocolError, ProtocolErrorCode, ResourceNotFoundError, ResourceTemplate } from "@modelcontextprotocol/server";
560
561// A resource at a fixed URI
562server.registerResource(
563 "example-teams",
564 "example://teams",
565 { title: "Teams", description: "Every team in the Example workspace", mimeType: "application/json" },
566 async (uri, ctx) => {
567 const teams = await apiRequest<unknown>("teams", {}, ctx.mcpReq.signal);
568 return { contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(teams) }] };
569 }
570);
571
572// A URI template: the matched variables arrive as the second argument
573server.registerResource(
574 "example-user",
575 new ResourceTemplate("example://users/{userId}", { list: undefined }),
576 { title: "User profile", description: "One Example user by ID", mimeType: "application/json" },
577 async (uri, { userId }, ctx) => {
578 if (!/^U\d+$/.test(String(userId))) {
579 throw new ProtocolError(ProtocolErrorCode.InvalidParams, `User IDs look like U123, got "${userId}"`);
580 }
581 const user = await apiRequest<unknown>(`users/${userId}`, {}, ctx.mcpReq.signal).catch((error: unknown) => {
582 // Only a 404 means the resource is missing; a 401, 429, or timeout keeps its own error
583 if (error instanceof ApiError && error.status === 404) throw new ResourceNotFoundError(uri.href);
584 throw error;
585 });
586 return { contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(user) }] };
587 }
588);
589
590// A prompt; completable() lets clients autocomplete the argument as the user types
591const TEAMS = ["engineering", "marketing", "sales"];
592
593server.registerPrompt(
594 "example_team_report",
595 {
596 title: "Team report",
597 description: "Summarize who is on a team",
598 argsSchema: z.object({
599 team: completable(z.string().describe("Team name"), value => TEAMS.filter(team => team.startsWith(value)))
600 })
601 },
602 async ({ team }) => ({
603 messages: [
604 {
605 role: "user",
606 content: { type: "text", text: `Use example_search_users to find everyone on the ${team} team, then summarize the team in a short table.` }
607 }
608 ]
609 })
610);
611```
612
613- Give a template a `list` callback that returns `{ resources: [...] }` to make its instances appear in `resources/list`; `{ list: undefined }` leaves them readable but unlisted
614- If a template variable becomes a filesystem path, resolve it with `realpath` and reject anything outside your root before reading
615
616## Notifications
617
618The handles returned by `registerTool`, `registerResource`, and `registerPrompt` send the matching `list_changed` notification when you change them:
619
620```typescript
621const exportTool = server.registerTool(
622 "example_export_data",
623 { description: "Export workspace data (export-enabled plans only)" },
624 async () => ({ content: [{ type: "text", text: "Export started" }] })
625);
626exportTool.disable(); // Sends notifications/tools/list_changed
627exportTool.enable(); // So do enable(), update(), and remove()
628```
629
630Behind `createMcpHandler` each request has its own server instance, so publish changes through the handler instead: `handler.notify.toolsChanged()`, `handler.notify.resourcesChanged()`. Send notifications only when the server's capabilities actually change.
631
632---
633
634## Verify Your Server
635
636Write a self-check script that starts the built server, calls its tools as a client would, and exits non-zero on any failure. Run it after every change, along with `npm run build`; adapt the tool names and assertions to your server.
637
638```typescript
639/**
640 * Self-check: starts the built server over stdio, calls its tools, and exits non-zero on any failure.
641 * Run with: npm run build && npm run smoke
642 */
643import { strict as assert } from "node:assert";
644import { Client } from "@modelcontextprotocol/client";
645import { getDefaultEnvironment, StdioClientTransport } from "@modelcontextprotocol/client/stdio";
646
647const client = new Client({ name: "smoke-test", version: "1.0.0" });
648await client.connect(
649 new StdioClientTransport({
650 command: "node",
651 args: ["dist/index.js"],
652 // The child gets only a safe default environment; pass the server's own variables explicitly
653 env: { ...getDefaultEnvironment(), EXAMPLE_API_KEY: process.env.EXAMPLE_API_KEY ?? "" }
654 })
655);
656
657const { tools } = await client.listTools();
658assert.deepEqual(tools.map(tool => tool.name).sort(), ["example_get_user", "example_search_users"]);
659
660const search = await client.callTool({
661 name: "example_search_users",
662 arguments: { query: "john", limit: 5, response_format: "json" }
663});
664assert.ok(!search.isError, `search failed: ${JSON.stringify(search.content)}`);
665const page = search.structuredContent as { users: { id: string }[]; total: number };
666assert.ok(Array.isArray(page.users), "search should return a users array");
667
668if (page.users.length > 0) {
669 const user = await client.callTool({ name: "example_get_user", arguments: { user_id: page.users[0].id } });
670 assert.ok(!user.isError, `get_user failed: ${JSON.stringify(user.content)}`);
671}
672
673// Invalid arguments must come back as a tool error the model can read
674const invalid = await client.callTool({ name: "example_search_users", arguments: { query: "j" } });
675assert.equal(invalid.isError, true, "a one-character query should be rejected");
676
677await client.close();
678console.error("Smoke test passed");
679```
680
681- Call read-only tools with realistic arguments; check that one invalid input is rejected
682- `StdioClientTransport` gives the child process only a safe default environment (`PATH`, `HOME`, and similar), so pass API keys and other settings in `env`
683- For an HTTP server, start it (`TRANSPORT=http npm start`) and connect with `new StreamableHTTPClientTransport(new URL("http://127.0.0.1:3000/mcp"))` from `@modelcontextprotocol/client` instead
684- For manual exploration, `npx @modelcontextprotocol/inspector node dist/index.js` opens an interactive UI
685- More test patterns, including in-process tests without a subprocess: `https://ts.sdk.modelcontextprotocol.io/v2/testing.md`
686
687---
688
689## More Features
690
691Each linked example is a runnable server and client pair from the SDK repository:
692
693| To... | See |
694|---|---|
695| Report progress, send log messages, and handle cancellation in long-running tools | [streaming](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/streaming) |
696| Ask the user for input mid-call (elicitation) | [elicitation](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/elicitation) |
697| Notify subscribed clients when resources change | [subscriptions](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/subscriptions) |
698| Add OAuth login (authorization code flow) | [oauth](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/oauth) |
699| Accept machine-to-machine OAuth (client credentials) | [oauth-client-credentials](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/oauth-client-credentials) |
700| Require different scopes for different tools | [scoped-tools](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/scoped-tools) |
701| Serve on Hono or another web-standard runtime | [hono](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/hono), [bearer-auth-web](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/bearer-auth-web) |
702| Run sessionful 2025-era HTTP deployments | [standalone-get](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/standalone-get), [sse-polling](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/sse-polling) |
703| See every server feature in one reference server | [todos-server](https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples/todos-server) |
704
705---
706
707## Migrating a v1 Server
708
709To move an existing `@modelcontextprotocol/sdk` server to v2, run the official codemod at the package root, then fix what it marks:
710
711```bash
712npx @modelcontextprotocol/codemod@latest v1-to-v2 .
713grep -rn '@mcp-codemod-error' . # Spots the codemod could not rewrite safely
714npx tsc --noEmit
715```
716
717The codemod rewrites imports, `package.json`, registration calls, and handler context access. Check that `zod` ends up at `^4.2.0` or later, then run your formatter and tests. The full guide is at `https://ts.sdk.modelcontextprotocol.io/v2/migration/upgrade-to-v2.md`.
718
719---
720
721## Quality Checklist
722
723### Tool Design
724- [ ] Tools enable complete workflows, not just API endpoint wrappers
725- [ ] Tool names are snake_case with a service prefix
726- [ ] Every tool has a `title`, a `description` that says when to use it, and correct `annotations`
727- [ ] Inputs are Zod object schemas with constraints and `.describe()` text; `z.strictObject` where unknown arguments should be rejected
728- [ ] List and search tools paginate with `limit` / `offset` and return `next_offset`
729- [ ] Responses stay under `CHARACTER_LIMIT` by returning fewer items
730- [ ] Results with `structuredContent` also include that data serialized as JSON text; `outputSchema` only on always-JSON tools
731- [ ] Error messages say what went wrong and how to recover
732
733### Implementation
734- [ ] `createServer()` returns a new `McpServer` on every call, with everything registered inside it; shared clients live at module scope
735- [ ] Upstream requests pass `ctx.mcpReq.signal` and have a timeout
736- [ ] Strict TypeScript; no `any`; upstream data validated where it feeds `structuredContent`
737- [ ] Nothing writes to stdout in a stdio server
738- [ ] HTTP servers keep Host/Origin validation, and add bearer auth when exposed beyond localhost
739
740### Project
741- [ ] `package.json` depends on `@modelcontextprotocol/server` (not `@modelcontextprotocol/sdk`) and `zod` `^4.2.0` or later
742- [ ] No imports from `@modelcontextprotocol/sdk/...` or `zod/v3`
743- [ ] `bin` points at `dist/index.js`, and `src/index.ts` starts with `#!/usr/bin/env node`
744
745### Verification
746- [ ] `npm run build` completes without errors
747- [ ] The self-check script passes against the built server

文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。