reference/mcp_best_practices.md
7.2 KB查看排版效果| 1 | # MCP Server Best Practices |
| 2 | |
| 3 | ## Quick Reference |
| 4 | |
| 5 | ### Server Naming |
| 6 | - **Python**: `{service}_mcp` (e.g., `slack_mcp`) |
| 7 | - **Node/TypeScript**: `{service}-mcp-server` (e.g., `slack-mcp-server`) |
| 8 | |
| 9 | ### Tool Naming |
| 10 | - Use snake_case with service prefix |
| 11 | - Format: `{service}_{action}_{resource}` |
| 12 | - Example: `slack_send_message`, `github_create_issue` |
| 13 | |
| 14 | ### Response Formats |
| 15 | - Support both JSON and Markdown formats |
| 16 | - JSON for programmatic processing |
| 17 | - Markdown for human readability |
| 18 | |
| 19 | ### Pagination |
| 20 | - Always respect `limit` parameter |
| 21 | - Return `has_more`, `next_offset`, `total_count` |
| 22 | - Default to 20-50 items |
| 23 | |
| 24 | ### Transport |
| 25 | - **Streamable HTTP**: For remote servers, multi-client scenarios |
| 26 | - **stdio**: For local integrations, command-line tools |
| 27 | - Avoid SSE (deprecated in favor of streamable HTTP) |
| 28 | |
| 29 | --- |
| 30 | |
| 31 | ## Server Naming Conventions |
| 32 | |
| 33 | Follow these standardized naming patterns: |
| 34 | |
| 35 | **Python**: Use format `{service}_mcp` (lowercase with underscores) |
| 36 | - Examples: `slack_mcp`, `github_mcp`, `jira_mcp` |
| 37 | |
| 38 | **Node/TypeScript**: Use format `{service}-mcp-server` (lowercase with hyphens) |
| 39 | - Examples: `slack-mcp-server`, `github-mcp-server`, `jira-mcp-server` |
| 40 | |
| 41 | The name should be general, descriptive of the service being integrated, easy to infer from the task description, and without version numbers. |
| 42 | |
| 43 | --- |
| 44 | |
| 45 | ## Tool Naming and Design |
| 46 | |
| 47 | ### Tool Naming |
| 48 | |
| 49 | 1. **Use snake_case**: `search_users`, `create_project`, `get_channel_info` |
| 50 | 2. **Include service prefix**: Anticipate that your MCP server may be used alongside other MCP servers |
| 51 | - Use `slack_send_message` instead of just `send_message` |
| 52 | - Use `github_create_issue` instead of just `create_issue` |
| 53 | 3. **Be action-oriented**: Start with verbs (get, list, search, create, etc.) |
| 54 | 4. **Be specific**: Avoid generic names that could conflict with other servers |
| 55 | |
| 56 | ### Tool Design |
| 57 | |
| 58 | - Tool descriptions must narrowly and unambiguously describe functionality |
| 59 | - Descriptions must precisely match actual functionality |
| 60 | - Provide tool annotations (readOnlyHint, destructiveHint, idempotentHint, openWorldHint) |
| 61 | - Keep tool operations focused and atomic |
| 62 | |
| 63 | --- |
| 64 | |
| 65 | ## Response Formats |
| 66 | |
| 67 | All tools that return data should support multiple formats: |
| 68 | |
| 69 | ### JSON Format (`response_format="json"`) |
| 70 | - Machine-readable structured data |
| 71 | - Include all available fields and metadata |
| 72 | - Consistent field names and types |
| 73 | - Use for programmatic processing |
| 74 | |
| 75 | ### Markdown Format (`response_format="markdown"`, typically default) |
| 76 | - Human-readable formatted text |
| 77 | - Use headers, lists, and formatting for clarity |
| 78 | - Convert timestamps to human-readable format |
| 79 | - Show display names with IDs in parentheses |
| 80 | - Omit verbose metadata |
| 81 | |
| 82 | --- |
| 83 | |
| 84 | ## Pagination |
| 85 | |
| 86 | For tools that list resources: |
| 87 | |
| 88 | - **Always respect the `limit` parameter** |
| 89 | - **Implement pagination**: Use `offset` or cursor-based pagination |
| 90 | - **Return pagination metadata**: Include `has_more`, `next_offset`/`next_cursor`, `total_count` |
| 91 | - **Never load all results into memory**: Especially important for large datasets |
| 92 | - **Default to reasonable limits**: 20-50 items is typical |
| 93 | |
| 94 | Example pagination response: |
| 95 | ```json |
| 96 | { |
| 97 | "total": 150, |
| 98 | "count": 20, |
| 99 | "offset": 0, |
| 100 | "items": [...], |
| 101 | "has_more": true, |
| 102 | "next_offset": 20 |
| 103 | } |
| 104 | ``` |
| 105 | |
| 106 | --- |
| 107 | |
| 108 | ## Transport Options |
| 109 | |
| 110 | ### Streamable HTTP |
| 111 | |
| 112 | **Best for**: Remote servers, web services, multi-client scenarios |
| 113 | |
| 114 | **Characteristics**: |
| 115 | - Bidirectional communication over HTTP |
| 116 | - Supports multiple simultaneous clients |
| 117 | - Can be deployed as a web service |
| 118 | - Enables server-to-client notifications |
| 119 | |
| 120 | **Use when**: |
| 121 | - Serving multiple clients simultaneously |
| 122 | - Deploying as a cloud service |
| 123 | - Integration with web applications |
| 124 | |
| 125 | ### stdio |
| 126 | |
| 127 | **Best for**: Local integrations, command-line tools |
| 128 | |
| 129 | **Characteristics**: |
| 130 | - Standard input/output stream communication |
| 131 | - Simple setup, no network configuration needed |
| 132 | - Runs as a subprocess of the client |
| 133 | |
| 134 | **Use when**: |
| 135 | - Building tools for local development environments |
| 136 | - Integrating with desktop applications |
| 137 | - Single-user, single-session scenarios |
| 138 | |
| 139 | **Note**: stdio servers should NOT log to stdout (use stderr for logging) |
| 140 | |
| 141 | ### Transport Selection |
| 142 | |
| 143 | | Criterion | stdio | Streamable HTTP | |
| 144 | |-----------|-------|-----------------| |
| 145 | | **Deployment** | Local | Remote | |
| 146 | | **Clients** | Single | Multiple | |
| 147 | | **Complexity** | Low | Medium | |
| 148 | | **Real-time** | No | Yes | |
| 149 | |
| 150 | --- |
| 151 | |
| 152 | ## Security Best Practices |
| 153 | |
| 154 | ### Authentication and Authorization |
| 155 | |
| 156 | **OAuth 2.1**: |
| 157 | - Use secure OAuth 2.1 with certificates from recognized authorities |
| 158 | - Validate access tokens before processing requests |
| 159 | - Only accept tokens specifically intended for your server |
| 160 | |
| 161 | **API Keys**: |
| 162 | - Store API keys in environment variables, never in code |
| 163 | - Validate keys on server startup |
| 164 | - Provide clear error messages when authentication fails |
| 165 | |
| 166 | ### Input Validation |
| 167 | |
| 168 | - Sanitize file paths to prevent directory traversal |
| 169 | - Validate URLs and external identifiers |
| 170 | - Check parameter sizes and ranges |
| 171 | - Prevent command injection in system calls |
| 172 | - Use schema validation (Pydantic/Zod) for all inputs |
| 173 | |
| 174 | ### Error Handling |
| 175 | |
| 176 | - Don't expose internal errors to clients |
| 177 | - Log security-relevant errors server-side |
| 178 | - Provide helpful but not revealing error messages |
| 179 | - Clean up resources after errors |
| 180 | |
| 181 | ### DNS Rebinding Protection |
| 182 | |
| 183 | For streamable HTTP servers running locally: |
| 184 | - Enable DNS rebinding protection |
| 185 | - Validate the `Origin` header on all incoming connections |
| 186 | - Bind to `127.0.0.1` rather than `0.0.0.0` |
| 187 | |
| 188 | --- |
| 189 | |
| 190 | ## Tool Annotations |
| 191 | |
| 192 | Provide annotations to help clients understand tool behavior: |
| 193 | |
| 194 | | Annotation | Type | Default | Description | |
| 195 | |-----------|------|---------|-------------| |
| 196 | | `readOnlyHint` | boolean | false | Tool does not modify its environment | |
| 197 | | `destructiveHint` | boolean | true | Tool may perform destructive updates | |
| 198 | | `idempotentHint` | boolean | false | Repeated calls with same args have no additional effect | |
| 199 | | `openWorldHint` | boolean | true | Tool interacts with external entities | |
| 200 | |
| 201 | **Important**: Annotations are hints, not security guarantees. Clients should not make security-critical decisions based solely on annotations. |
| 202 | |
| 203 | --- |
| 204 | |
| 205 | ## Error Handling |
| 206 | |
| 207 | - Use standard JSON-RPC error codes |
| 208 | - Report tool errors within result objects (not protocol-level errors) |
| 209 | - Provide helpful, specific error messages with suggested next steps |
| 210 | - Don't expose internal implementation details |
| 211 | - Clean up resources properly on errors |
| 212 | |
| 213 | Example error handling: |
| 214 | ```typescript |
| 215 | try { |
| 216 | const result = performOperation(); |
| 217 | return { content: [{ type: "text", text: result }] }; |
| 218 | } catch (error) { |
| 219 | return { |
| 220 | isError: true, |
| 221 | content: [{ |
| 222 | type: "text", |
| 223 | text: `Error: ${error.message}. Try using filter='active_only' to reduce results.` |
| 224 | }] |
| 225 | }; |
| 226 | } |
| 227 | ``` |
| 228 | |
| 229 | --- |
| 230 | |
| 231 | ## Testing Requirements |
| 232 | |
| 233 | Comprehensive testing should cover: |
| 234 | |
| 235 | - **Functional testing**: Verify correct execution with valid/invalid inputs |
| 236 | - **Integration testing**: Test interaction with external systems |
| 237 | - **Security testing**: Validate auth, input sanitization, rate limiting |
| 238 | - **Performance testing**: Check behavior under load, timeouts |
| 239 | - **Error handling**: Ensure proper error reporting and cleanup |
| 240 | |
| 241 | --- |
| 242 | |
| 243 | ## Documentation Requirements |
| 244 | |
| 245 | - Provide clear documentation of all tools and capabilities |
| 246 | - Include working examples (at least 3 per major feature) |
| 247 | - Document security considerations |
| 248 | - Specify required permissions and access levels |
| 249 | - Document rate limits and performance characteristics |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

