MCP Server Development Guide 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. --- Process 🚀 High-Level Workflow Creating a high-quality MCP server involves four main phases: Phase 1: Deep Research and Planning 1.1 Understand Agent-Centric Design Principles Before diving into implementati…

)\n age: int = Field(..., description=\"User's age\", ge=0, le=150)\n\n @field_validator('email')\n @classmethod\n def validate_email(cls, v: str) -> str:\n if not v.strip():\n raise ValueError(\"Email cannot be empty\")\n return v.lower()\n```\n\n## Response Format Options\n\nSupport multiple output formats for flexibility:\n\n```python\nfrom enum import Enum\n\nclass ResponseFormat(str, Enum):\n '''Output format for tool responses.'''\n MARKDOWN = \"markdown\"\n JSON = \"json\"\n\nclass UserSearchInput(BaseModel):\n query: str = Field(..., description=\"Search query\")\n response_format: ResponseFormat = Field(\n default=ResponseFormat.MARKDOWN,\n description=\"Output format: 'markdown' for human-readable or 'json' for machine-readable\"\n )\n```\n\n**Markdown format**:\n- Use headers, lists, and formatting for clarity\n- Convert timestamps to human-readable format (e.g., \"2024-01-15 10:30:00 UTC\" instead of epoch)\n- Show display names with IDs in parentheses (e.g., \"@john.doe (U123456)\")\n- Omit verbose metadata (e.g., show only one profile image URL, not all sizes)\n- Group related information logically\n\n**JSON format**:\n- Return complete, structured data suitable for programmatic processing\n- Include all available fields and metadata\n- Use consistent field names and types\n\n## Pagination Implementation\n\nFor tools that list resources:\n\n```python\nclass ListInput(BaseModel):\n limit: Optional[int] = Field(default=20, description=\"Maximum results to return\", ge=1, le=100)\n offset: Optional[int] = Field(default=0, description=\"Number of results to skip for pagination\", ge=0)\n\nasync def list_items(params: ListInput) -> str:\n # Make API request with pagination\n data = await api_request(limit=params.limit, offset=params.offset)\n\n # Return pagination info\n response = {\n \"total\": data[\"total\"],\n \"count\": len(data[\"items\"]),\n \"offset\": params.offset,\n \"items\": data[\"items\"],\n \"has_more\": data[\"total\"] > params.offset + len(data[\"items\"]),\n \"next_offset\": params.offset + len(data[\"items\"]) if data[\"total\"] > params.offset + len(data[\"items\"]) else None\n }\n return json.dumps(response, indent=2)\n```\n\n## Character Limits and Truncation\n\nAdd a CHARACTER_LIMIT constant to prevent overwhelming responses:\n\n```python\n# At module level\nCHARACTER_LIMIT = 25000 # Maximum response size in characters\n\nasync def search_tool(params: SearchInput) -> str:\n result = generate_response(data)\n\n # Check character limit and truncate if needed\n if len(result) > CHARACTER_LIMIT:\n # Truncate data and add notice\n truncated_data = data[:max(1, len(data) // 2)]\n response[\"data\"] = truncated_data\n response[\"truncated\"] = True\n response[\"truncation_message\"] = (\n f\"Response truncated from {len(data)} to {len(truncated_data)} items. \"\n f\"Use 'offset' parameter or add filters to see more results.\"\n )\n result = json.dumps(response, indent=2)\n\n return result\n```\n\n## Error Handling\n\nProvide clear, actionable error messages:\n\n```python\ndef _handle_api_error(e: Exception) -> str:\n '''Consistent error formatting across all tools.'''\n if isinstance(e, httpx.HTTPStatusError):\n if e.response.status_code == 404:\n return \"Error: Resource not found. Please check the ID is correct.\"\n elif e.response.status_code == 403:\n return \"Error: Permission denied. You don't have access to this resource.\"\n elif e.response.status_code == 429:\n return \"Error: Rate limit exceeded. Please wait before making more requests.\"\n return f\"Error: API request failed with status {e.response.status_code}\"\n elif isinstance(e, httpx.TimeoutException):\n return \"Error: Request timed out. Please try again.\"\n return f\"Error: Unexpected error occurred: {type(e).__name__}\"\n```\n\n## Shared Utilities\n\nExtract common functionality into reusable functions:\n\n```python\n# Shared API request function\nasync def _make_api_request(endpoint: str, method: str = \"GET\", **kwargs) -> dict:\n '''Reusable function for all API calls.'''\n async with httpx.AsyncClient() as client:\n response = await client.request(\n method,\n f\"{API_BASE_URL}/{endpoint}\",\n timeout=30.0,\n **kwargs\n )\n response.raise_for_status()\n return response.json()\n```\n\n## Async/Await Best Practices\n\nAlways use async/await for network requests and I/O operations:\n\n```python\n# Good: Async network request\nasync def fetch_data(resource_id: str) -> dict:\n async with httpx.AsyncClient() as client:\n response = await client.get(f\"{API_URL}/resource/{resource_id}\")\n response.raise_for_status()\n return response.json()\n\n# Bad: Synchronous request\ndef fetch_data(resource_id: str) -> dict:\n response = requests.get(f\"{API_URL}/resource/{resource_id}\") # Blocks\n return response.json()\n```\n\n## Type Hints\n\nUse type hints throughout:\n\n```python\nfrom typing import Optional, List, Dict, Any\n\nasync def get_user(user_id: str) -> Dict[str, Any]:\n data = await fetch_user(user_id)\n return {\"id\": data[\"id\"], \"name\": data[\"name\"]}\n```\n\n## Tool Docstrings\n\nEvery tool must have comprehensive docstrings with explicit type information:\n\n```python\nasync def search_users(params: UserSearchInput) -> str:\n '''\n Search for users in the Example system by name, email, or team.\n\n This tool searches across all user profiles in the Example platform,\n supporting partial matches and various search filters. It does NOT\n create or modify users, only searches existing ones.\n\n Args:\n params (UserSearchInput): Validated input parameters containing:\n - query (str): Search string to match against names/emails (e.g., \"john\", \"@example.com\", \"team:marketing\")\n - limit (Optional[int]): Maximum results to return, between 1-100 (default: 20)\n - offset (Optional[int]): Number of results to skip for pagination (default: 0)\n\n Returns:\n str: JSON-formatted string containing search results with the following schema:\n\n Success response:\n {\n \"total\": int, # Total number of matches found\n \"count\": int, # Number of results in this response\n \"offset\": int, # Current pagination offset\n \"users\": [\n {\n \"id\": str, # User ID (e.g., \"U123456789\")\n \"name\": str, # Full name (e.g., \"John Doe\")\n \"email\": str, # Email address (e.g., \"[email protected]\")\n \"team\": str # Team name (e.g., \"Marketing\") - optional\n }\n ]\n }\n\n Error response:\n \"Error: \u003cerror message>\" or \"No users found matching '\u003cquery>'\"\n\n Examples:\n - Use when: \"Find all marketing team members\" -> params with query=\"team:marketing\"\n - Use when: \"Search for John's account\" -> params with query=\"john\"\n - Don't use when: You need to create a user (use example_create_user instead)\n - Don't use when: You have a user ID and need full details (use example_get_user instead)\n\n Error Handling:\n - Input validation errors are handled by Pydantic model\n - Returns \"Error: Rate limit exceeded\" if too many requests (429 status)\n - Returns \"Error: Invalid API authentication\" if API key is invalid (401 status)\n - Returns formatted list of results or \"No users found matching 'query'\"\n '''\n```\n\n## Complete Example\n\nSee below for a complete Python MCP server example:\n\n```python\n#!/usr/bin/env python3\n'''\nMCP Server for Example Service.\n\nThis server provides tools to interact with Example API, including user search,\nproject management, and data export capabilities.\n'''\n\nfrom typing import Optional, List, Dict, Any\nfrom enum import Enum\nimport httpx\nfrom pydantic import BaseModel, Field, field_validator, ConfigDict\nfrom mcp.server.fastmcp import FastMCP\n\n# Initialize the MCP server\nmcp = FastMCP(\"example_mcp\")\n\n# Constants\nAPI_BASE_URL = \"https://api.example.com/v1\"\nCHARACTER_LIMIT = 25000 # Maximum response size in characters\n\n# Enums\nclass ResponseFormat(str, Enum):\n '''Output format for tool responses.'''\n MARKDOWN = \"markdown\"\n JSON = \"json\"\n\n# Pydantic Models for Input Validation\nclass UserSearchInput(BaseModel):\n '''Input model for user search operations.'''\n model_config = ConfigDict(\n str_strip_whitespace=True,\n validate_assignment=True\n )\n\n query: str = Field(..., description=\"Search string to match against names/emails\", min_length=2, max_length=200)\n limit: Optional[int] = Field(default=20, description=\"Maximum results to return\", ge=1, le=100)\n offset: Optional[int] = Field(default=0, description=\"Number of results to skip for pagination\", ge=0)\n response_format: ResponseFormat = Field(default=ResponseFormat.MARKDOWN, description=\"Output format\")\n\n @field_validator('query')\n @classmethod\n def validate_query(cls, v: str) -> str:\n if not v.strip():\n raise ValueError(\"Query cannot be empty or whitespace only\")\n return v.strip()\n\n# Shared utility functions\nasync def _make_api_request(endpoint: str, method: str = \"GET\", **kwargs) -> dict:\n '''Reusable function for all API calls.'''\n async with httpx.AsyncClient() as client:\n response = await client.request(\n method,\n f\"{API_BASE_URL}/{endpoint}\",\n timeout=30.0,\n **kwargs\n )\n response.raise_for_status()\n return response.json()\n\ndef _handle_api_error(e: Exception) -> str:\n '''Consistent error formatting across all tools.'''\n if isinstance(e, httpx.HTTPStatusError):\n if e.response.status_code == 404:\n return \"Error: Resource not found. Please check the ID is correct.\"\n elif e.response.status_code == 403:\n return \"Error: Permission denied. You don't have access to this resource.\"\n elif e.response.status_code == 429:\n return \"Error: Rate limit exceeded. Please wait before making more requests.\"\n return f\"Error: API request failed with status {e.response.status_code}\"\n elif isinstance(e, httpx.TimeoutException):\n return \"Error: Request timed out. Please try again.\"\n return f\"Error: Unexpected error occurred: {type(e).__name__}\"\n\n# Tool definitions\[email protected](\n name=\"example_search_users\",\n annotations={\n \"title\": \"Search Example Users\",\n \"readOnlyHint\": True,\n \"destructiveHint\": False,\n \"idempotentHint\": True,\n \"openWorldHint\": True\n }\n)\nasync def example_search_users(params: UserSearchInput) -> str:\n '''Search for users in the Example system by name, email, or team.\n\n [Full docstring as shown above]\n '''\n try:\n # Make API request using validated parameters\n data = await _make_api_request(\n \"users/search\",\n params={\n \"q\": params.query,\n \"limit\": params.limit,\n \"offset\": params.offset\n }\n )\n\n users = data.get(\"users\", [])\n total = data.get(\"total\", 0)\n\n if not users:\n return f\"No users found matching '{params.query}'\"\n\n # Format response based on requested format\n if params.response_format == ResponseFormat.MARKDOWN:\n lines = [f\"# User Search Results: '{params.query}'\", \"\"]\n lines.append(f\"Found {total} users (showing {len(users)})\")\n lines.append(\"\")\n\n for user in users:\n lines.append(f\"## {user['name']} ({user['id']})\")\n lines.append(f\"- **Email**: {user['email']}\")\n if user.get('team'):\n lines.append(f\"- **Team**: {user['team']}\")\n lines.append(\"\")\n\n return \"\\n\".join(lines)\n\n else:\n # Machine-readable JSON format\n import json\n response = {\n \"total\": total,\n \"count\": len(users),\n \"offset\": params.offset,\n \"users\": users\n }\n return json.dumps(response, indent=2)\n\n except Exception as e:\n return _handle_api_error(e)\n\nif __name__ == \"__main__\":\n mcp.run()\n```\n\n---\n\n## Advanced FastMCP Features\n\n### Context Parameter Injection\n\nFastMCP can automatically inject a `Context` parameter into tools for advanced capabilities like logging, progress reporting, resource reading, and user interaction:\n\n```python\nfrom mcp.server.fastmcp import FastMCP, Context\n\nmcp = FastMCP(\"example_mcp\")\n\[email protected]()\nasync def advanced_search(query: str, ctx: Context) -> str:\n '''Advanced tool with context access for logging and progress.'''\n\n # Report progress for long operations\n await ctx.report_progress(0.25, \"Starting search...\")\n\n # Log information for debugging\n await ctx.log_info(\"Processing query\", {\"query\": query, \"timestamp\": datetime.now()})\n\n # Perform search\n results = await search_api(query)\n await ctx.report_progress(0.75, \"Formatting results...\")\n\n # Access server configuration\n server_name = ctx.fastmcp.name\n\n return format_results(results)\n\[email protected]()\nasync def interactive_tool(resource_id: str, ctx: Context) -> str:\n '''Tool that can request additional input from users.'''\n\n # Request sensitive information when needed\n api_key = await ctx.elicit(\n prompt=\"Please provide your API key:\",\n input_type=\"password\"\n )\n\n # Use the provided key\n return await api_call(resource_id, api_key)\n```\n\n**Context capabilities:**\n- `ctx.report_progress(progress, message)` - Report progress for long operations\n- `ctx.log_info(message, data)` / `ctx.log_error()` / `ctx.log_debug()` - Logging\n- `ctx.elicit(prompt, input_type)` - Request input from users\n- `ctx.fastmcp.name` - Access server configuration\n- `ctx.read_resource(uri)` - Read MCP resources\n\n### Resource Registration\n\nExpose data as resources for efficient, template-based access:\n\n```python\[email protected](\"file://documents/{name}\")\nasync def get_document(name: str) -> str:\n '''Expose documents as MCP resources.\n\n Resources are useful for static or semi-static data that doesn't\n require complex parameters. They use URI templates for flexible access.\n '''\n document_path = f\"./docs/{name}\"\n with open(document_path, \"r\") as f:\n return f.read()\n\[email protected](\"config://settings/{key}\")\nasync def get_setting(key: str, ctx: Context) -> str:\n '''Expose configuration as resources with context.'''\n settings = await load_settings()\n return json.dumps(settings.get(key, {}))\n```\n\n**When to use Resources vs Tools:**\n- **Resources**: For data access with simple parameters (URI templates)\n- **Tools**: For complex operations with validation and business logic\n\n### Structured Output Types\n\nFastMCP supports multiple return types beyond strings:\n\n```python\nfrom typing import TypedDict\nfrom dataclasses import dataclass\nfrom pydantic import BaseModel\n\n# TypedDict for structured returns\nclass UserData(TypedDict):\n id: str\n name: str\n email: str\n\[email protected]()\nasync def get_user_typed(user_id: str) -> UserData:\n '''Returns structured data - FastMCP handles serialization.'''\n return {\"id\": user_id, \"name\": \"John Doe\", \"email\": \"[email protected]\"}\n\n# Pydantic models for complex validation\nclass DetailedUser(BaseModel):\n id: str\n name: str\n email: str\n created_at: datetime\n metadata: Dict[str, Any]\n\[email protected]()\nasync def get_user_detailed(user_id: str) -> DetailedUser:\n '''Returns Pydantic model - automatically generates schema.'''\n user = await fetch_user(user_id)\n return DetailedUser(**user)\n```\n\n### Lifespan Management\n\nInitialize resources that persist across requests:\n\n```python\nfrom contextlib import asynccontextmanager\n\n@asynccontextmanager\nasync def app_lifespan():\n '''Manage resources that live for the server's lifetime.'''\n # Initialize connections, load config, etc.\n db = await connect_to_database()\n config = load_configuration()\n\n # Make available to all tools\n yield {\"db\": db, \"config\": config}\n\n # Cleanup on shutdown\n await db.close()\n\nmcp = FastMCP(\"example_mcp\", lifespan=app_lifespan)\n\[email protected]()\nasync def query_data(query: str, ctx: Context) -> str:\n '''Access lifespan resources through context.'''\n db = ctx.request_context.lifespan_state[\"db\"]\n results = await db.query(query)\n return format_results(results)\n```\n\n### Multiple Transport Options\n\nFastMCP supports different transport mechanisms:\n\n```python\n# Default: Stdio transport (for CLI tools)\nif __name__ == \"__main__\":\n mcp.run()\n\n# HTTP transport (for web services)\nif __name__ == \"__main__\":\n mcp.run(transport=\"streamable_http\", port=8000)\n\n# SSE transport (for real-time updates)\nif __name__ == \"__main__\":\n mcp.run(transport=\"sse\", port=8000)\n```\n\n**Transport selection:**\n- **Stdio**: Command-line tools, subprocess integration\n- **HTTP**: Web services, remote access, multiple clients\n- **SSE**: Real-time updates, push notifications\n\n---\n\n## Code Best Practices\n\n### Code Composability and Reusability\n\nYour implementation MUST prioritize composability and code reuse:\n\n1. **Extract Common Functionality**:\n - Create reusable helper functions for operations used across multiple tools\n - Build shared API clients for HTTP requests instead of duplicating code\n - Centralize error handling logic in utility functions\n - Extract business logic into dedicated functions that can be composed\n - Extract shared markdown or JSON field selection & formatting functionality\n\n2. **Avoid Duplication**:\n - NEVER copy-paste similar code between tools\n - If you find yourself writing similar logic twice, extract it into a function\n - Common operations like pagination, filtering, field selection, and formatting should be shared\n - Authentication/authorization logic should be centralized\n\n### Python-Specific Best Practices\n\n1. **Use Type Hints**: Always include type annotations for function parameters and return values\n2. **Pydantic Models**: Define clear Pydantic models for all input validation\n3. **Avoid Manual Validation**: Let Pydantic handle input validation with constraints\n4. **Proper Imports**: Group imports (standard library, third-party, local)\n5. **Error Handling**: Use specific exception types (httpx.HTTPStatusError, not generic Exception)\n6. **Async Context Managers**: Use `async with` for resources that need cleanup\n7. **Constants**: Define module-level constants in UPPER_CASE\n\n## Quality Checklist\n\nBefore finalizing your Python MCP server implementation, ensure:\n\n### Strategic Design\n- [ ] Tools enable complete workflows, not just API endpoint wrappers\n- [ ] Tool names reflect natural task subdivisions\n- [ ] Response formats optimize for agent context efficiency\n- [ ] Human-readable identifiers used where appropriate\n- [ ] Error messages guide agents toward correct usage\n\n### Implementation Quality\n- [ ] FOCUSED IMPLEMENTATION: Most important and valuable tools implemented\n- [ ] All tools have descriptive names and documentation\n- [ ] Return types are consistent across similar operations\n- [ ] Error handling is implemented for all external calls\n- [ ] Server name follows format: `{service}_mcp`\n- [ ] All network operations use async/await\n- [ ] Common functionality is extracted into reusable functions\n- [ ] Error messages are clear, actionable, and educational\n- [ ] Outputs are properly validated and formatted\n\n### Tool Configuration\n- [ ] All tools implement 'name' and 'annotations' in the decorator\n- [ ] Annotations correctly set (readOnlyHint, destructiveHint, idempotentHint, openWorldHint)\n- [ ] All tools use Pydantic BaseModel for input validation with Field() definitions\n- [ ] All Pydantic Fields have explicit types and descriptions with constraints\n- [ ] All tools have comprehensive docstrings with explicit input/output types\n- [ ] Docstrings include complete schema structure for dict/JSON returns\n- [ ] Pydantic models handle input validation (no manual validation needed)\n\n### Advanced Features (where applicable)\n- [ ] Context injection used for logging, progress, or elicitation\n- [ ] Resources registered for appropriate data endpoints\n- [ ] Lifespan management implemented for persistent connections\n- [ ] Structured output types used (TypedDict, Pydantic models)\n- [ ] Appropriate transport configured (stdio, HTTP, SSE)\n\n### Code Quality\n- [ ] File includes proper imports including Pydantic imports\n- [ ] Pagination is properly implemented where applicable\n- [ ] Large responses check CHARACTER_LIMIT and truncate with clear messages\n- [ ] Filtering options are provided for potentially large result sets\n- [ ] All async functions are properly defined with `async def`\n- [ ] HTTP client usage follows async patterns with proper context managers\n- [ ] Type hints are used throughout the code\n- [ ] Constants are defined at module level in UPPER_CASE\n\n### Testing\n- [ ] Server runs successfully: `python your_server.py --help`\n- [ ] All imports resolve correctly\n- [ ] Sample tool calls work as expected\n- [ ] Error scenarios handled gracefully","content_type":"text/markdown; charset=utf-8","language":"markdown","size":26182,"content_sha256":"4e6db48188f44ff4eb707f50b8d273d5d18af4b88d326f7a26f03a405064bc0b"},{"filename":"scripts/connections.py","content":"\"\"\"Lightweight connection handling for MCP servers.\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom contextlib import AsyncExitStack\nfrom typing import Any\n\nfrom mcp import ClientSession, StdioServerParameters\nfrom mcp.client.sse import sse_client\nfrom mcp.client.stdio import stdio_client\nfrom mcp.client.streamable_http import streamablehttp_client\n\n\nclass MCPConnection(ABC):\n \"\"\"Base class for MCP server connections.\"\"\"\n\n def __init__(self):\n self.session = None\n self._stack = None\n\n @abstractmethod\n def _create_context(self):\n \"\"\"Create the connection context based on connection type.\"\"\"\n\n async def __aenter__(self):\n \"\"\"Initialize MCP server connection.\"\"\"\n self._stack = AsyncExitStack()\n await self._stack.__aenter__()\n\n try:\n ctx = self._create_context()\n result = await self._stack.enter_async_context(ctx)\n\n if len(result) == 2:\n read, write = result\n elif len(result) == 3:\n read, write, _ = result\n else:\n raise ValueError(f\"Unexpected context result: {result}\")\n\n session_ctx = ClientSession(read, write)\n self.session = await self._stack.enter_async_context(session_ctx)\n await self.session.initialize()\n return self\n except BaseException:\n await self._stack.__aexit__(None, None, None)\n raise\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n \"\"\"Clean up MCP server connection resources.\"\"\"\n if self._stack:\n await self._stack.__aexit__(exc_type, exc_val, exc_tb)\n self.session = None\n self._stack = None\n\n async def list_tools(self) -> list[dict[str, Any]]:\n \"\"\"Retrieve available tools from the MCP server.\"\"\"\n response = await self.session.list_tools()\n return [\n {\n \"name\": tool.name,\n \"description\": tool.description,\n \"input_schema\": tool.inputSchema,\n }\n for tool in response.tools\n ]\n\n async def call_tool(self, tool_name: str, arguments: dict[str, Any]) -> Any:\n \"\"\"Call a tool on the MCP server with provided arguments.\"\"\"\n result = await self.session.call_tool(tool_name, arguments=arguments)\n return result.content\n\n\nclass MCPConnectionStdio(MCPConnection):\n \"\"\"MCP connection using standard input/output.\"\"\"\n\n def __init__(self, command: str, args: list[str] = None, env: dict[str, str] = None):\n super().__init__()\n self.command = command\n self.args = args or []\n self.env = env\n\n def _create_context(self):\n return stdio_client(\n StdioServerParameters(command=self.command, args=self.args, env=self.env)\n )\n\n\nclass MCPConnectionSSE(MCPConnection):\n \"\"\"MCP connection using Server-Sent Events.\"\"\"\n\n def __init__(self, url: str, headers: dict[str, str] = None):\n super().__init__()\n self.url = url\n self.headers = headers or {}\n\n def _create_context(self):\n return sse_client(url=self.url, headers=self.headers)\n\n\nclass MCPConnectionHTTP(MCPConnection):\n \"\"\"MCP connection using Streamable HTTP.\"\"\"\n\n def __init__(self, url: str, headers: dict[str, str] = None):\n super().__init__()\n self.url = url\n self.headers = headers or {}\n\n def _create_context(self):\n return streamablehttp_client(url=self.url, headers=self.headers)\n\n\ndef create_connection(\n transport: str,\n command: str = None,\n args: list[str] = None,\n env: dict[str, str] = None,\n url: str = None,\n headers: dict[str, str] = None,\n) -> MCPConnection:\n \"\"\"Factory function to create the appropriate MCP connection.\n\n Args:\n transport: Connection type (\"stdio\", \"sse\", or \"http\")\n command: Command to run (stdio only)\n args: Command arguments (stdio only)\n env: Environment variables (stdio only)\n url: Server URL (sse and http only)\n headers: HTTP headers (sse and http only)\n\n Returns:\n MCPConnection instance\n \"\"\"\n transport = transport.lower()\n\n if transport == \"stdio\":\n if not command:\n raise ValueError(\"Command is required for stdio transport\")\n return MCPConnectionStdio(command=command, args=args, env=env)\n\n elif transport == \"sse\":\n if not url:\n raise ValueError(\"URL is required for sse transport\")\n return MCPConnectionSSE(url=url, headers=headers)\n\n elif transport in [\"http\", \"streamable_http\", \"streamable-http\"]:\n if not url:\n raise ValueError(\"URL is required for http transport\")\n return MCPConnectionHTTP(url=url, headers=headers)\n\n else:\n raise ValueError(f\"Unsupported transport type: {transport}. Use 'stdio', 'sse', or 'http'\")\n","content_type":"text/x-python; charset=utf-8","language":"python","size":4875,"content_sha256":"9403668a2041568772082a8b334122c1f88daf0541fb393af4522d0094a47a6e"},{"filename":"scripts/evaluation.py","content":"\"\"\"MCP Server Evaluation Harness\n\nThis script evaluates MCP servers by running test questions against them using Claude.\n\"\"\"\n\nimport argparse\nimport asyncio\nimport json\nimport re\nimport sys\nimport time\nimport traceback\nimport xml.etree.ElementTree as ET\nfrom pathlib import Path\nfrom typing import Any\n\nfrom anthropic import Anthropic\n\nfrom connections import create_connection\n\nEVALUATION_PROMPT = \"\"\"You are an AI assistant with access to tools.\n\nWhen given a task, you MUST:\n1. Use the available tools to complete the task\n2. Provide summary of each step in your approach, wrapped in \u003csummary> tags\n3. Provide feedback on the tools provided, wrapped in \u003cfeedback> tags\n4. Provide your final response, wrapped in \u003cresponse> tags\n\nSummary Requirements:\n- In your \u003csummary> tags, you must explain:\n - The steps you took to complete the task\n - Which tools you used, in what order, and why\n - The inputs you provided to each tool\n - The outputs you received from each tool\n - A summary for how you arrived at the response\n\nFeedback Requirements:\n- In your \u003cfeedback> tags, provide constructive feedback on the tools:\n - Comment on tool names: Are they clear and descriptive?\n - Comment on input parameters: Are they well-documented? Are required vs optional parameters clear?\n - Comment on descriptions: Do they accurately describe what the tool does?\n - Comment on any errors encountered during tool usage: Did the tool fail to execute? Did the tool return too many tokens?\n - Identify specific areas for improvement and explain WHY they would help\n - Be specific and actionable in your suggestions\n\nResponse Requirements:\n- Your response should be concise and directly address what was asked\n- Always wrap your final response in \u003cresponse> tags\n- If you cannot solve the task return \u003cresponse>NOT_FOUND\u003c/response>\n- For numeric responses, provide just the number\n- For IDs, provide just the ID\n- For names or text, provide the exact text requested\n- Your response should go last\"\"\"\n\n\ndef parse_evaluation_file(file_path: Path) -> list[dict[str, Any]]:\n \"\"\"Parse XML evaluation file with qa_pair elements.\"\"\"\n try:\n tree = ET.parse(file_path)\n root = tree.getroot()\n evaluations = []\n\n for qa_pair in root.findall(\".//qa_pair\"):\n question_elem = qa_pair.find(\"question\")\n answer_elem = qa_pair.find(\"answer\")\n\n if question_elem is not None and answer_elem is not None:\n evaluations.append({\n \"question\": (question_elem.text or \"\").strip(),\n \"answer\": (answer_elem.text or \"\").strip(),\n })\n\n return evaluations\n except Exception as e:\n print(f\"Error parsing evaluation file {file_path}: {e}\")\n return []\n\n\ndef extract_xml_content(text: str, tag: str) -> str | None:\n \"\"\"Extract content from XML tags.\"\"\"\n pattern = rf\"\u003c{tag}>(.*?)\u003c/{tag}>\"\n matches = re.findall(pattern, text, re.DOTALL)\n return matches[-1].strip() if matches else None\n\n\nasync def agent_loop(\n client: Anthropic,\n model: str,\n question: str,\n tools: list[dict[str, Any]],\n connection: Any,\n) -> tuple[str, dict[str, Any]]:\n \"\"\"Run the agent loop with MCP tools.\"\"\"\n messages = [{\"role\": \"user\", \"content\": question}]\n\n response = await asyncio.to_thread(\n client.messages.create,\n model=model,\n max_tokens=4096,\n system=EVALUATION_PROMPT,\n messages=messages,\n tools=tools,\n )\n\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n tool_metrics = {}\n\n while response.stop_reason == \"tool_use\":\n tool_use = next(block for block in response.content if block.type == \"tool_use\")\n tool_name = tool_use.name\n tool_input = tool_use.input\n\n tool_start_ts = time.time()\n try:\n tool_result = await connection.call_tool(tool_name, tool_input)\n tool_response = json.dumps(tool_result) if isinstance(tool_result, (dict, list)) else str(tool_result)\n except Exception as e:\n tool_response = f\"Error executing tool {tool_name}: {str(e)}\\n\"\n tool_response += traceback.format_exc()\n tool_duration = time.time() - tool_start_ts\n\n if tool_name not in tool_metrics:\n tool_metrics[tool_name] = {\"count\": 0, \"durations\": []}\n tool_metrics[tool_name][\"count\"] += 1\n tool_metrics[tool_name][\"durations\"].append(tool_duration)\n\n messages.append({\n \"role\": \"user\",\n \"content\": [{\n \"type\": \"tool_result\",\n \"tool_use_id\": tool_use.id,\n \"content\": tool_response,\n }]\n })\n\n response = await asyncio.to_thread(\n client.messages.create,\n model=model,\n max_tokens=4096,\n system=EVALUATION_PROMPT,\n messages=messages,\n tools=tools,\n )\n messages.append({\"role\": \"assistant\", \"content\": response.content})\n\n response_text = next(\n (block.text for block in response.content if hasattr(block, \"text\")),\n None,\n )\n return response_text, tool_metrics\n\n\nasync def evaluate_single_task(\n client: Anthropic,\n model: str,\n qa_pair: dict[str, Any],\n tools: list[dict[str, Any]],\n connection: Any,\n task_index: int,\n) -> dict[str, Any]:\n \"\"\"Evaluate a single QA pair with the given tools.\"\"\"\n start_time = time.time()\n\n print(f\"Task {task_index + 1}: Running task with question: {qa_pair['question']}\")\n response, tool_metrics = await agent_loop(client, model, qa_pair[\"question\"], tools, connection)\n\n response_value = extract_xml_content(response, \"response\")\n summary = extract_xml_content(response, \"summary\")\n feedback = extract_xml_content(response, \"feedback\")\n\n duration_seconds = time.time() - start_time\n\n return {\n \"question\": qa_pair[\"question\"],\n \"expected\": qa_pair[\"answer\"],\n \"actual\": response_value,\n \"score\": int(response_value == qa_pair[\"answer\"]) if response_value else 0,\n \"total_duration\": duration_seconds,\n \"tool_calls\": tool_metrics,\n \"num_tool_calls\": sum(len(metrics[\"durations\"]) for metrics in tool_metrics.values()),\n \"summary\": summary,\n \"feedback\": feedback,\n }\n\n\nREPORT_HEADER = \"\"\"\n# Evaluation Report\n\n## Summary\n\n- **Accuracy**: {correct}/{total} ({accuracy:.1f}%)\n- **Average Task Duration**: {average_duration_s:.2f}s\n- **Average Tool Calls per Task**: {average_tool_calls:.2f}\n- **Total Tool Calls**: {total_tool_calls}\n\n---\n\"\"\"\n\nTASK_TEMPLATE = \"\"\"\n### Task {task_num}\n\n**Question**: {question}\n**Ground Truth Answer**: `{expected_answer}`\n**Actual Answer**: `{actual_answer}`\n**Correct**: {correct_indicator}\n**Duration**: {total_duration:.2f}s\n**Tool Calls**: {tool_calls}\n\n**Summary**\n{summary}\n\n**Feedback**\n{feedback}\n\n---\n\"\"\"\n\n\nasync def run_evaluation(\n eval_path: Path,\n connection: Any,\n model: str = \"claude-3-7-sonnet-20250219\",\n) -> str:\n \"\"\"Run evaluation with MCP server tools.\"\"\"\n print(\"🚀 Starting Evaluation\")\n\n client = Anthropic()\n\n tools = await connection.list_tools()\n print(f\"📋 Loaded {len(tools)} tools from MCP server\")\n\n qa_pairs = parse_evaluation_file(eval_path)\n print(f\"📋 Loaded {len(qa_pairs)} evaluation tasks\")\n\n results = []\n for i, qa_pair in enumerate(qa_pairs):\n print(f\"Processing task {i + 1}/{len(qa_pairs)}\")\n result = await evaluate_single_task(client, model, qa_pair, tools, connection, i)\n results.append(result)\n\n correct = sum(r[\"score\"] for r in results)\n accuracy = (correct / len(results)) * 100 if results else 0\n average_duration_s = sum(r[\"total_duration\"] for r in results) / len(results) if results else 0\n average_tool_calls = sum(r[\"num_tool_calls\"] for r in results) / len(results) if results else 0\n total_tool_calls = sum(r[\"num_tool_calls\"] for r in results)\n\n report = REPORT_HEADER.format(\n correct=correct,\n total=len(results),\n accuracy=accuracy,\n average_duration_s=average_duration_s,\n average_tool_calls=average_tool_calls,\n total_tool_calls=total_tool_calls,\n )\n\n report += \"\".join([\n TASK_TEMPLATE.format(\n task_num=i + 1,\n question=qa_pair[\"question\"],\n expected_answer=qa_pair[\"answer\"],\n actual_answer=result[\"actual\"] or \"N/A\",\n correct_indicator=\"✅\" if result[\"score\"] else \"❌\",\n total_duration=result[\"total_duration\"],\n tool_calls=json.dumps(result[\"tool_calls\"], indent=2),\n summary=result[\"summary\"] or \"N/A\",\n feedback=result[\"feedback\"] or \"N/A\",\n )\n for i, (qa_pair, result) in enumerate(zip(qa_pairs, results))\n ])\n\n return report\n\n\ndef parse_headers(header_list: list[str]) -> dict[str, str]:\n \"\"\"Parse header strings in format 'Key: Value' into a dictionary.\"\"\"\n headers = {}\n if not header_list:\n return headers\n\n for header in header_list:\n if \":\" in header:\n key, value = header.split(\":\", 1)\n headers[key.strip()] = value.strip()\n else:\n print(f\"Warning: Ignoring malformed header: {header}\")\n return headers\n\n\ndef parse_env_vars(env_list: list[str]) -> dict[str, str]:\n \"\"\"Parse environment variable strings in format 'KEY=VALUE' into a dictionary.\"\"\"\n env = {}\n if not env_list:\n return env\n\n for env_var in env_list:\n if \"=\" in env_var:\n key, value = env_var.split(\"=\", 1)\n env[key.strip()] = value.strip()\n else:\n print(f\"Warning: Ignoring malformed environment variable: {env_var}\")\n return env\n\n\nasync def main():\n parser = argparse.ArgumentParser(\n description=\"Evaluate MCP servers using test questions\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n epilog=\"\"\"\nExamples:\n # Evaluate a local stdio MCP server\n python evaluation.py -t stdio -c python -a my_server.py eval.xml\n\n # Evaluate an SSE MCP server\n python evaluation.py -t sse -u https://example.com/mcp -H \"Authorization: Bearer token\" eval.xml\n\n # Evaluate an HTTP MCP server with custom model\n python evaluation.py -t http -u https://example.com/mcp -m claude-3-5-sonnet-20241022 eval.xml\n \"\"\",\n )\n\n parser.add_argument(\"eval_file\", type=Path, help=\"Path to evaluation XML file\")\n parser.add_argument(\"-t\", \"--transport\", choices=[\"stdio\", \"sse\", \"http\"], default=\"stdio\", help=\"Transport type (default: stdio)\")\n parser.add_argument(\"-m\", \"--model\", default=\"claude-3-7-sonnet-20250219\", help=\"Claude model to use (default: claude-3-7-sonnet-20250219)\")\n\n stdio_group = parser.add_argument_group(\"stdio options\")\n stdio_group.add_argument(\"-c\", \"--command\", help=\"Command to run MCP server (stdio only)\")\n stdio_group.add_argument(\"-a\", \"--args\", nargs=\"+\", help=\"Arguments for the command (stdio only)\")\n stdio_group.add_argument(\"-e\", \"--env\", nargs=\"+\", help=\"Environment variables in KEY=VALUE format (stdio only)\")\n\n remote_group = parser.add_argument_group(\"sse/http options\")\n remote_group.add_argument(\"-u\", \"--url\", help=\"MCP server URL (sse/http only)\")\n remote_group.add_argument(\"-H\", \"--header\", nargs=\"+\", dest=\"headers\", help=\"HTTP headers in 'Key: Value' format (sse/http only)\")\n\n parser.add_argument(\"-o\", \"--output\", type=Path, help=\"Output file for evaluation report (default: stdout)\")\n\n args = parser.parse_args()\n\n if not args.eval_file.exists():\n print(f\"Error: Evaluation file not found: {args.eval_file}\")\n sys.exit(1)\n\n headers = parse_headers(args.headers) if args.headers else None\n env_vars = parse_env_vars(args.env) if args.env else None\n\n try:\n connection = create_connection(\n transport=args.transport,\n command=args.command,\n args=args.args,\n env=env_vars,\n url=args.url,\n headers=headers,\n )\n except ValueError as e:\n print(f\"Error: {e}\")\n sys.exit(1)\n\n print(f\"🔗 Connecting to MCP server via {args.transport}...\")\n\n async with connection:\n print(\"✅ Connected successfully\")\n report = await run_evaluation(args.eval_file, connection, args.model)\n\n if args.output:\n args.output.write_text(report)\n print(f\"\\n✅ Report saved to {args.output}\")\n else:\n print(\"\\n\" + report)\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","content_type":"text/x-python; charset=utf-8","language":"python","size":12579,"content_sha256":"49ed1d17cdce5da101b210197740713f49b935c29d4f339542a14b132658e6f7"},{"filename":"scripts/example_evaluation.xml","content":"\u003cevaluation>\n \u003cqa_pair>\n \u003cquestion>Calculate the compound interest on $10,000 invested at 5% annual interest rate, compounded monthly for 3 years. What is the final amount in dollars (rounded to 2 decimal places)?\u003c/question>\n \u003canswer>11614.72\u003c/answer>\n \u003c/qa_pair>\n \u003cqa_pair>\n \u003cquestion>A projectile is launched at a 45-degree angle with an initial velocity of 50 m/s. Calculate the total distance (in meters) it has traveled from the launch point after 2 seconds, assuming g=9.8 m/s². Round to 2 decimal places.\u003c/question>\n \u003canswer>87.25\u003c/answer>\n \u003c/qa_pair>\n \u003cqa_pair>\n \u003cquestion>A sphere has a volume of 500 cubic meters. Calculate its surface area in square meters. Round to 2 decimal places.\u003c/question>\n \u003canswer>304.65\u003c/answer>\n \u003c/qa_pair>\n \u003cqa_pair>\n \u003cquestion>Calculate the population standard deviation of this dataset: [12, 15, 18, 22, 25, 30, 35]. Round to 2 decimal places.\u003c/question>\n \u003canswer>7.61\u003c/answer>\n \u003c/qa_pair>\n \u003cqa_pair>\n \u003cquestion>Calculate the pH of a solution with a hydrogen ion concentration of 3.5 × 10^-5 M. Round to 2 decimal places.\u003c/question>\n \u003canswer>4.46\u003c/answer>\n \u003c/qa_pair>\n\u003c/evaluation>\n","content_type":"application/xml; charset=utf-8","language":"xml","size":1194,"content_sha256":"9272b348ddcc4b06ba562367ccd0770e018158c0068ac5116d5e34aaeff8777a"},{"filename":"scripts/requirements.txt","content":"anthropic>=0.39.0\nmcp>=1.1.0\n","content_type":"text/plain; charset=utf-8","language":null,"size":29,"content_sha256":"d5d7558b2368ecea9dfeed7d1fbc71ee9e0750bebd1282faa527d528a344c3c7"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"text":"MCP Server Development Guide","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Overview","type":"text"}]},{"type":"paragraph","content":[{"text":"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.","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":1},"content":[{"text":"Process","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"🚀 High-Level Workflow","type":"text"}]},{"type":"paragraph","content":[{"text":"Creating a high-quality MCP server involves four main phases:","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 1: Deep Research and Planning","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"1.1 Understand Agent-Centric Design Principles","type":"text"}]},{"type":"paragraph","content":[{"text":"Before diving into implementation, understand how to design tools for AI agents by reviewing these principles:","type":"text"}]},{"type":"paragraph","content":[{"text":"Build for Workflows, Not Just API Endpoints:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Don't simply wrap existing API endpoints - build thoughtful, high-impact workflow tools","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Consolidate related operations (e.g., ","type":"text"},{"text":"schedule_event","type":"text","marks":[{"type":"code_inline"}]},{"text":" that both checks availability and creates event)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Focus on tools that enable complete tasks, not just individual API calls","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Consider what workflows agents actually need to accomplish","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Optimize for Limited Context:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Agents have constrained context windows - make every token count","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Return high-signal information, not exhaustive data dumps","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Provide \"concise\" vs \"detailed\" response format options","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Default to human-readable identifiers over technical codes (names over IDs)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Consider the agent's context budget as a scarce resource","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Design Actionable Error Messages:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Error messages should guide agents toward correct usage patterns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Suggest specific next steps: \"Try using filter='active_only' to reduce results\"","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Make errors educational, not just diagnostic","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Help agents learn proper tool usage through clear feedback","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Follow Natural Task Subdivisions:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Tool names should reflect how humans think about tasks","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Group related tools with consistent prefixes for discoverability","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Design tools around natural workflows, not just API structure","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Use Evaluation-Driven Development:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Create realistic evaluation scenarios early","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Let agent feedback drive tool improvements","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Prototype quickly and iterate based on actual agent performance","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"1.3 Study MCP Protocol Documentation","type":"text"}]},{"type":"paragraph","content":[{"text":"Fetch the latest MCP protocol documentation:","type":"text","marks":[{"type":"strong"}]}]},{"type":"paragraph","content":[{"text":"Use WebFetch to load: ","type":"text"},{"text":"https://modelcontextprotocol.io/llms-full.txt","type":"text","marks":[{"type":"code_inline"}]}]},{"type":"paragraph","content":[{"text":"This comprehensive document contains the complete MCP specification and guidelines.","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"1.4 Study Framework Documentation","type":"text"}]},{"type":"paragraph","content":[{"text":"Load and read the following reference files:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"MCP Best Practices","type":"text","marks":[{"type":"strong"}]},{"text":": ","type":"text"},{"text":"📋 View Best Practices","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/mcp_best_practices.md","title":null}}]},{"text":" - Core guidelines for all MCP servers","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"For Python implementations, also load:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Python SDK Documentation","type":"text","marks":[{"type":"strong"}]},{"text":": Use WebFetch to load ","type":"text"},{"text":"https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"🐍 Python Implementation Guide","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/python_mcp_server.md","title":null}}]},{"text":" - Python-specific best practices and examples","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"For Node/TypeScript implementations, also load:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"TypeScript SDK Documentation","type":"text","marks":[{"type":"strong"}]},{"text":": Use WebFetch to load ","type":"text"},{"text":"https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"⚡ TypeScript Implementation Guide","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/node_mcp_server.md","title":null}}]},{"text":" - Node/TypeScript-specific best practices and examples","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"1.5 Exhaustively Study API Documentation","type":"text"}]},{"type":"paragraph","content":[{"text":"To integrate a service, read through ","type":"text"},{"text":"ALL","type":"text","marks":[{"type":"strong"}]},{"text":" available API documentation:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Official API reference documentation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Authentication and authorization requirements","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Rate limiting and pagination patterns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Error responses and status codes","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Available endpoints and their parameters","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Data models and schemas","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"To gather comprehensive information, use web search and the WebFetch tool as needed.","type":"text","marks":[{"type":"strong"}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"1.6 Create a Comprehensive Implementation Plan","type":"text"}]},{"type":"paragraph","content":[{"text":"Based on your research, create a detailed plan that includes:","type":"text"}]},{"type":"paragraph","content":[{"text":"Tool Selection:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"List the most valuable endpoints/operations to implement","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Prioritize tools that enable the most common and important use cases","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Consider which tools work together to enable complex workflows","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Shared Utilities and Helpers:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Identify common API request patterns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Plan pagination helpers","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Design filtering and formatting utilities","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Plan error handling strategies","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Input/Output Design:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Define input validation models (Pydantic for Python, Zod for TypeScript)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Design consistent response formats (e.g., JSON or Markdown), and configurable levels of detail (e.g., Detailed or Concise)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Plan for large-scale usage (thousands of users/resources)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implement character limits and truncation strategies (e.g., 25,000 tokens)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Error Handling Strategy:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Plan graceful failure modes","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Design clear, actionable, LLM-friendly, natural language error messages which prompt further action","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Consider rate limiting and timeout scenarios","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Handle authentication and authorization errors","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 2: Implementation","type":"text"}]},{"type":"paragraph","content":[{"text":"Now that you have a comprehensive plan, begin implementation following language-specific best practices.","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"2.1 Set Up Project Structure","type":"text"}]},{"type":"paragraph","content":[{"text":"For Python:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Create a single ","type":"text"},{"text":".py","type":"text","marks":[{"type":"code_inline"}]},{"text":" file or organize into modules if complex (see ","type":"text"},{"text":"🐍 Python Guide","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/python_mcp_server.md","title":null}}]},{"text":")","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use the MCP Python SDK for tool registration","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Define Pydantic models for input validation","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"For Node/TypeScript:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Create proper project structure (see ","type":"text"},{"text":"⚡ TypeScript Guide","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/node_mcp_server.md","title":null}}]},{"text":")","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Set up ","type":"text"},{"text":"package.json","type":"text","marks":[{"type":"code_inline"}]},{"text":" and ","type":"text"},{"text":"tsconfig.json","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use MCP TypeScript SDK","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Define Zod schemas for input validation","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"2.2 Implement Core Infrastructure First","type":"text"}]},{"type":"paragraph","content":[{"text":"To begin implementation, create shared utilities before implementing tools:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"API request helper functions","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Error handling utilities","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Response formatting functions (JSON and Markdown)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Pagination helpers","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Authentication/token management","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"2.3 Implement Tools Systematically","type":"text"}]},{"type":"paragraph","content":[{"text":"For each tool in the plan:","type":"text"}]},{"type":"paragraph","content":[{"text":"Define Input Schema:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use Pydantic (Python) or Zod (TypeScript) for validation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Include proper constraints (min/max length, regex patterns, min/max values, ranges)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Provide clear, descriptive field descriptions","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Include diverse examples in field descriptions","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Write Comprehensive Docstrings/Descriptions:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"One-line summary of what the tool does","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Detailed explanation of purpose and functionality","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Explicit parameter types with examples","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Complete return type schema","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Usage examples (when to use, when not to use)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Error handling documentation, which outlines how to proceed given specific errors","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Implement Tool Logic:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use shared utilities to avoid code duplication","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Follow async/await patterns for all I/O","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implement proper error handling","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Support multiple response formats (JSON and Markdown)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Respect pagination parameters","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Check character limits and truncate appropriately","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Add Tool Annotations:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"readOnlyHint","type":"text","marks":[{"type":"code_inline"}]},{"text":": true (for read-only operations)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"destructiveHint","type":"text","marks":[{"type":"code_inline"}]},{"text":": false (for non-destructive operations)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"idempotentHint","type":"text","marks":[{"type":"code_inline"}]},{"text":": true (if repeated calls have same effect)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"openWorldHint","type":"text","marks":[{"type":"code_inline"}]},{"text":": true (if interacting with external systems)","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"2.4 Follow Language-Specific Best Practices","type":"text"}]},{"type":"paragraph","content":[{"text":"At this point, load the appropriate language guide:","type":"text","marks":[{"type":"strong"}]}]},{"type":"paragraph","content":[{"text":"For Python: Load ","type":"text","marks":[{"type":"strong"}]},{"text":"🐍 Python Implementation Guide","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/python_mcp_server.md","title":null}},{"type":"strong"}]},{"text":" and ensure the following:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Using MCP Python SDK with proper tool registration","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Pydantic v2 models with ","type":"text"},{"text":"model_config","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Type hints throughout","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Async/await for all I/O operations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Proper imports organization","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Module-level constants (CHARACTER_LIMIT, API_BASE_URL)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"For Node/TypeScript: Load ","type":"text","marks":[{"type":"strong"}]},{"text":"⚡ TypeScript Implementation Guide","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/node_mcp_server.md","title":null}},{"type":"strong"}]},{"text":" and ensure the following:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Using ","type":"text"},{"text":"server.registerTool","type":"text","marks":[{"type":"code_inline"}]},{"text":" properly","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Zod schemas with ","type":"text"},{"text":".strict()","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"TypeScript strict mode enabled","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"No ","type":"text"},{"text":"any","type":"text","marks":[{"type":"code_inline"}]},{"text":" types - use proper types","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Explicit Promise\u003cT> return types","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Build process configured (","type":"text"},{"text":"npm run build","type":"text","marks":[{"type":"code_inline"}]},{"text":")","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 3: Review and Refine","type":"text"}]},{"type":"paragraph","content":[{"text":"After initial implementation:","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"3.1 Code Quality Review","type":"text"}]},{"type":"paragraph","content":[{"text":"To ensure quality, review the code for:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"DRY Principle","type":"text","marks":[{"type":"strong"}]},{"text":": No duplicated code between tools","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Composability","type":"text","marks":[{"type":"strong"}]},{"text":": Shared logic extracted into functions","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Consistency","type":"text","marks":[{"type":"strong"}]},{"text":": Similar operations return similar formats","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Error Handling","type":"text","marks":[{"type":"strong"}]},{"text":": All external calls have error handling","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Type Safety","type":"text","marks":[{"type":"strong"}]},{"text":": Full type coverage (Python type hints, TypeScript types)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Documentation","type":"text","marks":[{"type":"strong"}]},{"text":": Every tool has comprehensive docstrings/descriptions","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"3.2 Test and Build","type":"text"}]},{"type":"paragraph","content":[{"text":"Important:","type":"text","marks":[{"type":"strong"}]},{"text":" 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., ","type":"text"},{"text":"python server.py","type":"text","marks":[{"type":"code_inline"}]},{"text":" or ","type":"text"},{"text":"node dist/index.js","type":"text","marks":[{"type":"code_inline"}]},{"text":") will cause your process to hang indefinitely.","type":"text"}]},{"type":"paragraph","content":[{"text":"Safe ways to test the server:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use the evaluation harness (see Phase 4) - recommended approach","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Run the server in tmux to keep it outside your main process","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use a timeout when testing: ","type":"text"},{"text":"timeout 5s python server.py","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"paragraph","content":[{"text":"For Python:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Verify Python syntax: ","type":"text"},{"text":"python -m py_compile your_server.py","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Check imports work correctly by reviewing the file","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"To manually test: Run server in tmux, then test with evaluation harness in main process","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Or use the evaluation harness directly (it manages the server for stdio transport)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"For Node/TypeScript:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Run ","type":"text"},{"text":"npm run build","type":"text","marks":[{"type":"code_inline"}]},{"text":" and ensure it completes without errors","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Verify dist/index.js is created","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"To manually test: Run server in tmux, then test with evaluation harness in main process","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Or use the evaluation harness directly (it manages the server for stdio transport)","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"3.3 Use Quality Checklist","type":"text"}]},{"type":"paragraph","content":[{"text":"To verify implementation quality, load the appropriate checklist from the language-specific guide:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Python: see \"Quality Checklist\" in ","type":"text"},{"text":"🐍 Python Guide","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/python_mcp_server.md","title":null}}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Node/TypeScript: see \"Quality Checklist\" in ","type":"text"},{"text":"⚡ TypeScript Guide","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/node_mcp_server.md","title":null}}]}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":3},"content":[{"text":"Phase 4: Create Evaluations","type":"text"}]},{"type":"paragraph","content":[{"text":"After implementing your MCP server, create comprehensive evaluations to test its effectiveness.","type":"text"}]},{"type":"paragraph","content":[{"text":"Load ","type":"text","marks":[{"type":"strong"}]},{"text":"✅ Evaluation Guide","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/evaluation.md","title":null}},{"type":"strong"}]},{"text":" for complete evaluation guidelines.","type":"text","marks":[{"type":"strong"}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"4.1 Understand Evaluation Purpose","type":"text"}]},{"type":"paragraph","content":[{"text":"Evaluations test whether LLMs can effectively use your MCP server to answer realistic, complex questions.","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"4.2 Create 10 Evaluation Questions","type":"text"}]},{"type":"paragraph","content":[{"text":"To create effective evaluations, follow the process outlined in the evaluation guide:","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Tool Inspection","type":"text","marks":[{"type":"strong"}]},{"text":": List available tools and understand their capabilities","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Content Exploration","type":"text","marks":[{"type":"strong"}]},{"text":": Use READ-ONLY operations to explore available data","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Question Generation","type":"text","marks":[{"type":"strong"}]},{"text":": Create 10 complex, realistic questions","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Answer Verification","type":"text","marks":[{"type":"strong"}]},{"text":": Solve each question yourself to verify answers","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"4.3 Evaluation Requirements","type":"text"}]},{"type":"paragraph","content":[{"text":"Each question must be:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Independent","type":"text","marks":[{"type":"strong"}]},{"text":": Not dependent on other questions","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Read-only","type":"text","marks":[{"type":"strong"}]},{"text":": Only non-destructive operations required","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Complex","type":"text","marks":[{"type":"strong"}]},{"text":": Requiring multiple tool calls and deep exploration","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Realistic","type":"text","marks":[{"type":"strong"}]},{"text":": Based on real use cases humans would care about","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Verifiable","type":"text","marks":[{"type":"strong"}]},{"text":": Single, clear answer that can be verified by string comparison","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Stable","type":"text","marks":[{"type":"strong"}]},{"text":": Answer won't change over time","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"4.4 Output Format","type":"text"}]},{"type":"paragraph","content":[{"text":"Create an XML file with this structure:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"xml"},"content":[{"text":"\u003cevaluation>\n \u003cqa_pair>\n \u003cquestion>Find discussions about AI model launches with animal codenames. One model needed a specific safety designation that uses the format ASL-X. What number X was being determined for the model named after a spotted wild cat?\u003c/question>\n \u003canswer>3\u003c/answer>\n \u003c/qa_pair>\n\u003c!-- More qa_pairs... -->\n\u003c/evaluation>","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":1},"content":[{"text":"Reference Files","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"📚 Documentation Library","type":"text"}]},{"type":"paragraph","content":[{"text":"Load these resources as needed during development:","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Core MCP Documentation (Load First)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"MCP Protocol","type":"text","marks":[{"type":"strong"}]},{"text":": Fetch from ","type":"text"},{"text":"https://modelcontextprotocol.io/llms-full.txt","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Complete MCP specification","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"📋 MCP Best Practices","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/mcp_best_practices.md","title":null}}]},{"text":" - Universal MCP guidelines including:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Server and tool naming conventions","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Response format guidelines (JSON vs Markdown)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Pagination best practices","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Character limits and truncation strategies","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Tool development guidelines","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Security and error handling standards","type":"text"}]}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"SDK Documentation (Load During Phase 1/2)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Python SDK","type":"text","marks":[{"type":"strong"}]},{"text":": Fetch from ","type":"text"},{"text":"https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"TypeScript SDK","type":"text","marks":[{"type":"strong"}]},{"text":": Fetch from ","type":"text"},{"text":"https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Language-Specific Implementation Guides (Load During Phase 2)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"🐍 Python Implementation Guide","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/python_mcp_server.md","title":null}}]},{"text":" - Complete Python/FastMCP guide with:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Server initialization patterns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Pydantic model examples","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Tool registration with ","type":"text"},{"text":"@mcp.tool","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Complete working examples","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Quality checklist","type":"text"}]}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"⚡ TypeScript Implementation Guide","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/node_mcp_server.md","title":null}}]},{"text":" - Complete TypeScript guide with:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Project structure","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Zod schema patterns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Tool registration with ","type":"text"},{"text":"server.registerTool","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Complete working examples","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Quality checklist","type":"text"}]}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Evaluation Guide (Load During Phase 4)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Evaluation Guide","type":"text","marks":[{"type":"link","attrs":{"href":"./reference/evaluation.md","title":null}}]},{"text":" - Complete evaluation creation guide with:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Question creation guidelines","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Answer verification strategies","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"XML format specifications","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Example questions and answers","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Running an evaluation with the provided scripts","type":"text"}]}]}]}]}]}]},"metadata":{"date":"2026-11-02","name":"mcp-builder","author":"@skillopedia","source":{"stars":78586,"repo_name":"awesome-claude-skills","origin_url":"https://github.com/ComposioHQ/awesome-claude-skills/blob/HEAD/mcp-builder/SKILL.md","repo_owner":"ComposioHQ","body_sha256":"b1010e90adcb8fd6bf57640df34ab6454fbf7e4216e150a4620f7caccadc4e63","cluster_key":"4bf8a0fd9e6c81f176baaf5a227936bdd989207d4afd98171a658e444363c645","clean_bundle":{"format":"clean-skill-bundle-v1","source":"ComposioHQ/awesome-claude-skills/mcp-builder/SKILL.md","text_bytes":122141,"source_commit":"be2a406907dbc61b73e6827ded415c96139d13a2","skills_sh_rank":4640,"attachment_count":8,"text_attachments":8,"attachment_storage":"skill_attachments","binary_attachments":0},"cluster_size":1,"skill_md_path":"mcp-builder/SKILL.md","import_metadata":{"date":"2026-11-02","author":"@skillopedia","version":"v1","category":"ai-agent-development","category_label":"AI"},"exact_dupes_collapsed_into_this":0},"license":"Complete terms in LICENSE.txt","version":"v1","category":"ai-agent-development","import_tag":"skills-sh-top20k-2026-11","description":"Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK)."}},"renderedAt":1793661825666}

MCP Server Development Guide 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. --- Process 🚀 High-Level Workflow Creating a high-quality MCP server involves four main phases: Phase 1: Deep Research and Planning 1.1 Understand Agent-Centric Design Principles Before diving into implementati…