跳到主要内容

MCP 服务器构建

收藏0

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

让 AI 安装

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

reference/node_mcp_server.md

28.1 KB查看排版效果
1# Node/TypeScript MCP Server Implementation Guide
2
3> **This guide covers v1 of the TypeScript SDK (`@modelcontextprotocol/sdk`).** Use it only for projects that already depend on v1. For new servers, use the [v2 guide](./node_mcp_server_v2.md).
4
5## Overview
6
7This document provides Node/TypeScript-specific best practices and examples for implementing MCP servers using the MCP TypeScript SDK. It covers project structure, server setup, tool registration patterns, input validation with Zod, error handling, and complete working examples.
8
9---
10
11## Quick Reference
12
13### Key Imports
14```typescript
15import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
16import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
17import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
18import express from "express";
19import { z } from "zod";
20```
21
22### Server Initialization
23```typescript
24const server = new McpServer({
25 name: "service-mcp-server",
26 version: "1.0.0"
27});
28```
29
30### Tool Registration Pattern
31```typescript
32server.registerTool(
33 "tool_name",
34 {
35 title: "Tool Display Name",
36 description: "What the tool does",
37 inputSchema: { param: z.string() },
38 outputSchema: { result: z.string() }
39 },
40 async ({ param }) => {
41 const output = { result: `Processed: ${param}` };
42 return {
43 content: [{ type: "text", text: JSON.stringify(output) }],
44 structuredContent: output // Modern pattern for structured data
45 };
46 }
47);
48```
49
50---
51
52## MCP TypeScript SDK
53
54The official MCP TypeScript SDK provides:
55- `McpServer` class for server initialization
56- `registerTool` method for tool registration
57- Zod schema integration for runtime input validation
58- Type-safe tool handler implementations
59
60**IMPORTANT - Use Modern APIs Only:**
61- **DO use**: `server.registerTool()`, `server.registerResource()`, `server.registerPrompt()`
62- **DO NOT use**: Old deprecated APIs such as `server.tool()`, `server.setRequestHandler(ListToolsRequestSchema, ...)`, or manual handler registration
63- The `register*` methods provide better type safety, automatic schema handling, and are the recommended approach
64
65See the MCP SDK documentation in the references for complete details.
66
67## Server Naming Convention
68
69Node/TypeScript MCP servers must follow this naming pattern:
70- **Format**: `{service}-mcp-server` (lowercase with hyphens)
71- **Examples**: `github-mcp-server`, `jira-mcp-server`, `stripe-mcp-server`
72
73The name should be:
74- General (not tied to specific features)
75- Descriptive of the service/API being integrated
76- Easy to infer from the task description
77- Without version numbers or dates
78
79## Project Structure
80
81Create the following structure for Node/TypeScript MCP servers:
82
83```
84{service}-mcp-server/
85├── package.json
86├── tsconfig.json
87├── README.md
88├── src/
89│ ├── index.ts # Main entry point with McpServer initialization
90│ ├── types.ts # TypeScript type definitions and interfaces
91│ ├── tools/ # Tool implementations (one file per domain)
92│ ├── services/ # API clients and shared utilities
93│ ├── schemas/ # Zod validation schemas
94│ └── constants.ts # Shared constants (API_URL, CHARACTER_LIMIT, etc.)
95└── dist/ # Built JavaScript files (entry point: dist/index.js)
96```
97
98## Tool Implementation
99
100### Tool Naming
101
102Use snake_case for tool names (e.g., "search_users", "create_project", "get_channel_info") with clear, action-oriented names.
103
104**Avoid Naming Conflicts**: Include the service context to prevent overlaps:
105- Use "slack_send_message" instead of just "send_message"
106- Use "github_create_issue" instead of just "create_issue"
107- Use "asana_list_tasks" instead of just "list_tasks"
108
109### Tool Structure
110
111Tools are registered using the `registerTool` method with the following requirements:
112- Use Zod schemas for runtime input validation and type safety
113- The `description` field must be explicitly provided - JSDoc comments are NOT automatically extracted
114- Explicitly provide `title`, `description`, `inputSchema`, and `annotations`
115- The `inputSchema` must be a Zod schema object (not a JSON schema)
116- Type all parameters and return values explicitly
117
118```typescript
119import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
120import { z } from "zod";
121
122const server = new McpServer({
123 name: "example-mcp",
124 version: "1.0.0"
125});
126
127// Zod schema for input validation
128const UserSearchInputSchema = z.object({
129 query: z.string()
130 .min(2, "Query must be at least 2 characters")
131 .max(200, "Query must not exceed 200 characters")
132 .describe("Search string to match against names/emails"),
133 limit: z.number()
134 .int()
135 .min(1)
136 .max(100)
137 .default(20)
138 .describe("Maximum results to return"),
139 offset: z.number()
140 .int()
141 .min(0)
142 .default(0)
143 .describe("Number of results to skip for pagination"),
144 response_format: z.nativeEnum(ResponseFormat)
145 .default(ResponseFormat.MARKDOWN)
146 .describe("Output format: 'markdown' for human-readable or 'json' for machine-readable")
147}).strict();
148
149// Type definition from Zod schema
150type UserSearchInput = z.infer<typeof UserSearchInputSchema>;
151
152server.registerTool(
153 "example_search_users",
154 {
155 title: "Search Example Users",
156 description: `Search for users in the Example system by name, email, or team.
157
158This tool searches across all user profiles in the Example platform, supporting partial matches and various search filters. It does NOT create or modify users, only searches existing ones.
159
160Args:
161 - query (string): Search string to match against names/emails
162 - limit (number): Maximum results to return, between 1-100 (default: 20)
163 - offset (number): Number of results to skip for pagination (default: 0)
164 - response_format ('markdown' | 'json'): Output format (default: 'markdown')
165
166Returns:
167 For JSON format: Structured data with schema:
168 {
169 "total": number, // Total number of matches found
170 "count": number, // Number of results in this response
171 "offset": number, // Current pagination offset
172 "users": [
173 {
174 "id": string, // User ID (e.g., "U123456789")
175 "name": string, // Full name (e.g., "John Doe")
176 "email": string, // Email address
177 "team": string, // Team name (optional)
178 "active": boolean // Whether user is active
179 }
180 ],
181 "has_more": boolean, // Whether more results are available
182 "next_offset": number // Offset for next page (if has_more is true)
183 }
184
185Examples:
186 - Use when: "Find all marketing team members" -> params with query="team:marketing"
187 - Use when: "Search for John's account" -> params with query="john"
188 - Don't use when: You need to create a user (use example_create_user instead)
189
190Error Handling:
191 - Returns "Error: Rate limit exceeded" if too many requests (429 status)
192 - Returns "No users found matching '<query>'" if search returns empty`,
193 inputSchema: UserSearchInputSchema,
194 annotations: {
195 readOnlyHint: true,
196 destructiveHint: false,
197 idempotentHint: true,
198 openWorldHint: true
199 }
200 },
201 async (params: UserSearchInput) => {
202 try {
203 // Input validation is handled by Zod schema
204 // Make API request using validated parameters
205 const data = await makeApiRequest<any>(
206 "users/search",
207 "GET",
208 undefined,
209 {
210 q: params.query,
211 limit: params.limit,
212 offset: params.offset
213 }
214 );
215
216 const users = data.users || [];
217 const total = data.total || 0;
218
219 if (!users.length) {
220 return {
221 content: [{
222 type: "text",
223 text: `No users found matching '${params.query}'`
224 }]
225 };
226 }
227
228 // Prepare structured output
229 const output = {
230 total,
231 count: users.length,
232 offset: params.offset,
233 users: users.map((user: any) => ({
234 id: user.id,
235 name: user.name,
236 email: user.email,
237 ...(user.team ? { team: user.team } : {}),
238 active: user.active ?? true
239 })),
240 has_more: total > params.offset + users.length,
241 ...(total > params.offset + users.length ? {
242 next_offset: params.offset + users.length
243 } : {})
244 };
245
246 // Format text representation based on requested format
247 let textContent: string;
248 if (params.response_format === ResponseFormat.MARKDOWN) {
249 const lines = [`# User Search Results: '${params.query}'`, "",
250 `Found ${total} users (showing ${users.length})`, ""];
251 for (const user of users) {
252 lines.push(`## ${user.name} (${user.id})`);
253 lines.push(`- **Email**: ${user.email}`);
254 if (user.team) lines.push(`- **Team**: ${user.team}`);
255 lines.push("");
256 }
257 textContent = lines.join("\n");
258 } else {
259 textContent = JSON.stringify(output, null, 2);
260 }
261
262 return {
263 content: [{ type: "text", text: textContent }],
264 structuredContent: output // Modern pattern for structured data
265 };
266 } catch (error) {
267 return {
268 content: [{
269 type: "text",
270 text: handleApiError(error)
271 }]
272 };
273 }
274 }
275);
276```
277
278## Zod Schemas for Input Validation
279
280Zod provides runtime type validation:
281
282```typescript
283import { z } from "zod";
284
285// Basic schema with validation
286const CreateUserSchema = z.object({
287 name: z.string()
288 .min(1, "Name is required")
289 .max(100, "Name must not exceed 100 characters"),
290 email: z.string()
291 .email("Invalid email format"),
292 age: z.number()
293 .int("Age must be a whole number")
294 .min(0, "Age cannot be negative")
295 .max(150, "Age cannot be greater than 150")
296}).strict(); // Use .strict() to forbid extra fields
297
298// Enums
299enum ResponseFormat {
300 MARKDOWN = "markdown",
301 JSON = "json"
302}
303
304const SearchSchema = z.object({
305 response_format: z.nativeEnum(ResponseFormat)
306 .default(ResponseFormat.MARKDOWN)
307 .describe("Output format")
308});
309
310// Optional fields with defaults
311const PaginationSchema = z.object({
312 limit: z.number()
313 .int()
314 .min(1)
315 .max(100)
316 .default(20)
317 .describe("Maximum results to return"),
318 offset: z.number()
319 .int()
320 .min(0)
321 .default(0)
322 .describe("Number of results to skip")
323});
324```
325
326## Response Format Options
327
328Support multiple output formats for flexibility:
329
330```typescript
331enum ResponseFormat {
332 MARKDOWN = "markdown",
333 JSON = "json"
334}
335
336const inputSchema = z.object({
337 query: z.string(),
338 response_format: z.nativeEnum(ResponseFormat)
339 .default(ResponseFormat.MARKDOWN)
340 .describe("Output format: 'markdown' for human-readable or 'json' for machine-readable")
341});
342```
343
344**Markdown format**:
345- Use headers, lists, and formatting for clarity
346- Convert timestamps to human-readable format
347- Show display names with IDs in parentheses
348- Omit verbose metadata
349- Group related information logically
350
351**JSON format**:
352- Return complete, structured data suitable for programmatic processing
353- Include all available fields and metadata
354- Use consistent field names and types
355
356## Pagination Implementation
357
358For tools that list resources:
359
360```typescript
361const ListSchema = z.object({
362 limit: z.number().int().min(1).max(100).default(20),
363 offset: z.number().int().min(0).default(0)
364});
365
366async function listItems(params: z.infer<typeof ListSchema>) {
367 const data = await apiRequest(params.limit, params.offset);
368
369 const response = {
370 total: data.total,
371 count: data.items.length,
372 offset: params.offset,
373 items: data.items,
374 has_more: data.total > params.offset + data.items.length,
375 next_offset: data.total > params.offset + data.items.length
376 ? params.offset + data.items.length
377 : undefined
378 };
379
380 return JSON.stringify(response, null, 2);
381}
382```
383
384## Character Limits and Truncation
385
386Add a CHARACTER_LIMIT constant to prevent overwhelming responses:
387
388```typescript
389// At module level in constants.ts
390export const CHARACTER_LIMIT = 25000; // Maximum response size in characters
391
392async function searchTool(params: SearchInput) {
393 let result = generateResponse(data);
394
395 // Check character limit and truncate if needed
396 if (result.length > CHARACTER_LIMIT) {
397 const truncatedData = data.slice(0, Math.max(1, data.length / 2));
398 response.data = truncatedData;
399 response.truncated = true;
400 response.truncation_message =
401 `Response truncated from ${data.length} to ${truncatedData.length} items. ` +
402 `Use 'offset' parameter or add filters to see more results.`;
403 result = JSON.stringify(response, null, 2);
404 }
405
406 return result;
407}
408```
409
410## Error Handling
411
412Provide clear, actionable error messages:
413
414```typescript
415import axios, { AxiosError } from "axios";
416
417function handleApiError(error: unknown): string {
418 if (error instanceof AxiosError) {
419 if (error.response) {
420 switch (error.response.status) {
421 case 404:
422 return "Error: Resource not found. Please check the ID is correct.";
423 case 403:
424 return "Error: Permission denied. You don't have access to this resource.";
425 case 429:
426 return "Error: Rate limit exceeded. Please wait before making more requests.";
427 default:
428 return `Error: API request failed with status ${error.response.status}`;
429 }
430 } else if (error.code === "ECONNABORTED") {
431 return "Error: Request timed out. Please try again.";
432 }
433 }
434 return `Error: Unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`;
435}
436```
437
438## Shared Utilities
439
440Extract common functionality into reusable functions:
441
442```typescript
443// Shared API request function
444async function makeApiRequest<T>(
445 endpoint: string,
446 method: "GET" | "POST" | "PUT" | "DELETE" = "GET",
447 data?: any,
448 params?: any
449): Promise<T> {
450 try {
451 const response = await axios({
452 method,
453 url: `${API_BASE_URL}/${endpoint}`,
454 data,
455 params,
456 timeout: 30000,
457 headers: {
458 "Content-Type": "application/json",
459 "Accept": "application/json"
460 }
461 });
462 return response.data;
463 } catch (error) {
464 throw error;
465 }
466}
467```
468
469## Async/Await Best Practices
470
471Always use async/await for network requests and I/O operations:
472
473```typescript
474// Good: Async network request
475async function fetchData(resourceId: string): Promise<ResourceData> {
476 const response = await axios.get(`${API_URL}/resource/${resourceId}`);
477 return response.data;
478}
479
480// Bad: Promise chains
481function fetchData(resourceId: string): Promise<ResourceData> {
482 return axios.get(`${API_URL}/resource/${resourceId}`)
483 .then(response => response.data); // Harder to read and maintain
484}
485```
486
487## TypeScript Best Practices
488
4891. **Use Strict TypeScript**: Enable strict mode in tsconfig.json
4902. **Define Interfaces**: Create clear interface definitions for all data structures
4913. **Avoid `any`**: Use proper types or `unknown` instead of `any`
4924. **Zod for Runtime Validation**: Use Zod schemas to validate external data
4935. **Type Guards**: Create type guard functions for complex type checking
4946. **Error Handling**: Always use try-catch with proper error type checking
4957. **Null Safety**: Use optional chaining (`?.`) and nullish coalescing (`??`)
496
497```typescript
498// Good: Type-safe with Zod and interfaces
499interface UserResponse {
500 id: string;
501 name: string;
502 email: string;
503 team?: string;
504 active: boolean;
505}
506
507const UserSchema = z.object({
508 id: z.string(),
509 name: z.string(),
510 email: z.string().email(),
511 team: z.string().optional(),
512 active: z.boolean()
513});
514
515type User = z.infer<typeof UserSchema>;
516
517async function getUser(id: string): Promise<User> {
518 const data = await apiCall(`/users/${id}`);
519 return UserSchema.parse(data); // Runtime validation
520}
521
522// Bad: Using any
523async function getUser(id: string): Promise<any> {
524 return await apiCall(`/users/${id}`); // No type safety
525}
526```
527
528## Package Configuration
529
530### package.json
531
532```json
533{
534 "name": "{service}-mcp-server",
535 "version": "1.0.0",
536 "description": "MCP server for {Service} API integration",
537 "type": "module",
538 "main": "dist/index.js",
539 "scripts": {
540 "start": "node dist/index.js",
541 "dev": "tsx watch src/index.ts",
542 "build": "tsc",
543 "clean": "rm -rf dist"
544 },
545 "engines": {
546 "node": ">=18"
547 },
548 "dependencies": {
549 "@modelcontextprotocol/sdk": "^1.6.1",
550 "axios": "^1.7.9",
551 "zod": "^3.23.8"
552 },
553 "devDependencies": {
554 "@types/node": "^22.10.0",
555 "tsx": "^4.19.2",
556 "typescript": "^5.7.2"
557 }
558}
559```
560
561### tsconfig.json
562
563```json
564{
565 "compilerOptions": {
566 "target": "ES2022",
567 "module": "Node16",
568 "moduleResolution": "Node16",
569 "lib": ["ES2022"],
570 "outDir": "./dist",
571 "rootDir": "./src",
572 "strict": true,
573 "esModuleInterop": true,
574 "skipLibCheck": true,
575 "forceConsistentCasingInFileNames": true,
576 "declaration": true,
577 "declarationMap": true,
578 "sourceMap": true,
579 "allowSyntheticDefaultImports": true
580 },
581 "include": ["src/**/*"],
582 "exclude": ["node_modules", "dist"]
583}
584```
585
586## Complete Example
587
588```typescript
589#!/usr/bin/env node
590/**
591 * MCP Server for Example Service.
592 *
593 * This server provides tools to interact with Example API, including user search,
594 * project management, and data export capabilities.
595 */
596
597import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
598import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
599import { z } from "zod";
600import axios, { AxiosError } from "axios";
601
602// Constants
603const API_BASE_URL = "https://api.example.com/v1";
604const CHARACTER_LIMIT = 25000;
605
606// Enums
607enum ResponseFormat {
608 MARKDOWN = "markdown",
609 JSON = "json"
610}
611
612// Zod schemas
613const UserSearchInputSchema = z.object({
614 query: z.string()
615 .min(2, "Query must be at least 2 characters")
616 .max(200, "Query must not exceed 200 characters")
617 .describe("Search string to match against names/emails"),
618 limit: z.number()
619 .int()
620 .min(1)
621 .max(100)
622 .default(20)
623 .describe("Maximum results to return"),
624 offset: z.number()
625 .int()
626 .min(0)
627 .default(0)
628 .describe("Number of results to skip for pagination"),
629 response_format: z.nativeEnum(ResponseFormat)
630 .default(ResponseFormat.MARKDOWN)
631 .describe("Output format: 'markdown' for human-readable or 'json' for machine-readable")
632}).strict();
633
634type UserSearchInput = z.infer<typeof UserSearchInputSchema>;
635
636// Shared utility functions
637async function makeApiRequest<T>(
638 endpoint: string,
639 method: "GET" | "POST" | "PUT" | "DELETE" = "GET",
640 data?: any,
641 params?: any
642): Promise<T> {
643 try {
644 const response = await axios({
645 method,
646 url: `${API_BASE_URL}/${endpoint}`,
647 data,
648 params,
649 timeout: 30000,
650 headers: {
651 "Content-Type": "application/json",
652 "Accept": "application/json"
653 }
654 });
655 return response.data;
656 } catch (error) {
657 throw error;
658 }
659}
660
661function handleApiError(error: unknown): string {
662 if (error instanceof AxiosError) {
663 if (error.response) {
664 switch (error.response.status) {
665 case 404:
666 return "Error: Resource not found. Please check the ID is correct.";
667 case 403:
668 return "Error: Permission denied. You don't have access to this resource.";
669 case 429:
670 return "Error: Rate limit exceeded. Please wait before making more requests.";
671 default:
672 return `Error: API request failed with status ${error.response.status}`;
673 }
674 } else if (error.code === "ECONNABORTED") {
675 return "Error: Request timed out. Please try again.";
676 }
677 }
678 return `Error: Unexpected error occurred: ${error instanceof Error ? error.message : String(error)}`;
679}
680
681// Create MCP server instance
682const server = new McpServer({
683 name: "example-mcp",
684 version: "1.0.0"
685});
686
687// Register tools
688server.registerTool(
689 "example_search_users",
690 {
691 title: "Search Example Users",
692 description: `[Full description as shown above]`,
693 inputSchema: UserSearchInputSchema,
694 annotations: {
695 readOnlyHint: true,
696 destructiveHint: false,
697 idempotentHint: true,
698 openWorldHint: true
699 }
700 },
701 async (params: UserSearchInput) => {
702 // Implementation as shown above
703 }
704);
705
706// Main function
707// For stdio (local):
708async function runStdio() {
709 if (!process.env.EXAMPLE_API_KEY) {
710 console.error("ERROR: EXAMPLE_API_KEY environment variable is required");
711 process.exit(1);
712 }
713
714 const transport = new StdioServerTransport();
715 await server.connect(transport);
716 console.error("MCP server running via stdio");
717}
718
719// For streamable HTTP (remote):
720async function runHTTP() {
721 if (!process.env.EXAMPLE_API_KEY) {
722 console.error("ERROR: EXAMPLE_API_KEY environment variable is required");
723 process.exit(1);
724 }
725
726 const app = express();
727 app.use(express.json());
728
729 app.post('/mcp', async (req, res) => {
730 const transport = new StreamableHTTPServerTransport({
731 sessionIdGenerator: undefined,
732 enableJsonResponse: true
733 });
734 res.on('close', () => transport.close());
735 await server.connect(transport);
736 await transport.handleRequest(req, res, req.body);
737 });
738
739 const port = parseInt(process.env.PORT || '3000');
740 app.listen(port, () => {
741 console.error(`MCP server running on http://localhost:${port}/mcp`);
742 });
743}
744
745// Choose transport based on environment
746const transport = process.env.TRANSPORT || 'stdio';
747if (transport === 'http') {
748 runHTTP().catch(error => {
749 console.error("Server error:", error);
750 process.exit(1);
751 });
752} else {
753 runStdio().catch(error => {
754 console.error("Server error:", error);
755 process.exit(1);
756 });
757}
758```
759
760---
761
762## Advanced MCP Features
763
764### Resource Registration
765
766Expose data as resources for efficient, URI-based access:
767
768```typescript
769import { ResourceTemplate } from "@modelcontextprotocol/sdk/types.js";
770
771// Register a resource with URI template
772server.registerResource(
773 {
774 uri: "file://documents/{name}",
775 name: "Document Resource",
776 description: "Access documents by name",
777 mimeType: "text/plain"
778 },
779 async (uri: string) => {
780 // Extract parameter from URI
781 const match = uri.match(/^file:\/\/documents\/(.+)$/);
782 if (!match) {
783 throw new Error("Invalid URI format");
784 }
785
786 const documentName = match[1];
787 const content = await loadDocument(documentName);
788
789 return {
790 contents: [{
791 uri,
792 mimeType: "text/plain",
793 text: content
794 }]
795 };
796 }
797);
798
799// List available resources dynamically
800server.registerResourceList(async () => {
801 const documents = await getAvailableDocuments();
802 return {
803 resources: documents.map(doc => ({
804 uri: `file://documents/${doc.name}`,
805 name: doc.name,
806 mimeType: "text/plain",
807 description: doc.description
808 }))
809 };
810});
811```
812
813**When to use Resources vs Tools:**
814- **Resources**: For data access with simple URI-based parameters
815- **Tools**: For complex operations requiring validation and business logic
816- **Resources**: When data is relatively static or template-based
817- **Tools**: When operations have side effects or complex workflows
818
819### Transport Options
820
821The TypeScript SDK supports two main transport mechanisms:
822
823#### Streamable HTTP (Recommended for Remote Servers)
824
825```typescript
826import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
827import express from "express";
828
829const app = express();
830app.use(express.json());
831
832app.post('/mcp', async (req, res) => {
833 // Create new transport for each request (stateless, prevents request ID collisions)
834 const transport = new StreamableHTTPServerTransport({
835 sessionIdGenerator: undefined,
836 enableJsonResponse: true
837 });
838
839 res.on('close', () => transport.close());
840
841 await server.connect(transport);
842 await transport.handleRequest(req, res, req.body);
843});
844
845app.listen(3000);
846```
847
848#### stdio (For Local Integrations)
849
850```typescript
851import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
852
853const transport = new StdioServerTransport();
854await server.connect(transport);
855```
856
857**Transport selection:**
858- **Streamable HTTP**: Web services, remote access, multiple clients
859- **stdio**: Command-line tools, local development, subprocess integration
860
861### Notification Support
862
863Notify clients when server state changes:
864
865```typescript
866// Notify when tools list changes
867server.notification({
868 method: "notifications/tools/list_changed"
869});
870
871// Notify when resources change
872server.notification({
873 method: "notifications/resources/list_changed"
874});
875```
876
877Use notifications sparingly - only when server capabilities genuinely change.
878
879---
880
881## Code Best Practices
882
883### Code Composability and Reusability
884
885Your implementation MUST prioritize composability and code reuse:
886
8871. **Extract Common Functionality**:
888 - Create reusable helper functions for operations used across multiple tools
889 - Build shared API clients for HTTP requests instead of duplicating code
890 - Centralize error handling logic in utility functions
891 - Extract business logic into dedicated functions that can be composed
892 - Extract shared markdown or JSON field selection & formatting functionality
893
8942. **Avoid Duplication**:
895 - NEVER copy-paste similar code between tools
896 - If you find yourself writing similar logic twice, extract it into a function
897 - Common operations like pagination, filtering, field selection, and formatting should be shared
898 - Authentication/authorization logic should be centralized
899
900## Building and Running
901
902Always build your TypeScript code before running:
903
904```bash
905# Build the project
906npm run build
907
908# Run the server
909npm start
910
911# Development with auto-reload
912npm run dev
913```
914
915Always ensure `npm run build` completes successfully before considering the implementation complete.
916
917## Quality Checklist
918
919Before finalizing your Node/TypeScript MCP server implementation, ensure:
920
921### Strategic Design
922- [ ] Tools enable complete workflows, not just API endpoint wrappers
923- [ ] Tool names reflect natural task subdivisions
924- [ ] Response formats optimize for agent context efficiency
925- [ ] Human-readable identifiers used where appropriate
926- [ ] Error messages guide agents toward correct usage
927
928### Implementation Quality
929- [ ] FOCUSED IMPLEMENTATION: Most important and valuable tools implemented
930- [ ] All tools registered using `registerTool` with complete configuration
931- [ ] All tools include `title`, `description`, `inputSchema`, and `annotations`
932- [ ] Annotations correctly set (readOnlyHint, destructiveHint, idempotentHint, openWorldHint)
933- [ ] All tools use Zod schemas for runtime input validation with `.strict()` enforcement
934- [ ] All Zod schemas have proper constraints and descriptive error messages
935- [ ] All tools have comprehensive descriptions with explicit input/output types
936- [ ] Descriptions include return value examples and complete schema documentation
937- [ ] Error messages are clear, actionable, and educational
938
939### TypeScript Quality
940- [ ] TypeScript interfaces are defined for all data structures
941- [ ] Strict TypeScript is enabled in tsconfig.json
942- [ ] No use of `any` type - use `unknown` or proper types instead
943- [ ] All async functions have explicit Promise<T> return types
944- [ ] Error handling uses proper type guards (e.g., `axios.isAxiosError`, `z.ZodError`)
945
946### Advanced Features (where applicable)
947- [ ] Resources registered for appropriate data endpoints
948- [ ] Appropriate transport configured (stdio or streamable HTTP)
949- [ ] Notifications implemented for dynamic server capabilities
950- [ ] Type-safe with SDK interfaces
951
952### Project Configuration
953- [ ] Package.json includes all necessary dependencies
954- [ ] Build script produces working JavaScript in dist/ directory
955- [ ] Main entry point is properly configured as dist/index.js
956- [ ] Server name follows format: `{service}-mcp-server`
957- [ ] tsconfig.json properly configured with strict mode
958
959### Code Quality
960- [ ] Pagination is properly implemented where applicable
961- [ ] Large responses check CHARACTER_LIMIT constant and truncate with clear messages
962- [ ] Filtering options are provided for potentially large result sets
963- [ ] All network operations handle timeouts and connection errors gracefully
964- [ ] Common functionality is extracted into reusable functions
965- [ ] Return types are consistent across similar operations
966
967### Testing and Build
968- [ ] `npm run build` completes successfully without errors
969- [ ] dist/index.js created and executable
970- [ ] Server runs: `node dist/index.js --help`
971- [ ] All imports resolve correctly
972- [ ] Sample tool calls work as expected

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