Generated banner for MCP Builder
Generated logo for MCP Builder

MCP Builder

AnthropicOfficialPublished by Anthropic

  • Skill
  • Tool integration
  • Software development
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

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).
— the description by Anthropic

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

mcp-builder provides a structured, four-phase workflow for developing robust MCP servers. It covers the entire lifecycle from initial research and planning to implementation, testing, and the creation of standardized evaluations. The guide emphasizes best practices for tool design, schema definition using Zod or Pydantic, and proper error handling to ensure LLMs can effectively interact with external APIs.

What it does

  • Outlines a four-phase development process for MCP servers.
  • Provides guidance on selecting between TypeScript (v2) and Python SDKs.
  • Details best practices for tool naming, discoverability, and context management.
  • Explains how to implement structured tool inputs and outputs.
  • Includes instructions for testing servers with the MCP Inspector.
  • Defines a standardized XML format for creating LLM-based evaluations.

When to use it

  • When you need to build a new MCP server to connect an external API to an LLM.
  • When you are unsure whether to use the TypeScript or Python SDK for your project.
  • When you need to migrate an existing MCP server from v1 to v2.
  • When you need to create a test suite to verify your MCP server's performance.

Advantages

  • Promotes consistent, high-quality tool design across different languages.
  • Provides clear migration paths for existing SDK versions.
  • Encourages the creation of verifiable, complex evaluation scenarios.
  • Focuses on actionable error messages to improve agent reliability.

Usage examples

“How do I start building a new MCP server in TypeScript?”
The agent will guide you through setting up a project using the v2 TypeScript SDK, including project structure and tool registration patterns.
“What are the best practices for naming tools in an MCP server?”
The agent will explain the importance of descriptive, action-oriented names and consistent prefixes like github_create_issue.
“How can I verify that my MCP server is working correctly?”
The agent will provide instructions on using the MCP Inspector and creating a 10-question evaluation suite in the required XML format.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/anthropics/mcp-builder/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip mcp-builder.zip -d .agents/skills

Documentation by Anthropic

MCP Server Development Guide

Overview

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.


Process

🚀 High-Level Workflow

Creating a high-quality MCP server involves four main phases:

Phase 1: Deep Research and Planning
1.1 Understand Modern MCP Design

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.

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.

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.

Actionable Error Messages: Error messages should guide agents toward solutions with specific suggestions and next steps.

1.2 Study MCP Protocol Documentation

Navigate the MCP specification:

Start with the sitemap to find relevant pages: https://modelcontextprotocol.io/sitemap.xml

