mirror of
https://github.com/anthropics/skills.git
synced 2026-04-15 14:33:47 +08:00
Update example skills and rename 'artifacts-builder' (#112)
* Export updated examples * Rename 'artifacts-builder' to 'web-artifacts-builder'
This commit is contained in:
@@ -8,7 +8,7 @@ license: Complete terms in LICENSE.txt
|
||||
|
||||
## Overview
|
||||
|
||||
To create high-quality MCP (Model Context Protocol) servers that enable LLMs to effectively interact with external services, use this skill. An MCP server provides tools that allow LLMs to access external services and APIs. The quality of an MCP server is measured by how well it enables LLMs to accomplish real-world tasks using the tools provided.
|
||||
Create MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. The quality of an MCP server is measured by how well it enables LLMs to accomplish real-world tasks.
|
||||
|
||||
---
|
||||
|
||||
@@ -20,222 +20,131 @@ Creating a high-quality MCP server involves four main phases:
|
||||
|
||||
### Phase 1: Deep Research and Planning
|
||||
|
||||
#### 1.1 Understand Agent-Centric Design Principles
|
||||
#### 1.1 Understand Modern MCP Design
|
||||
|
||||
Before diving into implementation, understand how to design tools for AI agents by reviewing these principles:
|
||||
**API Coverage vs. Workflow Tools:**
|
||||
Balance comprehensive API endpoint coverage with specialized workflow tools. Workflow tools can be more convenient for specific tasks, while comprehensive coverage gives agents flexibility to compose operations. Performance varies by client—some clients benefit from code execution that combines basic tools, while others work better with higher-level workflows. When uncertain, prioritize comprehensive API coverage.
|
||||
|
||||
**Build for Workflows, Not Just API Endpoints:**
|
||||
- Don't simply wrap existing API endpoints - build thoughtful, high-impact workflow tools
|
||||
- Consolidate related operations (e.g., `schedule_event` that both checks availability and creates event)
|
||||
- Focus on tools that enable complete tasks, not just individual API calls
|
||||
- Consider what workflows agents actually need to accomplish
|
||||
**Tool Naming and Discoverability:**
|
||||
Clear, descriptive tool names help agents find the right tools quickly. Use consistent prefixes (e.g., `github_create_issue`, `github_list_repos`) and action-oriented naming.
|
||||
|
||||
**Optimize for Limited Context:**
|
||||
- Agents have constrained context windows - make every token count
|
||||
- Return high-signal information, not exhaustive data dumps
|
||||
- Provide "concise" vs "detailed" response format options
|
||||
- Default to human-readable identifiers over technical codes (names over IDs)
|
||||
- Consider the agent's context budget as a scarce resource
|
||||
**Context Management:**
|
||||
Agents benefit from concise tool descriptions and the ability to filter/paginate results. Design tools that return focused, relevant data. Some clients support code execution which can help agents filter and process data efficiently.
|
||||
|
||||
**Design Actionable Error Messages:**
|
||||
- Error messages should guide agents toward correct usage patterns
|
||||
- Suggest specific next steps: "Try using filter='active_only' to reduce results"
|
||||
- Make errors educational, not just diagnostic
|
||||
- Help agents learn proper tool usage through clear feedback
|
||||
**Actionable Error Messages:**
|
||||
Error messages should guide agents toward solutions with specific suggestions and next steps.
|
||||
|
||||
**Follow Natural Task Subdivisions:**
|
||||
- Tool names should reflect how humans think about tasks
|
||||
- Group related tools with consistent prefixes for discoverability
|
||||
- Design tools around natural workflows, not just API structure
|
||||
#### 1.2 Study MCP Protocol Documentation
|
||||
|
||||
**Use Evaluation-Driven Development:**
|
||||
- Create realistic evaluation scenarios early
|
||||
- Let agent feedback drive tool improvements
|
||||
- Prototype quickly and iterate based on actual agent performance
|
||||
**Navigate the MCP specification:**
|
||||
|
||||
#### 1.3 Study MCP Protocol Documentation
|
||||
Start with the sitemap to find relevant pages: `https://modelcontextprotocol.io/sitemap.xml`
|
||||
|
||||
**Fetch the latest MCP protocol documentation:**
|
||||
Then fetch specific pages with `.md` suffix for markdown format (e.g., `https://modelcontextprotocol.io/specification/draft.md`).
|
||||
|
||||
Use WebFetch to load: `https://modelcontextprotocol.io/llms-full.txt`
|
||||
Key pages to review:
|
||||
- Specification overview and architecture
|
||||
- Transport mechanisms (streamable HTTP, stdio)
|
||||
- Tool, resource, and prompt definitions
|
||||
|
||||
This comprehensive document contains the complete MCP specification and guidelines.
|
||||
#### 1.3 Study Framework Documentation
|
||||
|
||||
#### 1.4 Study Framework Documentation
|
||||
**Recommended stack:**
|
||||
- **Language**: TypeScript (high-quality SDK support and good compatibility in many execution environments e.g. MCPB. Plus AI models are good at generating TypeScript code, benefiting from its broad usage, static typing and good linting tools)
|
||||
- **Transport**: Streamable HTTP for remote servers, using stateless JSON (simpler to scale and maintain, as opposed to stateful sessions and streaming responses). stdio for local servers.
|
||||
|
||||
**Load and read the following reference files:**
|
||||
**Load framework documentation:**
|
||||
|
||||
- **MCP Best Practices**: [📋 View Best Practices](./reference/mcp_best_practices.md) - Core guidelines for all MCP servers
|
||||
- **MCP Best Practices**: [📋 View Best Practices](./reference/mcp_best_practices.md) - Core guidelines
|
||||
|
||||
**For Python implementations, also load:**
|
||||
- **Python SDK Documentation**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md`
|
||||
- [🐍 Python Implementation Guide](./reference/python_mcp_server.md) - Python-specific best practices and examples
|
||||
**For TypeScript (recommended):**
|
||||
- **TypeScript SDK**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md`
|
||||
- [⚡ TypeScript Guide](./reference/node_mcp_server.md) - TypeScript patterns and examples
|
||||
|
||||
**For Node/TypeScript implementations, also load:**
|
||||
- **TypeScript SDK Documentation**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md`
|
||||
- [⚡ TypeScript Implementation Guide](./reference/node_mcp_server.md) - Node/TypeScript-specific best practices and examples
|
||||
**For Python:**
|
||||
- **Python SDK**: Use WebFetch to load `https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md`
|
||||
- [🐍 Python Guide](./reference/python_mcp_server.md) - Python patterns and examples
|
||||
|
||||
#### 1.5 Exhaustively Study API Documentation
|
||||
#### 1.4 Plan Your Implementation
|
||||
|
||||
To integrate a service, read through **ALL** available API documentation:
|
||||
- Official API reference documentation
|
||||
- Authentication and authorization requirements
|
||||
- Rate limiting and pagination patterns
|
||||
- Error responses and status codes
|
||||
- Available endpoints and their parameters
|
||||
- Data models and schemas
|
||||
|
||||
**To gather comprehensive information, use web search and the WebFetch tool as needed.**
|
||||
|
||||
#### 1.6 Create a Comprehensive Implementation Plan
|
||||
|
||||
Based on your research, create a detailed plan that includes:
|
||||
**Understand the API:**
|
||||
Review the service's API documentation to identify key endpoints, authentication requirements, and data models. Use web search and WebFetch as needed.
|
||||
|
||||
**Tool Selection:**
|
||||
- List the most valuable endpoints/operations to implement
|
||||
- Prioritize tools that enable the most common and important use cases
|
||||
- Consider which tools work together to enable complex workflows
|
||||
|
||||
**Shared Utilities and Helpers:**
|
||||
- Identify common API request patterns
|
||||
- Plan pagination helpers
|
||||
- Design filtering and formatting utilities
|
||||
- Plan error handling strategies
|
||||
|
||||
**Input/Output Design:**
|
||||
- Define input validation models (Pydantic for Python, Zod for TypeScript)
|
||||
- Design consistent response formats (e.g., JSON or Markdown), and configurable levels of detail (e.g., Detailed or Concise)
|
||||
- Plan for large-scale usage (thousands of users/resources)
|
||||
- Implement character limits and truncation strategies (e.g., 25,000 tokens)
|
||||
|
||||
**Error Handling Strategy:**
|
||||
- Plan graceful failure modes
|
||||
- Design clear, actionable, LLM-friendly, natural language error messages which prompt further action
|
||||
- Consider rate limiting and timeout scenarios
|
||||
- Handle authentication and authorization errors
|
||||
Prioritize comprehensive API coverage. List endpoints to implement, starting with the most common operations.
|
||||
|
||||
---
|
||||
|
||||
### Phase 2: Implementation
|
||||
|
||||
Now that you have a comprehensive plan, begin implementation following language-specific best practices.
|
||||
|
||||
#### 2.1 Set Up Project Structure
|
||||
|
||||
**For Python:**
|
||||
- Create a single `.py` file or organize into modules if complex (see [🐍 Python Guide](./reference/python_mcp_server.md))
|
||||
- Use the MCP Python SDK for tool registration
|
||||
- Define Pydantic models for input validation
|
||||
See language-specific guides for project setup:
|
||||
- [⚡ TypeScript Guide](./reference/node_mcp_server.md) - Project structure, package.json, tsconfig.json
|
||||
- [🐍 Python Guide](./reference/python_mcp_server.md) - Module organization, dependencies
|
||||
|
||||
**For Node/TypeScript:**
|
||||
- Create proper project structure (see [⚡ TypeScript Guide](./reference/node_mcp_server.md))
|
||||
- Set up `package.json` and `tsconfig.json`
|
||||
- Use MCP TypeScript SDK
|
||||
- Define Zod schemas for input validation
|
||||
#### 2.2 Implement Core Infrastructure
|
||||
|
||||
#### 2.2 Implement Core Infrastructure First
|
||||
Create shared utilities:
|
||||
- API client with authentication
|
||||
- Error handling helpers
|
||||
- Response formatting (JSON/Markdown)
|
||||
- Pagination support
|
||||
|
||||
**To begin implementation, create shared utilities before implementing tools:**
|
||||
- API request helper functions
|
||||
- Error handling utilities
|
||||
- Response formatting functions (JSON and Markdown)
|
||||
- Pagination helpers
|
||||
- Authentication/token management
|
||||
#### 2.3 Implement Tools
|
||||
|
||||
#### 2.3 Implement Tools Systematically
|
||||
For each tool:
|
||||
|
||||
For each tool in the plan:
|
||||
**Input Schema:**
|
||||
- Use Zod (TypeScript) or Pydantic (Python)
|
||||
- Include constraints and clear descriptions
|
||||
- Add examples in field descriptions
|
||||
|
||||
**Define Input Schema:**
|
||||
- Use Pydantic (Python) or Zod (TypeScript) for validation
|
||||
- Include proper constraints (min/max length, regex patterns, min/max values, ranges)
|
||||
- Provide clear, descriptive field descriptions
|
||||
- Include diverse examples in field descriptions
|
||||
**Output Schema:**
|
||||
- Define `outputSchema` where possible for structured data
|
||||
- Use `structuredContent` in tool responses (TypeScript SDK feature)
|
||||
- Helps clients understand and process tool outputs
|
||||
|
||||
**Write Comprehensive Docstrings/Descriptions:**
|
||||
- One-line summary of what the tool does
|
||||
- Detailed explanation of purpose and functionality
|
||||
- Explicit parameter types with examples
|
||||
- Complete return type schema
|
||||
- Usage examples (when to use, when not to use)
|
||||
- Error handling documentation, which outlines how to proceed given specific errors
|
||||
**Tool Description:**
|
||||
- Concise summary of functionality
|
||||
- Parameter descriptions
|
||||
- Return type schema
|
||||
|
||||
**Implement Tool Logic:**
|
||||
- Use shared utilities to avoid code duplication
|
||||
- Follow async/await patterns for all I/O
|
||||
- Implement proper error handling
|
||||
- Support multiple response formats (JSON and Markdown)
|
||||
- Respect pagination parameters
|
||||
- Check character limits and truncate appropriately
|
||||
**Implementation:**
|
||||
- Async/await for I/O operations
|
||||
- Proper error handling with actionable messages
|
||||
- Support pagination where applicable
|
||||
- Return both text content and structured data when using modern SDKs
|
||||
|
||||
**Add Tool Annotations:**
|
||||
- `readOnlyHint`: true (for read-only operations)
|
||||
- `destructiveHint`: false (for non-destructive operations)
|
||||
- `idempotentHint`: true (if repeated calls have same effect)
|
||||
- `openWorldHint`: true (if interacting with external systems)
|
||||
|
||||
#### 2.4 Follow Language-Specific Best Practices
|
||||
|
||||
**At this point, load the appropriate language guide:**
|
||||
|
||||
**For Python: Load [🐍 Python Implementation Guide](./reference/python_mcp_server.md) and ensure the following:**
|
||||
- Using MCP Python SDK with proper tool registration
|
||||
- Pydantic v2 models with `model_config`
|
||||
- Type hints throughout
|
||||
- Async/await for all I/O operations
|
||||
- Proper imports organization
|
||||
- Module-level constants (CHARACTER_LIMIT, API_BASE_URL)
|
||||
|
||||
**For Node/TypeScript: Load [⚡ TypeScript Implementation Guide](./reference/node_mcp_server.md) and ensure the following:**
|
||||
- Using `server.registerTool` properly
|
||||
- Zod schemas with `.strict()`
|
||||
- TypeScript strict mode enabled
|
||||
- No `any` types - use proper types
|
||||
- Explicit Promise<T> return types
|
||||
- Build process configured (`npm run build`)
|
||||
**Annotations:**
|
||||
- `readOnlyHint`: true/false
|
||||
- `destructiveHint`: true/false
|
||||
- `idempotentHint`: true/false
|
||||
- `openWorldHint`: true/false
|
||||
|
||||
---
|
||||
|
||||
### Phase 3: Review and Refine
|
||||
### Phase 3: Review and Test
|
||||
|
||||
After initial implementation:
|
||||
#### 3.1 Code Quality
|
||||
|
||||
#### 3.1 Code Quality Review
|
||||
Review for:
|
||||
- No duplicated code (DRY principle)
|
||||
- Consistent error handling
|
||||
- Full type coverage
|
||||
- Clear tool descriptions
|
||||
|
||||
To ensure quality, review the code for:
|
||||
- **DRY Principle**: No duplicated code between tools
|
||||
- **Composability**: Shared logic extracted into functions
|
||||
- **Consistency**: Similar operations return similar formats
|
||||
- **Error Handling**: All external calls have error handling
|
||||
- **Type Safety**: Full type coverage (Python type hints, TypeScript types)
|
||||
- **Documentation**: Every tool has comprehensive docstrings/descriptions
|
||||
#### 3.2 Build and Test
|
||||
|
||||
#### 3.2 Test and Build
|
||||
**TypeScript:**
|
||||
- Run `npm run build` to verify compilation
|
||||
- Test with MCP Inspector: `npx @modelcontextprotocol/inspector`
|
||||
|
||||
**Important:** MCP servers are long-running processes that wait for requests over stdio/stdin or sse/http. Running them directly in your main process (e.g., `python server.py` or `node dist/index.js`) will cause your process to hang indefinitely.
|
||||
**Python:**
|
||||
- Verify syntax: `python -m py_compile your_server.py`
|
||||
- Test with MCP Inspector
|
||||
|
||||
**Safe ways to test the server:**
|
||||
- Use the evaluation harness (see Phase 4) - recommended approach
|
||||
- Run the server in tmux to keep it outside your main process
|
||||
- Use a timeout when testing: `timeout 5s python server.py`
|
||||
|
||||
**For Python:**
|
||||
- Verify Python syntax: `python -m py_compile your_server.py`
|
||||
- Check imports work correctly by reviewing the file
|
||||
- To manually test: Run server in tmux, then test with evaluation harness in main process
|
||||
- Or use the evaluation harness directly (it manages the server for stdio transport)
|
||||
|
||||
**For Node/TypeScript:**
|
||||
- Run `npm run build` and ensure it completes without errors
|
||||
- Verify dist/index.js is created
|
||||
- To manually test: Run server in tmux, then test with evaluation harness in main process
|
||||
- Or use the evaluation harness directly (it manages the server for stdio transport)
|
||||
|
||||
#### 3.3 Use Quality Checklist
|
||||
|
||||
To verify implementation quality, load the appropriate checklist from the language-specific guide:
|
||||
- Python: see "Quality Checklist" in [🐍 Python Guide](./reference/python_mcp_server.md)
|
||||
- Node/TypeScript: see "Quality Checklist" in [⚡ TypeScript Guide](./reference/node_mcp_server.md)
|
||||
See language-specific guides for detailed testing approaches and quality checklists.
|
||||
|
||||
---
|
||||
|
||||
@@ -247,7 +156,7 @@ After implementing your MCP server, create comprehensive evaluations to test its
|
||||
|
||||
#### 4.1 Understand Evaluation Purpose
|
||||
|
||||
Evaluations test whether LLMs can effectively use your MCP server to answer realistic, complex questions.
|
||||
Use evaluations to test whether LLMs can effectively use your MCP server to answer realistic, complex questions.
|
||||
|
||||
#### 4.2 Create 10 Evaluation Questions
|
||||
|
||||
@@ -260,7 +169,7 @@ To create effective evaluations, follow the process outlined in the evaluation g
|
||||
|
||||
#### 4.3 Evaluation Requirements
|
||||
|
||||
Each question must be:
|
||||
Ensure each question is:
|
||||
- **Independent**: Not dependent on other questions
|
||||
- **Read-only**: Only non-destructive operations required
|
||||
- **Complex**: Requiring multiple tool calls and deep exploration
|
||||
@@ -291,13 +200,12 @@ Create an XML file with this structure:
|
||||
Load these resources as needed during development:
|
||||
|
||||
### Core MCP Documentation (Load First)
|
||||
- **MCP Protocol**: Fetch from `https://modelcontextprotocol.io/llms-full.txt` - Complete MCP specification
|
||||
- **MCP Protocol**: Start with sitemap at `https://modelcontextprotocol.io/sitemap.xml`, then fetch specific pages with `.md` suffix
|
||||
- [📋 MCP Best Practices](./reference/mcp_best_practices.md) - Universal MCP guidelines including:
|
||||
- Server and tool naming conventions
|
||||
- Response format guidelines (JSON vs Markdown)
|
||||
- Pagination best practices
|
||||
- Character limits and truncation strategies
|
||||
- Tool development guidelines
|
||||
- Transport selection (streamable HTTP vs stdio)
|
||||
- Security and error handling standards
|
||||
|
||||
### SDK Documentation (Load During Phase 1/2)
|
||||
|
||||
@@ -1,10 +1,4 @@
|
||||
# MCP Server Development Best Practices and Guidelines
|
||||
|
||||
## Overview
|
||||
|
||||
This document compiles essential best practices and guidelines for building Model Context Protocol (MCP) servers. It covers naming conventions, tool design, response formats, pagination, error handling, security, and compliance requirements.
|
||||
|
||||
---
|
||||
# MCP Server Best Practices
|
||||
|
||||
## Quick Reference
|
||||
|
||||
@@ -27,106 +21,77 @@ This document compiles essential best practices and guidelines for building Mode
|
||||
- Return `has_more`, `next_offset`, `total_count`
|
||||
- Default to 20-50 items
|
||||
|
||||
### Character Limits
|
||||
- Set CHARACTER_LIMIT constant (typically 25,000)
|
||||
- Truncate gracefully with clear messages
|
||||
- Provide guidance on filtering
|
||||
### Transport
|
||||
- **Streamable HTTP**: For remote servers, multi-client scenarios
|
||||
- **stdio**: For local integrations, command-line tools
|
||||
- Avoid SSE (deprecated in favor of streamable HTTP)
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
1. Server Naming Conventions
|
||||
2. Tool Naming and Design
|
||||
3. Response Format Guidelines
|
||||
4. Pagination Best Practices
|
||||
5. Character Limits and Truncation
|
||||
6. Tool Development Best Practices
|
||||
7. Transport Best Practices
|
||||
8. Testing Requirements
|
||||
9. OAuth and Security Best Practices
|
||||
10. Resource Management Best Practices
|
||||
11. Prompt Management Best Practices
|
||||
12. Error Handling Standards
|
||||
13. Documentation Requirements
|
||||
14. Compliance and Monitoring
|
||||
## Server Naming Conventions
|
||||
|
||||
---
|
||||
|
||||
## 1. Server Naming Conventions
|
||||
|
||||
Follow these standardized naming patterns for MCP servers:
|
||||
Follow these standardized naming patterns:
|
||||
|
||||
**Python**: Use format `{service}_mcp` (lowercase with underscores)
|
||||
- Examples: `slack_mcp`, `github_mcp`, `jira_mcp`, `stripe_mcp`
|
||||
- Examples: `slack_mcp`, `github_mcp`, `jira_mcp`
|
||||
|
||||
**Node/TypeScript**: Use format `{service}-mcp-server` (lowercase with hyphens)
|
||||
- Examples: `slack-mcp-server`, `github-mcp-server`, `jira-mcp-server`
|
||||
|
||||
The name should be:
|
||||
- General (not tied to specific features)
|
||||
- Descriptive of the service/API being integrated
|
||||
- Easy to infer from the task description
|
||||
- Without version numbers or dates
|
||||
The name should be general, descriptive of the service being integrated, easy to infer from the task description, and without version numbers.
|
||||
|
||||
---
|
||||
|
||||
## 2. Tool Naming and Design
|
||||
## Tool Naming and Design
|
||||
|
||||
### Tool Naming Best Practices
|
||||
### Tool Naming
|
||||
|
||||
1. **Use snake_case**: `search_users`, `create_project`, `get_channel_info`
|
||||
2. **Include service prefix**: Anticipate that your MCP server may be used alongside other MCP servers
|
||||
- Use `slack_send_message` instead of just `send_message`
|
||||
- Use `github_create_issue` instead of just `create_issue`
|
||||
- Use `asana_list_tasks` instead of just `list_tasks`
|
||||
3. **Be action-oriented**: Start with verbs (get, list, search, create, etc.)
|
||||
4. **Be specific**: Avoid generic names that could conflict with other servers
|
||||
5. **Maintain consistency**: Use consistent naming patterns within your server
|
||||
|
||||
### Tool Design Guidelines
|
||||
### Tool Design
|
||||
|
||||
- Tool descriptions must narrowly and unambiguously describe functionality
|
||||
- Descriptions must precisely match actual functionality
|
||||
- Should not create confusion with other MCP servers
|
||||
- Should provide tool annotations (readOnlyHint, destructiveHint, idempotentHint, openWorldHint)
|
||||
- Provide tool annotations (readOnlyHint, destructiveHint, idempotentHint, openWorldHint)
|
||||
- Keep tool operations focused and atomic
|
||||
|
||||
---
|
||||
|
||||
## 3. Response Format Guidelines
|
||||
## Response Formats
|
||||
|
||||
All tools that return data should support multiple formats for flexibility:
|
||||
All tools that return data should support multiple formats:
|
||||
|
||||
### JSON Format (`response_format="json"`)
|
||||
- Machine-readable structured data
|
||||
- Include all available fields and metadata
|
||||
- Consistent field names and types
|
||||
- Suitable for programmatic processing
|
||||
- Use for when LLMs need to process data further
|
||||
- Use for programmatic processing
|
||||
|
||||
### Markdown Format (`response_format="markdown"`, typically default)
|
||||
- Human-readable formatted text
|
||||
- Use headers, lists, and formatting for clarity
|
||||
- Convert timestamps to human-readable format (e.g., "2024-01-15 10:30:00 UTC" instead of epoch)
|
||||
- Show display names with IDs in parentheses (e.g., "@john.doe (U123456)")
|
||||
- Omit verbose metadata (e.g., show only one profile image URL, not all sizes)
|
||||
- Group related information logically
|
||||
- Use for when presenting information to users
|
||||
- Convert timestamps to human-readable format
|
||||
- Show display names with IDs in parentheses
|
||||
- Omit verbose metadata
|
||||
|
||||
---
|
||||
|
||||
## 4. Pagination Best Practices
|
||||
## Pagination
|
||||
|
||||
For tools that list resources:
|
||||
|
||||
- **Always respect the `limit` parameter**: Never load all results when a limit is specified
|
||||
- **Always respect the `limit` parameter**
|
||||
- **Implement pagination**: Use `offset` or cursor-based pagination
|
||||
- **Return pagination metadata**: Include `has_more`, `next_offset`/`next_cursor`, `total_count`
|
||||
- **Never load all results into memory**: Especially important for large datasets
|
||||
- **Default to reasonable limits**: 20-50 items is typical
|
||||
- **Include clear pagination info in responses**: Make it easy for LLMs to request more data
|
||||
|
||||
Example pagination response structure:
|
||||
Example pagination response:
|
||||
```json
|
||||
{
|
||||
"total": 150,
|
||||
@@ -140,776 +105,145 @@ Example pagination response structure:
|
||||
|
||||
---
|
||||
|
||||
## 5. Character Limits and Truncation
|
||||
## Transport Options
|
||||
|
||||
To prevent overwhelming responses with too much data:
|
||||
### Streamable HTTP
|
||||
|
||||
- **Define CHARACTER_LIMIT constant**: Typically 25,000 characters at module level
|
||||
- **Check response size before returning**: Measure the final response length
|
||||
- **Truncate gracefully with clear indicators**: Let the LLM know data was truncated
|
||||
- **Provide guidance on filtering**: Suggest how to use parameters to reduce results
|
||||
- **Include truncation metadata**: Show what was truncated and how to get more
|
||||
|
||||
Example truncation handling:
|
||||
```python
|
||||
CHARACTER_LIMIT = 25000
|
||||
|
||||
if len(result) > CHARACTER_LIMIT:
|
||||
truncated_data = data[:max(1, len(data) // 2)]
|
||||
response["truncated"] = True
|
||||
response["truncation_message"] = (
|
||||
f"Response truncated from {len(data)} to {len(truncated_data)} items. "
|
||||
f"Use 'offset' parameter or add filters to see more results."
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Transport Options
|
||||
|
||||
MCP servers support multiple transport mechanisms for different deployment scenarios:
|
||||
|
||||
### Stdio Transport
|
||||
|
||||
**Best for**: Command-line tools, local integrations, subprocess execution
|
||||
**Best for**: Remote servers, web services, multi-client scenarios
|
||||
|
||||
**Characteristics**:
|
||||
- Standard input/output stream communication
|
||||
- Simple setup, no network configuration needed
|
||||
- Runs as a subprocess of the client
|
||||
- Ideal for desktop applications and CLI tools
|
||||
|
||||
**Use when**:
|
||||
- Building tools for local development environments
|
||||
- Integrating with desktop applications (e.g., Claude Desktop)
|
||||
- Creating command-line utilities
|
||||
- Single-user, single-session scenarios
|
||||
|
||||
### HTTP Transport
|
||||
|
||||
**Best for**: Web services, remote access, multi-client scenarios
|
||||
|
||||
**Characteristics**:
|
||||
- Request-response pattern over HTTP
|
||||
- Bidirectional communication over HTTP
|
||||
- Supports multiple simultaneous clients
|
||||
- Can be deployed as a web service
|
||||
- Requires network configuration and security considerations
|
||||
- Enables server-to-client notifications
|
||||
|
||||
**Use when**:
|
||||
- Serving multiple clients simultaneously
|
||||
- Deploying as a cloud service
|
||||
- Integration with web applications
|
||||
- Need for load balancing or scaling
|
||||
|
||||
### Server-Sent Events (SSE) Transport
|
||||
### stdio
|
||||
|
||||
**Best for**: Real-time updates, push notifications, streaming data
|
||||
**Best for**: Local integrations, command-line tools
|
||||
|
||||
**Characteristics**:
|
||||
- One-way server-to-client streaming over HTTP
|
||||
- Enables real-time updates without polling
|
||||
- Long-lived connections for continuous data flow
|
||||
- Built on standard HTTP infrastructure
|
||||
- Standard input/output stream communication
|
||||
- Simple setup, no network configuration needed
|
||||
- Runs as a subprocess of the client
|
||||
|
||||
**Use when**:
|
||||
- Clients need real-time data updates
|
||||
- Implementing push notifications
|
||||
- Streaming logs or monitoring data
|
||||
- Progressive result delivery for long operations
|
||||
- Building tools for local development environments
|
||||
- Integrating with desktop applications
|
||||
- Single-user, single-session scenarios
|
||||
|
||||
### Transport Selection Criteria
|
||||
**Note**: stdio servers should NOT log to stdout (use stderr for logging)
|
||||
|
||||
| Criterion | Stdio | HTTP | SSE |
|
||||
|-----------|-------|------|-----|
|
||||
| **Deployment** | Local | Remote | Remote |
|
||||
| **Clients** | Single | Multiple | Multiple |
|
||||
| **Communication** | Bidirectional | Request-Response | Server-Push |
|
||||
| **Complexity** | Low | Medium | Medium-High |
|
||||
| **Real-time** | No | No | Yes |
|
||||
### Transport Selection
|
||||
|
||||
| Criterion | stdio | Streamable HTTP |
|
||||
|-----------|-------|-----------------|
|
||||
| **Deployment** | Local | Remote |
|
||||
| **Clients** | Single | Multiple |
|
||||
| **Complexity** | Low | Medium |
|
||||
| **Real-time** | No | Yes |
|
||||
|
||||
---
|
||||
|
||||
## 7. Tool Development Best Practices
|
||||
|
||||
### General Guidelines
|
||||
1. Tool names should be descriptive and action-oriented
|
||||
2. Use parameter validation with detailed JSON schemas
|
||||
3. Include examples in tool descriptions
|
||||
4. Implement proper error handling and validation
|
||||
5. Use progress reporting for long operations
|
||||
6. Keep tool operations focused and atomic
|
||||
7. Document expected return value structures
|
||||
8. Implement proper timeouts
|
||||
9. Consider rate limiting for resource-intensive operations
|
||||
10. Log tool usage for debugging and monitoring
|
||||
|
||||
### Security Considerations for Tools
|
||||
|
||||
#### Input Validation
|
||||
- Validate all parameters against schema
|
||||
- Sanitize file paths and system commands
|
||||
- Validate URLs and external identifiers
|
||||
- Check parameter sizes and ranges
|
||||
- Prevent command injection
|
||||
|
||||
#### Access Control
|
||||
- Implement authentication where needed
|
||||
- Use appropriate authorization checks
|
||||
- Audit tool usage
|
||||
- Rate limit requests
|
||||
- Monitor for abuse
|
||||
|
||||
#### Error Handling
|
||||
- Don't expose internal errors to clients
|
||||
- Log security-relevant errors
|
||||
- Handle timeouts appropriately
|
||||
- Clean up resources after errors
|
||||
- Validate return values
|
||||
|
||||
### Tool Annotations
|
||||
- Provide readOnlyHint and destructiveHint annotations
|
||||
- Remember annotations are hints, not security guarantees
|
||||
- Clients should not make security-critical decisions based solely on annotations
|
||||
|
||||
---
|
||||
|
||||
## 8. Transport Best Practices
|
||||
|
||||
### General Transport Guidelines
|
||||
1. Handle connection lifecycle properly
|
||||
2. Implement proper error handling
|
||||
3. Use appropriate timeout values
|
||||
4. Implement connection state management
|
||||
5. Clean up resources on disconnection
|
||||
|
||||
### Security Best Practices for Transport
|
||||
- Follow security considerations for DNS rebinding attacks
|
||||
- Implement proper authentication mechanisms
|
||||
- Validate message formats
|
||||
- Handle malformed messages gracefully
|
||||
|
||||
### Stdio Transport Specific
|
||||
- Local MCP servers should NOT log to stdout (interferes with protocol)
|
||||
- Use stderr for logging messages
|
||||
- Handle standard I/O streams properly
|
||||
|
||||
---
|
||||
|
||||
## 9. Testing Requirements
|
||||
|
||||
A comprehensive testing strategy should cover:
|
||||
|
||||
### Functional Testing
|
||||
- Verify correct execution with valid/invalid inputs
|
||||
|
||||
### Integration Testing
|
||||
- Test interaction with external systems
|
||||
|
||||
### Security Testing
|
||||
- Validate auth, input sanitization, rate limiting
|
||||
|
||||
### Performance Testing
|
||||
- Check behavior under load, timeouts
|
||||
|
||||
### Error Handling
|
||||
- Ensure proper error reporting and cleanup
|
||||
|
||||
---
|
||||
|
||||
## 10. OAuth and Security Best Practices
|
||||
## Security Best Practices
|
||||
|
||||
### Authentication and Authorization
|
||||
|
||||
MCP servers that connect to external services should implement proper authentication:
|
||||
|
||||
**OAuth 2.1 Implementation:**
|
||||
**OAuth 2.1**:
|
||||
- Use secure OAuth 2.1 with certificates from recognized authorities
|
||||
- Validate access tokens before processing requests
|
||||
- Only accept tokens specifically intended for your server
|
||||
- Reject tokens without proper audience claims
|
||||
- Never pass through tokens received from MCP clients
|
||||
|
||||
**API Key Management:**
|
||||
**API Keys**:
|
||||
- Store API keys in environment variables, never in code
|
||||
- Validate keys on server startup
|
||||
- Provide clear error messages when authentication fails
|
||||
- Use secure transmission for sensitive credentials
|
||||
|
||||
### Input Validation and Security
|
||||
### Input Validation
|
||||
|
||||
**Always validate inputs:**
|
||||
- Sanitize file paths to prevent directory traversal
|
||||
- Validate URLs and external identifiers
|
||||
- Check parameter sizes and ranges
|
||||
- Prevent command injection in system calls
|
||||
- Use schema validation (Pydantic/Zod) for all inputs
|
||||
|
||||
**Error handling security:**
|
||||
### Error Handling
|
||||
|
||||
- Don't expose internal errors to clients
|
||||
- Log security-relevant errors server-side
|
||||
- Provide helpful but not revealing error messages
|
||||
- Clean up resources after errors
|
||||
|
||||
### Privacy and Data Protection
|
||||
### DNS Rebinding Protection
|
||||
|
||||
**Data collection principles:**
|
||||
- Only collect data strictly necessary for functionality
|
||||
- Don't collect extraneous conversation data
|
||||
- Don't collect PII unless explicitly required for the tool's purpose
|
||||
- Provide clear information about what data is accessed
|
||||
|
||||
**Data transmission:**
|
||||
- Don't send data to servers outside your organization without disclosure
|
||||
- Use secure transmission (HTTPS) for all network communication
|
||||
- Validate certificates for external services
|
||||
For streamable HTTP servers running locally:
|
||||
- Enable DNS rebinding protection
|
||||
- Validate the `Origin` header on all incoming connections
|
||||
- Bind to `127.0.0.1` rather than `0.0.0.0`
|
||||
|
||||
---
|
||||
|
||||
## 11. Resource Management Best Practices
|
||||
## Tool Annotations
|
||||
|
||||
1. Only suggest necessary resources
|
||||
2. Use clear, descriptive names for roots
|
||||
3. Handle resource boundaries properly
|
||||
4. Respect client control over resources
|
||||
5. Use model-controlled primitives (tools) for automatic data exposure
|
||||
Provide annotations to help clients understand tool behavior:
|
||||
|
||||
| Annotation | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `readOnlyHint` | boolean | false | Tool does not modify its environment |
|
||||
| `destructiveHint` | boolean | true | Tool may perform destructive updates |
|
||||
| `idempotentHint` | boolean | false | Repeated calls with same args have no additional effect |
|
||||
| `openWorldHint` | boolean | true | Tool interacts with external entities |
|
||||
|
||||
**Important**: Annotations are hints, not security guarantees. Clients should not make security-critical decisions based solely on annotations.
|
||||
|
||||
---
|
||||
|
||||
## 12. Prompt Management Best Practices
|
||||
|
||||
- Clients should show users proposed prompts
|
||||
- Users should be able to modify or reject prompts
|
||||
- Clients should show users completions
|
||||
- Users should be able to modify or reject completions
|
||||
- Consider costs when using sampling
|
||||
|
||||
---
|
||||
|
||||
## 13. Error Handling Standards
|
||||
## Error Handling
|
||||
|
||||
- Use standard JSON-RPC error codes
|
||||
- Report tool errors within result objects (not protocol-level)
|
||||
- Provide helpful, specific error messages
|
||||
- Report tool errors within result objects (not protocol-level errors)
|
||||
- Provide helpful, specific error messages with suggested next steps
|
||||
- Don't expose internal implementation details
|
||||
- Clean up resources properly on errors
|
||||
|
||||
Example error handling:
|
||||
```typescript
|
||||
try {
|
||||
const result = performOperation();
|
||||
return { content: [{ type: "text", text: result }] };
|
||||
} catch (error) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [{
|
||||
type: "text",
|
||||
text: `Error: ${error.message}. Try using filter='active_only' to reduce results.`
|
||||
}]
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 14. Documentation Requirements
|
||||
## Testing Requirements
|
||||
|
||||
Comprehensive testing should cover:
|
||||
|
||||
- **Functional testing**: Verify correct execution with valid/invalid inputs
|
||||
- **Integration testing**: Test interaction with external systems
|
||||
- **Security testing**: Validate auth, input sanitization, rate limiting
|
||||
- **Performance testing**: Check behavior under load, timeouts
|
||||
- **Error handling**: Ensure proper error reporting and cleanup
|
||||
|
||||
---
|
||||
|
||||
## Documentation Requirements
|
||||
|
||||
- Provide clear documentation of all tools and capabilities
|
||||
- Include working examples (at least 3 per major feature)
|
||||
- Document security considerations
|
||||
- Specify required permissions and access levels
|
||||
- Document rate limits and performance characteristics
|
||||
|
||||
---
|
||||
|
||||
## 15. Compliance and Monitoring
|
||||
|
||||
- Implement logging for debugging and monitoring
|
||||
- Track tool usage patterns
|
||||
- Monitor for potential abuse
|
||||
- Maintain audit trails for security-relevant operations
|
||||
- Be prepared for ongoing compliance reviews
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
These best practices represent the comprehensive guidelines for building secure, efficient, and compliant MCP servers that work well within the ecosystem. Developers should follow these guidelines to ensure their MCP servers meet the standards for inclusion in the MCP directory and provide a safe, reliable experience for users.
|
||||
|
||||
|
||||
----------
|
||||
|
||||
|
||||
# Tools
|
||||
|
||||
> Enable LLMs to perform actions through your server
|
||||
|
||||
Tools are a powerful primitive in the Model Context Protocol (MCP) that enable servers to expose executable functionality to clients. Through tools, LLMs can interact with external systems, perform computations, and take actions in the real world.
|
||||
|
||||
<Note>
|
||||
Tools are designed to be **model-controlled**, meaning that tools are exposed from servers to clients with the intention of the AI model being able to automatically invoke them (with a human in the loop to grant approval).
|
||||
</Note>
|
||||
|
||||
## Overview
|
||||
|
||||
Tools in MCP allow servers to expose executable functions that can be invoked by clients and used by LLMs to perform actions. Key aspects of tools include:
|
||||
|
||||
* **Discovery**: Clients can obtain a list of available tools by sending a `tools/list` request
|
||||
* **Invocation**: Tools are called using the `tools/call` request, where servers perform the requested operation and return results
|
||||
* **Flexibility**: Tools can range from simple calculations to complex API interactions
|
||||
|
||||
Like [resources](/docs/concepts/resources), tools are identified by unique names and can include descriptions to guide their usage. However, unlike resources, tools represent dynamic operations that can modify state or interact with external systems.
|
||||
|
||||
## Tool definition structure
|
||||
|
||||
Each tool is defined with the following structure:
|
||||
|
||||
```typescript
|
||||
{
|
||||
name: string; // Unique identifier for the tool
|
||||
description?: string; // Human-readable description
|
||||
inputSchema: { // JSON Schema for the tool's parameters
|
||||
type: "object",
|
||||
properties: { ... } // Tool-specific parameters
|
||||
},
|
||||
annotations?: { // Optional hints about tool behavior
|
||||
title?: string; // Human-readable title for the tool
|
||||
readOnlyHint?: boolean; // If true, the tool does not modify its environment
|
||||
destructiveHint?: boolean; // If true, the tool may perform destructive updates
|
||||
idempotentHint?: boolean; // If true, repeated calls with same args have no additional effect
|
||||
openWorldHint?: boolean; // If true, tool interacts with external entities
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Implementing tools
|
||||
|
||||
Here's an example of implementing a basic tool in an MCP server:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="TypeScript">
|
||||
```typescript
|
||||
const server = new Server({
|
||||
name: "example-server",
|
||||
version: "1.0.0"
|
||||
}, {
|
||||
capabilities: {
|
||||
tools: {}
|
||||
}
|
||||
});
|
||||
|
||||
// Define available tools
|
||||
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
||||
return {
|
||||
tools: [{
|
||||
name: "calculate_sum",
|
||||
description: "Add two numbers together",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: { type: "number" },
|
||||
b: { type: "number" }
|
||||
},
|
||||
required: ["a", "b"]
|
||||
}
|
||||
}]
|
||||
};
|
||||
});
|
||||
|
||||
// Handle tool execution
|
||||
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
||||
if (request.params.name === "calculate_sum") {
|
||||
const { a, b } = request.params.arguments;
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: String(a + b)
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
throw new Error("Tool not found");
|
||||
});
|
||||
```
|
||||
</Tab>
|
||||
|
||||
<Tab title="Python">
|
||||
```python
|
||||
app = Server("example-server")
|
||||
|
||||
@app.list_tools()
|
||||
async def list_tools() -> list[types.Tool]:
|
||||
return [
|
||||
types.Tool(
|
||||
name="calculate_sum",
|
||||
description="Add two numbers together",
|
||||
inputSchema={
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"a": {"type": "number"},
|
||||
"b": {"type": "number"}
|
||||
},
|
||||
"required": ["a", "b"]
|
||||
}
|
||||
)
|
||||
]
|
||||
|
||||
@app.call_tool()
|
||||
async def call_tool(
|
||||
name: str,
|
||||
arguments: dict
|
||||
) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
|
||||
if name == "calculate_sum":
|
||||
a = arguments["a"]
|
||||
b = arguments["b"]
|
||||
result = a + b
|
||||
return [types.TextContent(type="text", text=str(result))]
|
||||
raise ValueError(f"Tool not found: {name}")
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Example tool patterns
|
||||
|
||||
Here are some examples of types of tools that a server could provide:
|
||||
|
||||
### System operations
|
||||
|
||||
Tools that interact with the local system:
|
||||
|
||||
```typescript
|
||||
{
|
||||
name: "execute_command",
|
||||
description: "Run a shell command",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
command: { type: "string" },
|
||||
args: { type: "array", items: { type: "string" } }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### API integrations
|
||||
|
||||
Tools that wrap external APIs:
|
||||
|
||||
```typescript
|
||||
{
|
||||
name: "github_create_issue",
|
||||
description: "Create a GitHub issue",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
title: { type: "string" },
|
||||
body: { type: "string" },
|
||||
labels: { type: "array", items: { type: "string" } }
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Data processing
|
||||
|
||||
Tools that transform or analyze data:
|
||||
|
||||
```typescript
|
||||
{
|
||||
name: "analyze_csv",
|
||||
description: "Analyze a CSV file",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
filepath: { type: "string" },
|
||||
operations: {
|
||||
type: "array",
|
||||
items: {
|
||||
enum: ["sum", "average", "count"]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Best practices
|
||||
|
||||
When implementing tools:
|
||||
|
||||
1. Provide clear, descriptive names and descriptions
|
||||
2. Use detailed JSON Schema definitions for parameters
|
||||
3. Include examples in tool descriptions to demonstrate how the model should use them
|
||||
4. Implement proper error handling and validation
|
||||
5. Use progress reporting for long operations
|
||||
6. Keep tool operations focused and atomic
|
||||
7. Document expected return value structures
|
||||
8. Implement proper timeouts
|
||||
9. Consider rate limiting for resource-intensive operations
|
||||
10. Log tool usage for debugging and monitoring
|
||||
|
||||
### Tool name conflicts
|
||||
|
||||
MCP client applications and MCP server proxies may encounter tool name conflicts when building their own tool lists. For example, two connected MCP servers `web1` and `web2` may both expose a tool named `search_web`.
|
||||
|
||||
Applications may disambiguiate tools with one of the following strategies (among others; not an exhaustive list):
|
||||
|
||||
* Concatenating a unique, user-defined server name with the tool name, e.g. `web1___search_web` and `web2___search_web`. This strategy may be preferable when unique server names are already provided by the user in a configuration file.
|
||||
* Generating a random prefix for the tool name, e.g. `jrwxs___search_web` and `6cq52___search_web`. This strategy may be preferable in server proxies where user-defined unique names are not available.
|
||||
* Using the server URI as a prefix for the tool name, e.g. `web1.example.com:search_web` and `web2.example.com:search_web`. This strategy may be suitable when working with remote MCP servers.
|
||||
|
||||
Note that the server-provided name from the initialization flow is not guaranteed to be unique and is not generally suitable for disambiguation purposes.
|
||||
|
||||
## Security considerations
|
||||
|
||||
When exposing tools:
|
||||
|
||||
### Input validation
|
||||
|
||||
* Validate all parameters against the schema
|
||||
* Sanitize file paths and system commands
|
||||
* Validate URLs and external identifiers
|
||||
* Check parameter sizes and ranges
|
||||
* Prevent command injection
|
||||
|
||||
### Access control
|
||||
|
||||
* Implement authentication where needed
|
||||
* Use appropriate authorization checks
|
||||
* Audit tool usage
|
||||
* Rate limit requests
|
||||
* Monitor for abuse
|
||||
|
||||
### Error handling
|
||||
|
||||
* Don't expose internal errors to clients
|
||||
* Log security-relevant errors
|
||||
* Handle timeouts appropriately
|
||||
* Clean up resources after errors
|
||||
* Validate return values
|
||||
|
||||
## Tool discovery and updates
|
||||
|
||||
MCP supports dynamic tool discovery:
|
||||
|
||||
1. Clients can list available tools at any time
|
||||
2. Servers can notify clients when tools change using `notifications/tools/list_changed`
|
||||
3. Tools can be added or removed during runtime
|
||||
4. Tool definitions can be updated (though this should be done carefully)
|
||||
|
||||
## Error handling
|
||||
|
||||
Tool errors should be reported within the result object, not as MCP protocol-level errors. This allows the LLM to see and potentially handle the error. When a tool encounters an error:
|
||||
|
||||
1. Set `isError` to `true` in the result
|
||||
2. Include error details in the `content` array
|
||||
|
||||
Here's an example of proper error handling for tools:
|
||||
|
||||
<Tabs>
|
||||
<Tab title="TypeScript">
|
||||
```typescript
|
||||
try {
|
||||
// Tool operation
|
||||
const result = performOperation();
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Operation successful: ${result}`
|
||||
}
|
||||
]
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
isError: true,
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: `Error: ${error.message}`
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
```
|
||||
</Tab>
|
||||
|
||||
<Tab title="Python">
|
||||
```python
|
||||
try:
|
||||
# Tool operation
|
||||
result = perform_operation()
|
||||
return types.CallToolResult(
|
||||
content=[
|
||||
types.TextContent(
|
||||
type="text",
|
||||
text=f"Operation successful: {result}"
|
||||
)
|
||||
]
|
||||
)
|
||||
except Exception as error:
|
||||
return types.CallToolResult(
|
||||
isError=True,
|
||||
content=[
|
||||
types.TextContent(
|
||||
type="text",
|
||||
text=f"Error: {str(error)}"
|
||||
)
|
||||
]
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
This approach allows the LLM to see that an error occurred and potentially take corrective action or request human intervention.
|
||||
|
||||
## Tool annotations
|
||||
|
||||
Tool annotations provide additional metadata about a tool's behavior, helping clients understand how to present and manage tools. These annotations are hints that describe the nature and impact of a tool, but should not be relied upon for security decisions.
|
||||
|
||||
### Purpose of tool annotations
|
||||
|
||||
Tool annotations serve several key purposes:
|
||||
|
||||
1. Provide UX-specific information without affecting model context
|
||||
2. Help clients categorize and present tools appropriately
|
||||
3. Convey information about a tool's potential side effects
|
||||
4. Assist in developing intuitive interfaces for tool approval
|
||||
|
||||
### Available tool annotations
|
||||
|
||||
The MCP specification defines the following annotations for tools:
|
||||
|
||||
| Annotation | Type | Default | Description |
|
||||
| ----------------- | ------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `title` | string | - | A human-readable title for the tool, useful for UI display |
|
||||
| `readOnlyHint` | boolean | false | If true, indicates the tool does not modify its environment |
|
||||
| `destructiveHint` | boolean | true | If true, the tool may perform destructive updates (only meaningful when `readOnlyHint` is false) |
|
||||
| `idempotentHint` | boolean | false | If true, calling the tool repeatedly with the same arguments has no additional effect (only meaningful when `readOnlyHint` is false) |
|
||||
| `openWorldHint` | boolean | true | If true, the tool may interact with an "open world" of external entities |
|
||||
|
||||
### Example usage
|
||||
|
||||
Here's how to define tools with annotations for different scenarios:
|
||||
|
||||
```typescript
|
||||
// A read-only search tool
|
||||
{
|
||||
name: "web_search",
|
||||
description: "Search the web for information",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
query: { type: "string" }
|
||||
},
|
||||
required: ["query"]
|
||||
},
|
||||
annotations: {
|
||||
title: "Web Search",
|
||||
readOnlyHint: true,
|
||||
openWorldHint: true
|
||||
}
|
||||
}
|
||||
|
||||
// A destructive file deletion tool
|
||||
{
|
||||
name: "delete_file",
|
||||
description: "Delete a file from the filesystem",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
path: { type: "string" }
|
||||
},
|
||||
required: ["path"]
|
||||
},
|
||||
annotations: {
|
||||
title: "Delete File",
|
||||
readOnlyHint: false,
|
||||
destructiveHint: true,
|
||||
idempotentHint: true,
|
||||
openWorldHint: false
|
||||
}
|
||||
}
|
||||
|
||||
// A non-destructive database record creation tool
|
||||
{
|
||||
name: "create_record",
|
||||
description: "Create a new record in the database",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
table: { type: "string" },
|
||||
data: { type: "object" }
|
||||
},
|
||||
required: ["table", "data"]
|
||||
},
|
||||
annotations: {
|
||||
title: "Create Database Record",
|
||||
readOnlyHint: false,
|
||||
destructiveHint: false,
|
||||
idempotentHint: false,
|
||||
openWorldHint: false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Integrating annotations in server implementation
|
||||
|
||||
<Tabs>
|
||||
<Tab title="TypeScript">
|
||||
```typescript
|
||||
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
||||
return {
|
||||
tools: [{
|
||||
name: "calculate_sum",
|
||||
description: "Add two numbers together",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: { type: "number" },
|
||||
b: { type: "number" }
|
||||
},
|
||||
required: ["a", "b"]
|
||||
},
|
||||
annotations: {
|
||||
title: "Calculate Sum",
|
||||
readOnlyHint: true,
|
||||
openWorldHint: false
|
||||
}
|
||||
}]
|
||||
};
|
||||
});
|
||||
```
|
||||
</Tab>
|
||||
|
||||
<Tab title="Python">
|
||||
```python
|
||||
from mcp.server.fastmcp import FastMCP
|
||||
|
||||
mcp = FastMCP("example-server")
|
||||
|
||||
@mcp.tool(
|
||||
annotations={
|
||||
"title": "Calculate Sum",
|
||||
"readOnlyHint": True,
|
||||
"openWorldHint": False
|
||||
}
|
||||
)
|
||||
async def calculate_sum(a: float, b: float) -> str:
|
||||
"""Add two numbers together.
|
||||
|
||||
Args:
|
||||
a: First number to add
|
||||
b: Second number to add
|
||||
"""
|
||||
result = a + b
|
||||
return str(result)
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Best practices for tool annotations
|
||||
|
||||
1. **Be accurate about side effects**: Clearly indicate whether a tool modifies its environment and whether those modifications are destructive.
|
||||
|
||||
2. **Use descriptive titles**: Provide human-friendly titles that clearly describe the tool's purpose.
|
||||
|
||||
3. **Indicate idempotency properly**: Mark tools as idempotent only if repeated calls with the same arguments truly have no additional effect.
|
||||
|
||||
4. **Set appropriate open/closed world hints**: Indicate whether a tool interacts with a closed system (like a database) or an open system (like the web).
|
||||
|
||||
5. **Remember annotations are hints**: All properties in ToolAnnotations are hints and not guaranteed to provide a faithful description of tool behavior. Clients should never make security-critical decisions based solely on annotations.
|
||||
|
||||
## Testing tools
|
||||
|
||||
A comprehensive testing strategy for MCP tools should cover:
|
||||
|
||||
* **Functional testing**: Verify tools execute correctly with valid inputs and handle invalid inputs appropriately
|
||||
* **Integration testing**: Test tool interaction with external systems using both real and mocked dependencies
|
||||
* **Security testing**: Validate authentication, authorization, input sanitization, and rate limiting
|
||||
* **Performance testing**: Check behavior under load, timeout handling, and resource cleanup
|
||||
* **Error handling**: Ensure tools properly report errors through the MCP protocol and clean up resources
|
||||
|
||||
@@ -11,9 +11,10 @@ This document provides Node/TypeScript-specific best practices and examples for
|
||||
### Key Imports
|
||||
```typescript
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||
import express from "express";
|
||||
import { z } from "zod";
|
||||
import axios, { AxiosError } from "axios";
|
||||
```
|
||||
|
||||
### Server Initialization
|
||||
@@ -26,9 +27,22 @@ const server = new McpServer({
|
||||
|
||||
### Tool Registration Pattern
|
||||
```typescript
|
||||
server.registerTool("tool_name", {...config}, async (params) => {
|
||||
// Implementation
|
||||
});
|
||||
server.registerTool(
|
||||
"tool_name",
|
||||
{
|
||||
title: "Tool Display Name",
|
||||
description: "What the tool does",
|
||||
inputSchema: { param: z.string() },
|
||||
outputSchema: { result: z.string() }
|
||||
},
|
||||
async ({ param }) => {
|
||||
const output = { result: `Processed: ${param}` };
|
||||
return {
|
||||
content: [{ type: "text", text: JSON.stringify(output) }],
|
||||
structuredContent: output // Modern pattern for structured data
|
||||
};
|
||||
}
|
||||
);
|
||||
```
|
||||
|
||||
---
|
||||
@@ -41,6 +55,11 @@ The official MCP TypeScript SDK provides:
|
||||
- Zod schema integration for runtime input validation
|
||||
- Type-safe tool handler implementations
|
||||
|
||||
**IMPORTANT - Use Modern APIs Only:**
|
||||
- **DO use**: `server.registerTool()`, `server.registerResource()`, `server.registerPrompt()`
|
||||
- **DO NOT use**: Old deprecated APIs such as `server.tool()`, `server.setRequestHandler(ListToolsRequestSchema, ...)`, or manual handler registration
|
||||
- The `register*` methods provide better type safety, automatic schema handling, and are the recommended approach
|
||||
|
||||
See the MCP SDK documentation in the references for complete details.
|
||||
|
||||
## Server Naming Convention
|
||||
@@ -204,55 +223,43 @@ Error Handling:
|
||||
};
|
||||
}
|
||||
|
||||
// Format response based on requested format
|
||||
let result: string;
|
||||
// Prepare structured output
|
||||
const output = {
|
||||
total,
|
||||
count: users.length,
|
||||
offset: params.offset,
|
||||
users: users.map((user: any) => ({
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
...(user.team ? { team: user.team } : {}),
|
||||
active: user.active ?? true
|
||||
})),
|
||||
has_more: total > params.offset + users.length,
|
||||
...(total > params.offset + users.length ? {
|
||||
next_offset: params.offset + users.length
|
||||
} : {})
|
||||
};
|
||||
|
||||
// Format text representation based on requested format
|
||||
let textContent: string;
|
||||
if (params.response_format === ResponseFormat.MARKDOWN) {
|
||||
// Human-readable markdown format
|
||||
const lines: string[] = [`# User Search Results: '${params.query}'`, ""];
|
||||
lines.push(`Found ${total} users (showing ${users.length})`);
|
||||
lines.push("");
|
||||
|
||||
const lines = [`# User Search Results: '${params.query}'`, "",
|
||||
`Found ${total} users (showing ${users.length})`, ""];
|
||||
for (const user of users) {
|
||||
lines.push(`## ${user.name} (${user.id})`);
|
||||
lines.push(`- **Email**: ${user.email}`);
|
||||
if (user.team) {
|
||||
lines.push(`- **Team**: ${user.team}`);
|
||||
}
|
||||
if (user.team) lines.push(`- **Team**: ${user.team}`);
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
result = lines.join("\n");
|
||||
|
||||
textContent = lines.join("\n");
|
||||
} else {
|
||||
// Machine-readable JSON format
|
||||
const response: any = {
|
||||
total,
|
||||
count: users.length,
|
||||
offset: params.offset,
|
||||
users: users.map((user: any) => ({
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
...(user.team ? { team: user.team } : {}),
|
||||
active: user.active ?? true
|
||||
}))
|
||||
};
|
||||
|
||||
// Add pagination info if there are more results
|
||||
if (total > params.offset + users.length) {
|
||||
response.has_more = true;
|
||||
response.next_offset = params.offset + users.length;
|
||||
}
|
||||
|
||||
result = JSON.stringify(response, null, 2);
|
||||
textContent = JSON.stringify(output, null, 2);
|
||||
}
|
||||
|
||||
return {
|
||||
content: [{
|
||||
type: "text",
|
||||
text: result
|
||||
}]
|
||||
content: [{ type: "text", text: textContent }],
|
||||
structuredContent: output // Modern pattern for structured data
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
@@ -695,27 +702,57 @@ server.registerTool(
|
||||
);
|
||||
|
||||
// Main function
|
||||
async function main() {
|
||||
// Verify environment variables if needed
|
||||
// For stdio (local):
|
||||
async function runStdio() {
|
||||
if (!process.env.EXAMPLE_API_KEY) {
|
||||
console.error("ERROR: EXAMPLE_API_KEY environment variable is required");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Create transport
|
||||
const transport = new StdioServerTransport();
|
||||
|
||||
// Connect server to transport
|
||||
await server.connect(transport);
|
||||
|
||||
console.error("Example MCP server running via stdio");
|
||||
console.error("MCP server running via stdio");
|
||||
}
|
||||
|
||||
// Run the server
|
||||
main().catch((error) => {
|
||||
console.error("Server error:", error);
|
||||
process.exit(1);
|
||||
});
|
||||
// For streamable HTTP (remote):
|
||||
async function runHTTP() {
|
||||
if (!process.env.EXAMPLE_API_KEY) {
|
||||
console.error("ERROR: EXAMPLE_API_KEY environment variable is required");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
|
||||
app.post('/mcp', async (req, res) => {
|
||||
const transport = new StreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined,
|
||||
enableJsonResponse: true
|
||||
});
|
||||
res.on('close', () => transport.close());
|
||||
await server.connect(transport);
|
||||
await transport.handleRequest(req, res, req.body);
|
||||
});
|
||||
|
||||
const port = parseInt(process.env.PORT || '3000');
|
||||
app.listen(port, () => {
|
||||
console.error(`MCP server running on http://localhost:${port}/mcp`);
|
||||
});
|
||||
}
|
||||
|
||||
// Choose transport based on environment
|
||||
const transport = process.env.TRANSPORT || 'stdio';
|
||||
if (transport === 'http') {
|
||||
runHTTP().catch(error => {
|
||||
console.error("Server error:", error);
|
||||
process.exit(1);
|
||||
});
|
||||
} else {
|
||||
runStdio().catch(error => {
|
||||
console.error("Server error:", error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
@@ -777,30 +814,47 @@ server.registerResourceList(async () => {
|
||||
- **Resources**: When data is relatively static or template-based
|
||||
- **Tools**: When operations have side effects or complex workflows
|
||||
|
||||
### Multiple Transport Options
|
||||
### Transport Options
|
||||
|
||||
The TypeScript SDK supports different transport mechanisms:
|
||||
The TypeScript SDK supports two main transport mechanisms:
|
||||
|
||||
#### Streamable HTTP (Recommended for Remote Servers)
|
||||
|
||||
```typescript
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
import express from "express";
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
|
||||
app.post('/mcp', async (req, res) => {
|
||||
// Create new transport for each request (stateless, prevents request ID collisions)
|
||||
const transport = new StreamableHTTPServerTransport({
|
||||
sessionIdGenerator: undefined,
|
||||
enableJsonResponse: true
|
||||
});
|
||||
|
||||
res.on('close', () => transport.close());
|
||||
|
||||
await server.connect(transport);
|
||||
await transport.handleRequest(req, res, req.body);
|
||||
});
|
||||
|
||||
app.listen(3000);
|
||||
```
|
||||
|
||||
#### stdio (For Local Integrations)
|
||||
|
||||
```typescript
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
||||
|
||||
// Stdio transport (default - for CLI tools)
|
||||
const stdioTransport = new StdioServerTransport();
|
||||
await server.connect(stdioTransport);
|
||||
|
||||
// SSE transport (for real-time web updates)
|
||||
const sseTransport = new SSEServerTransport("/message", response);
|
||||
await server.connect(sseTransport);
|
||||
|
||||
// HTTP transport (for web services)
|
||||
// Configure based on your HTTP framework integration
|
||||
const transport = new StdioServerTransport();
|
||||
await server.connect(transport);
|
||||
```
|
||||
|
||||
**Transport selection guide:**
|
||||
- **Stdio**: Command-line tools, subprocess integration, local development
|
||||
- **HTTP**: Web services, remote access, multiple simultaneous clients
|
||||
- **SSE**: Real-time updates, server-push notifications, web dashboards
|
||||
**Transport selection:**
|
||||
- **Streamable HTTP**: Web services, remote access, multiple clients
|
||||
- **stdio**: Command-line tools, local development, subprocess integration
|
||||
|
||||
### Notification Support
|
||||
|
||||
@@ -889,7 +943,7 @@ Before finalizing your Node/TypeScript MCP server implementation, ensure:
|
||||
|
||||
### Advanced Features (where applicable)
|
||||
- [ ] Resources registered for appropriate data endpoints
|
||||
- [ ] Appropriate transport configured (stdio, HTTP, SSE)
|
||||
- [ ] Appropriate transport configured (stdio or streamable HTTP)
|
||||
- [ ] Notifications implemented for dynamic server capabilities
|
||||
- [ ] Type-safe with SDK interfaces
|
||||
|
||||
|
||||
@@ -204,32 +204,6 @@ async def list_items(params: ListInput) -> str:
|
||||
return json.dumps(response, indent=2)
|
||||
```
|
||||
|
||||
## Character Limits and Truncation
|
||||
|
||||
Add a CHARACTER_LIMIT constant to prevent overwhelming responses:
|
||||
|
||||
```python
|
||||
# At module level
|
||||
CHARACTER_LIMIT = 25000 # Maximum response size in characters
|
||||
|
||||
async def search_tool(params: SearchInput) -> str:
|
||||
result = generate_response(data)
|
||||
|
||||
# Check character limit and truncate if needed
|
||||
if len(result) > CHARACTER_LIMIT:
|
||||
# Truncate data and add notice
|
||||
truncated_data = data[:max(1, len(data) // 2)]
|
||||
response["data"] = truncated_data
|
||||
response["truncated"] = True
|
||||
response["truncation_message"] = (
|
||||
f"Response truncated from {len(data)} to {len(truncated_data)} items. "
|
||||
f"Use 'offset' parameter or add filters to see more results."
|
||||
)
|
||||
result = json.dumps(response, indent=2)
|
||||
|
||||
return result
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
Provide clear, actionable error messages:
|
||||
@@ -377,7 +351,6 @@ mcp = FastMCP("example_mcp")
|
||||
|
||||
# Constants
|
||||
API_BASE_URL = "https://api.example.com/v1"
|
||||
CHARACTER_LIMIT = 25000 # Maximum response size in characters
|
||||
|
||||
# Enums
|
||||
class ResponseFormat(str, Enum):
|
||||
@@ -643,28 +616,23 @@ async def query_data(query: str, ctx: Context) -> str:
|
||||
return format_results(results)
|
||||
```
|
||||
|
||||
### Multiple Transport Options
|
||||
### Transport Options
|
||||
|
||||
FastMCP supports different transport mechanisms:
|
||||
FastMCP supports two main transport mechanisms:
|
||||
|
||||
```python
|
||||
# Default: Stdio transport (for CLI tools)
|
||||
# stdio transport (for local tools) - default
|
||||
if __name__ == "__main__":
|
||||
mcp.run()
|
||||
|
||||
# HTTP transport (for web services)
|
||||
# Streamable HTTP transport (for remote servers)
|
||||
if __name__ == "__main__":
|
||||
mcp.run(transport="streamable_http", port=8000)
|
||||
|
||||
# SSE transport (for real-time updates)
|
||||
if __name__ == "__main__":
|
||||
mcp.run(transport="sse", port=8000)
|
||||
```
|
||||
|
||||
**Transport selection:**
|
||||
- **Stdio**: Command-line tools, subprocess integration
|
||||
- **HTTP**: Web services, remote access, multiple clients
|
||||
- **SSE**: Real-time updates, push notifications
|
||||
- **stdio**: Command-line tools, local integrations, subprocess execution
|
||||
- **Streamable HTTP**: Web services, remote access, multiple clients
|
||||
|
||||
---
|
||||
|
||||
@@ -733,12 +701,11 @@ Before finalizing your Python MCP server implementation, ensure:
|
||||
- [ ] Resources registered for appropriate data endpoints
|
||||
- [ ] Lifespan management implemented for persistent connections
|
||||
- [ ] Structured output types used (TypedDict, Pydantic models)
|
||||
- [ ] Appropriate transport configured (stdio, HTTP, SSE)
|
||||
- [ ] Appropriate transport configured (stdio or streamable HTTP)
|
||||
|
||||
### Code Quality
|
||||
- [ ] File includes proper imports including Pydantic imports
|
||||
- [ ] Pagination is properly implemented where applicable
|
||||
- [ ] Large responses check CHARACTER_LIMIT and truncate with clear messages
|
||||
- [ ] Filtering options are provided for potentially large result sets
|
||||
- [ ] All async functions are properly defined with `async def`
|
||||
- [ ] HTTP client usage follows async patterns with proper context managers
|
||||
|
||||
Reference in New Issue
Block a user