Then fetch specific pages with .md suffix for markdown format (e.g., https://modelcontextprotocol.io/specification/draft.md).

Key pages to review:

  • Specification overview and architecture

  • Transport mechanisms (streamable HTTP, stdio)

  • Tool, resource, and prompt definitions

1.3 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 framework documentation:

For TypeScript (recommended):

The TypeScript SDK has two major versions. Pick one before writing code:

  • v2 (@modelcontextprotocol/server): the current stable release. Use it for new servers.

  • v1 (@modelcontextprotocol/sdk): receives bug and security fixes only. Use it only when the project's package.json already depends on @modelcontextprotocol/sdk, or migrate that project with npx @modelcontextprotocol/codemod@latest v1-to-v2 .

If the project already uses v1, tell the user once, in a sentence or two, that v2 (@modelcontextprotocol/server) is the current stable release, that v1 receives only bug and security fixes, and that npx @modelcontextprotocol/codemod@latest v1-to-v2 . migrates the project. Then continue with v1 unless the user asks to migrate.

Don't mix the two in one project: v1 code samples (imports from @modelcontextprotocol/sdk/...) don't apply to v2.

  • TypeScript SDK (v2): Use WebFetch to load https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md; the full docs index is https://ts.sdk.modelcontextprotocol.io/v2/llms.txt

  • ⚡ TypeScript Guide (v2) - TypeScript patterns and examples

  • For v1 projects only: https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/v1.x/README.md and the TypeScript Guide (v1)

For Python:

  • Python SDK: Use WebFetch to load https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md

  • 🐍 Python Guide - Python patterns and examples

1.4 Plan Your Implementation

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: Prioritize comprehensive API coverage. List endpoints to implement, starting with the most common operations.


Phase 2: Implementation
2.1 Set Up Project Structure

See language-specific guides for project setup:

2.2 Implement Core Infrastructure

Create shared utilities:

  • API client with authentication

  • Error handling helpers

  • Response formatting (JSON/Markdown)

  • Pagination support

2.3 Implement Tools

For each tool:

Input Schema:

  • Use Zod (TypeScript) or Pydantic (Python)

  • Include constraints and clear descriptions

  • Add 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

Tool Description:

  • Concise summary of functionality

  • Parameter descriptions

  • Return type schema

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

Annotations:

  • readOnlyHint: true/false

  • destructiveHint: true/false

  • idempotentHint: true/false

  • openWorldHint: true/false


Phase 3: Review and Test
3.1 Code Quality

Review for:

  • No duplicated code (DRY principle)

  • Consistent error handling

  • Full type coverage

  • Clear tool descriptions

3.2 Build and Test

TypeScript:

  • Run npm run build to verify compilation

  • v2 projects: run the self-check script from the v2 guide against the built server

  • Test with MCP Inspector: npx @modelcontextprotocol/inspector

Python:

  • Verify syntax: python -m py_compile your_server.py

  • Test with MCP Inspector

See language-specific guides for detailed testing approaches and quality checklists.


Phase 4: Create Evaluations

After implementing your MCP server, create comprehensive evaluations to test its effectiveness.

Load ✅ Evaluation Guide for complete evaluation guidelines.

4.1 Understand Evaluation Purpose

Use evaluations to test whether LLMs can effectively use your MCP server to answer realistic, complex questions.

4.2 Create 10 Evaluation Questions

To create effective evaluations, follow the process outlined in the evaluation guide:

  1. Tool Inspection: List available tools and understand their capabilities

  2. Content Exploration: Use READ-ONLY operations to explore available data

  3. Question Generation: Create 10 complex, realistic questions

  4. Answer Verification: Solve each question yourself to verify answers

4.3 Evaluation Requirements

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

  • Realistic: Based on real use cases humans would care about

  • Verifiable: Single, clear answer that can be verified by string comparison

  • Stable: Answer won't change over time

4.4 Output Format

Create an XML file with this structure:

<evaluation>
  <qa_pair>
    <question>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?</question>
    <answer>3</answer>
  </qa_pair>
<!-- More qa_pairs... -->
</evaluation>

Reference Files

📚 Documentation Library

Load these resources as needed during development:

Core MCP Documentation (Load First)
  • MCP Protocol: Start with sitemap at https://modelcontextprotocol.io/sitemap.xml, then fetch specific pages with .md suffix

  • 📋 MCP Best Practices - Universal MCP guidelines including:

    • Server and tool naming conventions

    • Response format guidelines (JSON vs Markdown)

    • Pagination best practices

    • Transport selection (streamable HTTP vs stdio)

    • Security and error handling standards

SDK Documentation (Load During Phase 1/2)
  • Python SDK: Fetch from https://raw.githubusercontent.com/modelcontextprotocol/python-sdk/main/README.md

  • TypeScript SDK (v2): Fetch from https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/main/README.md; full docs index at https://ts.sdk.modelcontextprotocol.io/v2/llms.txt

  • TypeScript SDK (v1, existing v1 projects only): Fetch from https://raw.githubusercontent.com/modelcontextprotocol/typescript-sdk/v1.x/README.md

Language-Specific Implementation Guides (Load During Phase 2)
  • 🐍 Python Implementation Guide - Complete Python/FastMCP guide with:

    • Server initialization patterns

    • Pydantic model examples

    • Tool registration with @mcp.tool

    • Complete working examples

    • Quality checklist

  • ⚡ TypeScript Implementation Guide (SDK v2) - Complete TypeScript guide for @modelcontextprotocol/server with:

    • Project setup and the server factory

    • Tool design: Zod 4 schemas, output formats, pagination, errors

    • A complete example serving stdio and Streamable HTTP, plus bearer auth

    • Resources, prompts, and notifications

    • A self-check script to verify the built server

    • Links to SDK examples for advanced features

    • A v1 → v2 translation table, migration steps, and a quality checklist

  • ⚡ TypeScript Implementation Guide (SDK v1) - The equivalent guide for existing @modelcontextprotocol/sdk projects

Evaluation Guide (Load During Phase 4)
  • ✅ Evaluation Guide - Complete evaluation creation guide with:

    • Question creation guidelines

    • Answer verification strategies

    • XML format specifications

    • Example questions and answers

    • Running an evaluation with the provided scripts

Files

scripts/evaluation.py

"""MCP Server Evaluation Harness

This script evaluates MCP servers by running test questions against them using Claude.
"""

import argparse
import asyncio
import json
import re
import sys
import time
import traceback
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import Any

from anthropic import Anthropic

from connections import create_connection

EVALUATION_PROMPT = """You are an AI assistant with access to tools.

When given a task, you MUST:
1. Use the available tools to complete the task
2. Provide summary of each step in your approach, wrapped in <summary> tags
3. Provide feedback on the tools provided, wrapped in <feedback> tags
4. Provide your final response, wrapped in <response> tags

Summary Requirements:
- In your <summary> tags, you must explain:
  - The steps you took to complete the task
  - Which tools you used, in what order, and why
  - The inputs you provided to each tool
  - The outputs you received from each tool
  - A summary for how you arrived at the response

Feedback Requirements:
- In your <feedback> tags, provide constructive feedback on the tools:
  - Comment on tool names: Are they clear and descriptive?
  - Comment on input parameters: Are they well-documented? Are required vs optional parameters clear?
  - Comment on descriptions: Do they accurately describe what the tool does?
  - Comment on any errors encountered during tool usage: Did the tool fail to execute? Did the tool return too many tokens?
  - Identify specific areas for improvement and explain WHY they would help
  - Be specific and actionable in your suggestions

Response Requirements:
- Your response should be concise and directly address what was asked
- Always wrap your final response in <response> tags
- If you cannot solve the task return <response>NOT_FOUND</response>
- For numeric responses, provide just the number
- For IDs, provide just the ID
- For names or text, provide the exact text requested
- Your response should go last"""


def parse_evaluation_file(file_path: Path) -> list[dict[str, Any]]:
    """Parse XML evaluation file with qa_pair elements."""
    try:
        tree = ET.parse(file_path)
        root = tree.getroot()
        evaluations = []

        for qa_pair in root.findall(".//qa_pair"):
            question_elem = qa_pair.find("question")
            answer_elem = qa_pair.find("answer")

            if question_elem is not None and answer_elem is not None:
                evaluations.append({
                    "question": (question_elem.text or "").strip(),
                    "answer": (answer_elem.text or "").strip(),
                })

        return evaluations
    except Exception as e:
        print(f"Error parsing evaluation file {file_path}: {e}")
        return []


def extract_xml_content(text: str, tag: str) -> str | None:
    """Extract content from XML tags."""
    pattern = rf"<{tag}>(.*?)</{tag}>"
    matches = re.findall(pattern, text, re.DOTALL)
    return matches[-1].strip() if matches else None


async def agent_loop(
    client: Anthropic,
    model: str,
    question: str,
    tools: list[dict[str, Any]],
    connection: Any,
) -> tuple[str, dict[str, Any]]:
    """Run the agent loop with MCP tools."""
    messages = [{"role": "user", "content": question}]

    response = await asyncio.to_thread(
        client.messages.create,
        model=model,
        max_tokens=4096,
        system=EVALUATION_PROMPT,
        messages=messages,
        tools=tools,
    )

    messages.append({"role": "assistant", "content": response.content})

    tool_metrics = {}

    while response.stop_reason == "tool_use":
        tool_use = next(block for block in response.content if block.type == "tool_use")
        tool_name = tool_use.name
        tool_input = tool_use.input

        tool_start_ts = time.time()
        try:
            tool_result = await connection.call_tool(tool_name, tool_input)
            tool_response = json.dumps(tool_result) if isinstance(tool_result, (dict, list)) else str(tool_result)
        except Exception as e:
            tool_response = f"Error executing tool {tool_name}: {str(e)}\n"
            tool_response += traceback.format_exc()
        tool_duration = time.time() - tool_start_ts

        if tool_name not in tool_metrics:
            tool_metrics[tool_name] = {"count": 0, "durations": []}
        tool_metrics[tool_name]["count"] += 1
        tool_metrics[tool_name]["durations"].append(tool_duration)

        messages.append({
            "role": "user",
            "content": [{
                "type": "tool_result",
                "tool_use_id": tool_use.id,
                "content": tool_response,
            }]
        })

        response = await asyncio.to_thread(
            client.messages.create,
            model=model,
            max_tokens=4096,
            system=EVALUATION_PROMPT,
            messages=messages,
            tools=tools,
        )
        messages.append({"role": "assistant", "content": response.content})

    response_text = next(
        (block.text for block in response.content if hasattr(block, "text")),
        None,
    )
    return response_text, tool_metrics


async def evaluate_single_task(
    client: Anthropic,
    model: str,
    qa_pair: dict[str, Any],
    tools: list[dict[str, Any]],
    connection: Any,
    task_index: int,
) -> dict[str, Any]:
    """Evaluate a single QA pair with the given tools."""
    start_time = time.time()

    print(f"Task {task_index + 1}: Running task with question: {qa_pair['question']}")
    response, tool_metrics = await agent_loop(client, model, qa_pair["question"], tools, connection)

    response_value = extract_xml_content(response, "response")
    summary = extract_xml_content(response, "summary")
    feedback = extract_xml_content(response, "feedback")

    duration_seconds = time.time() - start_time

    return {
        "question": qa_pair["question"],
        "expected": qa_pair["answer"],
        "actual": response_value,
        "score": int(response_value == qa_pair["answer"]) if response_value else 0,
        "total_duration": duration_seconds,
        "tool_calls": tool_metrics,
        "num_tool_calls": sum(len(metrics["durations"]) for metrics in tool_metrics.values()),
        "summary": summary,
        "feedback": feedback,
    }


REPORT_HEADER = """
# Evaluation Report

## Summary

- **Accuracy**: {correct}/{total} ({accuracy:.1f}%)
- **Average Task Duration**: {average_duration_s:.2f}s
- **Average Tool Calls per Task**: {average_tool_calls:.2f}
- **Total Tool Calls**: {total_tool_calls}

---
"""

TASK_TEMPLATE = """
### Task {task_num}

**Question**: {question}
**Ground Truth Answer**: `{expected_answer}`
**Actual Answer**: `{actual_answer}`
**Correct**: {correct_indicator}
**Duration**: {total_duration:.2f}s
**Tool Calls**: {tool_calls}

**Summary**
{summary}

**Feedback**
{feedback}

---
"""


async def run_evaluation(
    eval_path: Path,
    connection: Any,
    model: str = "claude-3-7-sonnet-20250219",
) -> str:
    """Run evaluation with MCP server tools."""
    print("🚀 Starting Evaluation")

    client = Anthropic()

    tools = await connection.list_tools()
    print(f"📋 Loaded {len(tools)} tools from MCP server")

    qa_pairs = parse_evaluation_file(eval_path)
    print(f"📋 Loaded {len(qa_pairs)} evaluation tasks")

    results = []
    for i, qa_pair in enumerate(qa_pairs):
        print(f"Processing task {i + 1}/{len(qa_pairs)}")
        result = await evaluate_single_task(client, model, qa_pair, tools, connection, i)
        results.append(result)

    correct = sum(r["score"] for r in results)
    accuracy = (correct / len(results)) * 100 if results else 0
    average_duration_s = sum(r["total_duration"] for r in results) / len(results) if results else 0
    average_tool_calls = sum(r["num_tool_calls"] for r in results) / len(results) if results else 0
    total_tool_calls = sum(r["num_tool_calls"] for r in results)

    report = REPORT_HEADER.format(
        correct=correct,
        total=len(results),
        accuracy=accuracy,
        average_duration_s=average_duration_s,
        average_tool_calls=average_tool_calls,
        total_tool_calls=total_tool_calls,
    )

    report += "".join([
        TASK_TEMPLATE.format(
            task_num=i + 1,
            question=qa_pair["question"],
            expected_answer=qa_pair["answer"],
            actual_answer=result["actual"] or "N/A",
            correct_indicator="✅" if result["score"] else "❌",
            total_duration=result["total_duration"],
            tool_calls=json.dumps(result["tool_calls"], indent=2),
            summary=result["summary"] or "N/A",
            feedback=result["feedback"] or "N/A",
        )
        for i, (qa_pair, result) in enumerate(zip(qa_pairs, results))
    ])

    return report


def parse_headers(header_list: list[str]) -> dict[str, str]:
    """Parse header strings in format 'Key: Value' into a dictionary."""
    headers = {}
    if not header_list:
        return headers

    for header in header_list:
        if ":" in header:
            key, value = header.split(":", 1)
            headers[key.strip()] = value.strip()
        else:
            print(f"Warning: Ignoring malformed header: {header}")
    return headers


def parse_env_vars(env_list: list[str]) -> dict[str, str]:
    """Parse environment variable strings in format 'KEY=VALUE' into a dictionary."""
    env = {}
    if not env_list:
        return env

    for env_var in env_list:
        if "=" in env_var:
            key, value = env_var.split("=", 1)
            env[key.strip()] = value.strip()
        else:
            print(f"Warning: Ignoring malformed environment variable: {env_var}")
    return env


async def main():
    parser = argparse.ArgumentParser(
        description="Evaluate MCP servers using test questions",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Evaluate a local stdio MCP server
  python evaluation.py -t stdio -c python -a my_server.py eval.xml

  # Evaluate an SSE MCP server
  python evaluation.py -t sse -u https://example.com/mcp -H "Authorization: Bearer token" eval.xml

  # Evaluate an HTTP MCP server with custom model
  python evaluation.py -t http -u https://example.com/mcp -m claude-3-5-sonnet-20241022 eval.xml
        """,
    )

    parser.add_argument("eval_file", type=Path, help="Path to evaluation XML file")
    parser.add_argument("-t", "--transport", choices=["stdio", "sse", "http"], default="stdio", help="Transport type (default: stdio)")
    parser.add_argument("-m", "--model", default="claude-3-7-sonnet-20250219", help="Claude model to use (default: claude-3-7-sonnet-20250219)")

    stdio_group = parser.add_argument_group("stdio options")
    stdio_group.add_argument("-c", "--command", help="Command to run MCP server (stdio only)")
    stdio_group.add_argument("-a", "--args", nargs="+", help="Arguments for the command (stdio only)")
    stdio_group.add_argument("-e", "--env", nargs="+", help="Environment variables in KEY=VALUE format (stdio only)")

    remote_group = parser.add_argument_group("sse/http options")
    remote_group.add_argument("-u", "--url", help="MCP server URL (sse/http only)")
    remote_group.add_argument("-H", "--header", nargs="+", dest="headers", help="HTTP headers in 'Key: Value' format (sse/http only)")

    parser.add_argument("-o", "--output", type=Path, help="Output file for evaluation report (default: stdout)")

    args = parser.parse_args()

    if not args.eval_file.exists():
        print(f"Error: Evaluation file not found: {args.eval_file}")
        sys.exit(1)

    headers = parse_headers(args.headers) if args.headers else None
    env_vars = parse_env_vars(args.env) if args.env else None

    try:
        connection = create_connection(
            transport=args.transport,
            command=args.command,
            args=args.args,
            env=env_vars,
            url=args.url,
            headers=headers,
        )
    except ValueError as e:
        print(f"Error: {e}")
        sys.exit(1)

    print(f"🔗 Connecting to MCP server via {args.transport}...")

    async with connection:
        print("✅ Connected successfully")
        report = await run_evaluation(args.eval_file, connection, args.model)

        if args.output:
            args.output.write_text(report)
            print(f"\n✅ Report saved to {args.output}")
        else:
            print("\n" + report)


if __name__ == "__main__":
    asyncio.run(main())

Requirements and compatibility

Written for: Claude Code, Claude apps

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Names Claude Code tools, Needs an MCP server, Needs network access, Needs Python, Needs Node.js

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Published by
Anthropic
Publisher
Anthropic (Official)
Source
anthropics/skills · skills/mcp-builder · commit 2c5958e
Licence
Apache License 2.0 (redistribution allowed)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by Anthropic.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download mcp-builder.zip