servers Documentation

Model Context Protocol Servers

89,457 stars TypeScript TypeScript 1 file · ~32,051 tokens
RAW Doc

Docker & Self-Hosted Deployment Verified OCI

Deploy servers on any server, homelab, or cloud container platform.

1-Click Terminal Command
bash (docker run)
docker run -d --name servers --restart always modelcontextprotocol/servers:latest

1. Project Overview & Quickstart (modelcontextprotocol/servers)

File: README.md

Model Context Protocol servers

This repository is a collection of reference implementations for the Model Context Protocol (MCP), as well as references to community-built servers and additional resources.

[!IMPORTANT]
If you are looking for a list of MCP servers, you can browse published servers on the MCP Registry. The repository served by this README is dedicated to housing just the small number of reference servers maintained by the MCP steering group.

[!WARNING]
The servers in this repository are intended as reference implementations to demonstrate MCP features and SDK usage. They are meant to serve as educational examples for developers building their own MCP servers, not as production-ready solutions. Developers should evaluate their own security requirements and implement appropriate safeguards based on their specific threat model and use case.

The servers in this repository showcase the versatility and extensibility of MCP, demonstrating how it can be used to give Large Language Models (LLMs) secure, controlled access to tools and data sources.
Typically, each MCP server is implemented with an MCP SDK:

🌟 Reference Servers

These servers aim to demonstrate MCP features and the official SDKs.

  • Everything - Reference / test server with prompts, resources, and tools.
  • Fetch - Web content fetching and conversion for efficient LLM usage.
  • Filesystem - Secure file operations with configurable access controls.
  • Git - Tools to read, search, and manipulate Git repositories.
  • Memory - Knowledge graph-based persistent memory system.
  • Sequential Thinking - Dynamic and reflective problem-solving through thought sequences.
  • Time - Time and timezone conversion capabilities.

Archived

The following reference servers are now archived and can be found at servers-archived.

  • AWS KB Retrieval - Retrieval from AWS Knowledge Base using Bedrock Agent Runtime.
  • Brave Search - Web and local search using Brave's Search API. Has been replaced by the official server.
  • EverArt - AI image generation using various models.
  • GitHub - Repository management, file operations, and GitHub API integration.
  • GitLab - GitLab API, enabling project management.
  • Google Drive - File access and search capabilities for Google Drive.
  • Google Maps - Location services, directions, and place details.
  • PostgreSQL - Read-only database access with schema inspection.
  • Puppeteer - Browser automation and web scraping.
  • Redis - Interact with Redis key-value stores.
  • Sentry - Retrieving and analyzing issues from Sentry.io.
  • Slack - Channel management and messaging capabilities. Now maintained by Zencoder
  • SQLite - Database interaction and business intelligence capabilities.

🚀 Getting Started

Using MCP Servers in this Repository

TypeScript-based servers in this repository can be used directly with npx.

For example, this will start the Memory server:

sh
npx -y @modelcontextprotocol/server-memory

Python-based servers in this repository can be used directly with uvx or pip. uvx is recommended for ease of use and setup.

For example, this will start the Git server:

sh
# With uvx
uvx mcp-server-git

# With pip
pip install mcp-server-git
python -m mcp_server_git

Follow these instructions to install uv / uvx and these to install pip.

Using an MCP Client

However, running a server on its own isn't very useful, and should instead be configured into an MCP client. For example, here's the Claude Desktop configuration to use the above server:

json
{
  "mcpServers": {
    "memory": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-memory"]
    }
  }
}

On Windows, wrap npx with cmd /c:

json
{
  "mcpServers": {
    "memory": {
      "command": "cmd",
      "args": ["/c", "npx", "-y", "@modelcontextprotocol/server-memory"]
    }
  }
}

Additional examples of using the Claude Desktop as an MCP client might look like:

json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"]
    },
    "git": {
      "command": "uvx",
      "args": ["mcp-server-git", "--repository", "path/to/git/repo"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "<YOUR_TOKEN>"
      }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
    }
  }
}

On Windows, apply the same wrapper to each npx-based entry above by changing "command" to "cmd" and prepending "/c", "npx" to the existing args. Leave uvx entries unchanged.

🛠️ Creating Your Own Server

Interested in creating your own MCP server? Visit the official documentation at modelcontextprotocol.io for comprehensive guides, best practices, and technical details on implementing MCP servers.

📚 Learn More

See ADDITIONAL.md for a curated list of frameworks and resources that simplify building MCP servers and clients.

🤝 Contributing

See CONTRIBUTING.md for information about contributing to this repository.

📦 Releasing

See RELEASING.md for how packages are published (OIDC trusted publishing from CI — no registry tokens) and how to retry a failed publish.

🔒 Security

See SECURITY.md for reporting security vulnerabilities.

📜 License

This project is licensed under the Apache License, Version 2.0 for new contributions, with existing code under MIT - see the LICENSE file for details.

💬 Community

⭐ Support

If you find MCP servers useful, please consider starring the repository and contributing new servers or improvements!


Managed by Anthropic, but built together with the community. The Model Context Protocol is open source and we encourage everyone to contribute their own servers and improvements!


File: src/time/README.md

Time MCP Server

A Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.

Source: https://github.com/modelcontextprotocol/servers/tree/main/src/time

Available Tools

  • get_current_time - Get current time in a specific timezone or system timezone.

    • Required arguments:
      • timezone (string): IANA timezone name (e.g., 'America/New_York', 'Europe/London')
  • convert_time - Convert time between timezones.

    • Required arguments:
      • source_timezone (string): Source IANA timezone name
      • time (string): Time in 24-hour format (HH:MM)
      • target_timezone (string): Target IANA timezone name

Installation

When using uv no specific installation is needed. We will
use uvx to directly run mcp-server-time.

bash
uvx mcp-server-time

Using PIP

Alternatively you can install mcp-server-time via pip:

bash
pip install mcp-server-time

After installation, you can run it as a script using:

bash
python -m mcp_server_time

Configuration

Configure for Claude.app

Add to your Claude settings:

Using uvx

json
{
  "mcpServers": {
    "time": {
      "command": "uvx",
      "args": ["mcp-server-time"]
    }
  }
}

Using docker

json
{
  "mcpServers": {
    "time": {
      "command": "docker",
      "args": ["run", "-i", "--rm", "-e", "LOCAL_TIMEZONE", "mcp/time"]
    }
  }
}

Using pip installation

json
{
  "mcpServers": {
    "time": {
      "command": "python",
      "args": ["-m", "mcp_server_time"]
    }
  }
}

Configure for Zed

Add to your Zed settings.json:

Using uvx

json
"context_servers": [
  "mcp-server-time": {
    "command": "uvx",
    "args": ["mcp-server-time"]
  }
],

Using pip installation

json
"context_servers": {
  "mcp-server-time": {
    "command": "python",
    "args": ["-m", "mcp_server_time"]
  }
},

Configure for VS Code

For quick installation, use one of the one-click install buttons below...

For manual installation, add the following JSON block to your User Settings (JSON) file in VS Code. You can do this by pressing Ctrl + Shift + P and typing Preferences: Open User Settings (JSON).

Optionally, you can add it to a file called .vscode/mcp.json in your workspace. This will allow you to share the configuration with others.

Note that the mcp key is needed when using the mcp.json file.

Using uvx

json
{
  "mcp": {
    "servers": {
      "time": {
        "command": "uvx",
        "args": ["mcp-server-time"]
      }
    }
  }
}

Using Docker

json
{
  "mcp": {
    "servers": {
      "time": {
        "command": "docker",
        "args": ["run", "-i", "--rm", "mcp/time"]
      }
    }
  }
}

Configure for Zencoder

  1. Go to the Zencoder menu (...)
  2. From the dropdown menu, select Agent Tools
  3. Click on the Add Custom MCP
  4. Add the name and server configuration from below, and make sure to hit the Install button

Using uvx

json
{
    "command": "uvx",
    "args": ["mcp-server-time"]
  }

Customization - System Timezone

By default, the server automatically detects your system's timezone. You can override this by adding the argument --local-timezone to the args list in the configuration.

Example:

json
{
  "command": "python",
  "args": ["-m", "mcp_server_time", "--local-timezone=America/New_York"]
}

Example Interactions

  1. Get current time:
json
{
  "name": "get_current_time",
  "arguments": {
    "timezone": "Europe/Warsaw"
  }
}

Response:

json
{
  "timezone": "Europe/Warsaw",
  "datetime": "2024-01-01T13:00:00+01:00",
  "is_dst": false
}
  1. Convert time between timezones:
json
{
  "name": "convert_time",
  "arguments": {
    "source_timezone": "America/New_York",
    "time": "16:30",
    "target_timezone": "Asia/Tokyo"
  }
}

Response:

json
{
  "source": {
    "timezone": "America/New_York",
    "datetime": "2024-01-01T12:30:00-05:00",
    "is_dst": false
  },
  "target": {
    "timezone": "Asia/Tokyo",
    "datetime": "2024-01-01T12:30:00+09:00",
    "is_dst": false
  },
  "time_difference": "+13.0h",
}

Debugging

You can use the MCP inspector to debug the server. For uvx installations:

bash
npx @modelcontextprotocol/inspector uvx mcp-server-time

Or if you've installed the package in a specific directory or are developing on it:

bash
cd path/to/servers/src/time
npx @modelcontextprotocol/inspector uv run mcp-server-time

Examples of Questions for Claude

  1. "What time is it now?" (will use system timezone)
  2. "What time is it in Tokyo?"
  3. "When it's 4 PM in New York, what time is it in London?"
  4. "Convert 9:30 AM Tokyo time to New York time"

Build

Docker build:

bash
cd src/time
docker build -t mcp/time .

Contributing

We encourage contributions to help expand and improve mcp-server-time. Whether you want to add new time-related tools, enhance existing functionality, or improve documentation, your input is valuable.

For examples of other MCP servers and implementation patterns, see:
https://github.com/modelcontextprotocol/servers

Pull requests are welcome! Feel free to contribute new ideas, bug fixes, or enhancements to make mcp-server-time even more powerful and useful.

License

mcp-server-time is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.


File: src/sequentialthinking/README.md

Sequential Thinking MCP Server

An MCP server implementation that provides a tool for dynamic and reflective problem-solving through a structured thinking process.

Published on npm as @modelcontextprotocol/server-sequential-thinking.

Features

  • Break down complex problems into manageable steps
  • Revise and refine thoughts as understanding deepens
  • Branch into alternative paths of reasoning
  • Adjust the total number of thoughts dynamically
  • Generate and verify solution hypotheses

Tool

sequential_thinking

Facilitates a detailed, step-by-step thinking process for problem-solving and analysis.

Inputs:

  • thought (string): The current thinking step
  • nextThoughtNeeded (boolean): Whether another thought step is needed
  • thoughtNumber (integer): Current thought number
  • totalThoughts (integer): Estimated total thoughts needed
  • isRevision (boolean, optional): Whether this revises previous thinking
  • revisesThought (integer, optional): Which thought is being reconsidered
  • branchFromThought (integer, optional): Branching point thought number
  • branchId (string, optional): Branch identifier
  • needsMoreThoughts (boolean, optional): If more thoughts are needed

Usage

The Sequential Thinking tool is designed for:

  • Breaking down complex problems into steps
  • Planning and design with room for revision
  • Analysis that might need course correction
  • Problems where the full scope might not be clear initially
  • Tasks that need to maintain context over multiple steps
  • Situations where irrelevant information needs to be filtered out

In practice, you do not call sequential_thinking directly by hand unless your client exposes raw tool calls. Instead, connect the server to an MCP-aware host and ask the model to think through a problem step by step. The host can then decide to call the tool one or more times while it works.

What it looks like in use

Example prompts that typically benefit from this tool:

  • Plan a database migration from PostgreSQL 14 to 16, list risks, and revise the plan if downtime exceeds 5 minutes.
  • Debug why this deployment only fails in production and show your reasoning step by step.
  • Compare three architecture options for a file sync engine and branch if one assumption turns out to be wrong.

How to tell it is working

If your host or inspector shows tool activity, you should see repeated calls to sequential_thinking with fields such as:

  • thought
  • thoughtNumber
  • totalThoughts
  • nextThoughtNeeded

When the reasoning changes course, you may also see revision or branching fields like isRevision, revisesThought, branchFromThought, or branchId.

Quick manual verification

After installing the server in your MCP host:

  1. Restart or reload the host so it reconnects to the server.
  2. Confirm the sequential_thinking tool appears in the host's MCP tool list or inspector.
  3. Ask the host to solve a non-trivial problem in a step-by-step way.
  4. Verify that the host invokes the tool multiple times instead of returning a one-shot answer.

Configuration

Usage with Claude Desktop

Add this to your claude_desktop_config.json:

npx

json
{
  "mcpServers": {
    "sequential-thinking": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-sequential-thinking"
      ]
    }
  }
}

On Windows, use cmd /c to launch npx:

json
{
  "mcpServers": {
    "sequential-thinking": {
      "command": "cmd",
      "args": [
        "/c",
        "npx",
        "-y",
        "@modelcontextprotocol/server-sequential-thinking"
      ]
    }
  }
}

docker

json
{
  "mcpServers": {
    "sequentialthinking": {
      "command": "docker",
      "args": [
        "run",
        "--rm",
        "-i",
        "mcp/sequentialthinking"
      ]
    }
  }
}

To disable logging of thought information set env var: DISABLE_THOUGHT_LOGGING to true.

Usage with VS Code

For quick installation, click one of the installation buttons below...

For manual installation, you can configure the MCP server using one of these methods:

Method 1: User Configuration (Recommended)
Add the configuration to your user-level MCP configuration file. Open the Command Palette (Ctrl + Shift + P) and run MCP: Open User Configuration. This will open your user mcp.json file where you can add the server configuration.

Method 2: Workspace Configuration
Alternatively, you can add the configuration to a file called .vscode/mcp.json in your workspace. This will allow you to share the configuration with others.

For more details about MCP configuration in VS Code, see the official VS Code MCP documentation.

For NPX installation:

json
{
  "servers": {
    "sequential-thinking": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-sequential-thinking"
      ]
    }
  }
}

On Windows, use:

json
{
  "servers": {
    "sequential-thinking": {
      "command": "cmd",
      "args": [
        "/c",
        "npx",
        "-y",
        "@modelcontextprotocol/server-sequential-thinking"
      ]
    }
  }
}

For Docker installation:

json
{
  "servers": {
    "sequential-thinking": {
      "command": "docker",
      "args": [
        "run",
        "--rm",
        "-i",
        "mcp/sequentialthinking"
      ]
    }
  }
}

Usage with Codex CLI

Run the following:

npx

bash
codex mcp add sequential-thinking npx -y @modelcontextprotocol/server-sequential-thinking

Building

Docker:

bash
docker build -t mcp/sequentialthinking -f src/sequentialthinking/Dockerfile .

License

This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.


File: src/memory/README.md

Knowledge Graph Memory Server

A basic implementation of persistent memory using a local knowledge graph. This lets Claude remember information about the user across chats.

Published on npm as @modelcontextprotocol/server-memory.

Core Concepts

Entities

Entities are the primary nodes in the knowledge graph. Each entity has:

  • A unique name (identifier)
  • An entity type (e.g., "person", "organization", "event")
  • A list of observations

Example:

json
{
  "name": "John_Smith",
  "entityType": "person",
  "observations": ["Speaks fluent Spanish"]
}

Relations

Relations define directed connections between entities. They are always stored in active voice and describe how entities interact or relate to each other.

Example:

json
{
  "from": "John_Smith",
  "to": "Anthropic",
  "relationType": "works_at"
}

Observations

Observations are discrete pieces of information about an entity. They are:

  • Stored as strings
  • Attached to specific entities
  • Can be added or removed independently
  • Should be atomic (one fact per observation)

Example:

json
{
  "entityName": "John_Smith",
  "observations": [
    "Speaks fluent Spanish",
    "Graduated in 2019",
    "Prefers morning meetings"
  ]
}

API

Tools

  • create_entities

    • Create multiple new entities in the knowledge graph
    • Input: entities (array of objects)
      • Each object contains:
        • name (string): Entity identifier
        • entityType (string): Type classification
        • observations (string[]): Associated observations
    • Ignores entities with existing names
  • create_relations

    • Create multiple new relations between entities
    • Input: relations (array of objects)
      • Each object contains:
        • from (string): Source entity name
        • to (string): Target entity name
        • relationType (string): Relationship type in active voice
    • Skips duplicate relations
  • add_observations

    • Add new observations to existing entities
    • Input: observations (array of objects)
      • Each object contains:
        • entityName (string): Target entity
        • contents (string[]): New observations to add
    • Returns added observations per entity
    • Fails if entity doesn't exist
  • delete_entities

    • Remove entities and their relations
    • Input: entityNames (string[])
    • Cascading deletion of associated relations
    • Silent operation if entity doesn't exist
  • delete_observations

    • Remove specific observations from entities
    • Input: deletions (array of objects)
      • Each object contains:
        • entityName (string): Target entity
        • observations (string[]): Observations to remove
    • Silent operation if observation doesn't exist
  • delete_relations

    • Remove specific relations from the graph
    • Input: relations (array of objects)
      • Each object contains:
        • from (string): Source entity name
        • to (string): Target entity name
        • relationType (string): Relationship type
    • Silent operation if relation doesn't exist
  • read_graph

    • Read the entire knowledge graph
    • No input required
    • Returns complete graph structure with all entities and relations
  • search_nodes

    • Search for nodes based on query
    • Input: query (string)
    • Searches across:
      • Entity names
      • Entity types
      • Observation content
    • Returns matching entities and their relations
  • open_nodes

    • Retrieve specific nodes by name
    • Input: names (string[])
    • Returns:
      • Requested entities
      • Relations between requested entities
    • Silently skips non-existent nodes

Resources

  • knowledge-graph (memory://knowledge-graph)
    • The full knowledge graph as a readable MCP Resource
    • MIME type: application/json
    • Returns the same shape as read_graph (entities and relations)
    • Mutation tools (create_entities, create_relations, add_observations, delete_entities, delete_observations, delete_relations) emit notifications/resources/updated for this URI, so subscribed clients see live changes

Usage with Claude Desktop

Setup

Add this to your claude_desktop_config.json:

Docker

json
{
  "mcpServers": {
    "memory": {
      "command": "docker",
      "args": ["run", "-i", "-v", "claude-memory:/app/dist", "--rm", "mcp/memory"]
    }
  }
}

NPX

json
{
  "mcpServers": {
    "memory": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-memory"
      ]
    }
  }
}

On Windows, use cmd /c to launch npx:

json
{
  "mcpServers": {
    "memory": {
      "command": "cmd",
      "args": [
        "/c",
        "npx",
        "-y",
        "@modelcontextprotocol/server-memory"
      ]
    }
  }
}

NPX with custom setting

The server can be configured using the following environment variables:

json
{
  "mcpServers": {
    "memory": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-memory"
      ],
      "env": {
        "MEMORY_FILE_PATH": "/path/to/custom/memory.jsonl"
      }
    }
  }
}

On Windows, use:

json
{
  "mcpServers": {
    "memory": {
      "command": "cmd",
      "args": [
        "/c",
        "npx",
        "-y",
        "@modelcontextprotocol/server-memory"
      ],
      "env": {
        "MEMORY_FILE_PATH": "/path/to/custom/memory.jsonl"
      }
    }
  }
}
  • MEMORY_FILE_PATH: Path to the memory storage JSONL file (default: memory.jsonl in the server directory)

VS Code Installation Instructions

For quick installation, use one of the one-click installation buttons below:

For manual installation, you can configure the MCP server using one of these methods:

Method 1: User Configuration (Recommended)
Add the configuration to your user-level MCP configuration file. Open the Command Palette (Ctrl + Shift + P) and run MCP: Open User Configuration. This will open your user mcp.json file where you can add the server configuration.

Method 2: Workspace Configuration
Alternatively, you can add the configuration to a file called .vscode/mcp.json in your workspace. This will allow you to share the configuration with others.

For more details about MCP configuration in VS Code, see the official VS Code MCP documentation.

NPX

json
{
  "servers": {
    "memory": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-memory"
      ]
    }
  }
}

On Windows, use:

json
{
  "servers": {
    "memory": {
      "command": "cmd",
      "args": [
        "/c",
        "npx",
        "-y",
        "@modelcontextprotocol/server-memory"
      ]
    }
  }
}

Docker

json
{
  "servers": {
    "memory": {
      "command": "docker",
      "args": [
        "run",
        "-i",
        "-v",
        "claude-memory:/app/dist",
        "--rm",
        "mcp/memory"
      ]
    }
  }
}

System Prompt

The prompt for utilizing memory depends on the use case. Changing the prompt will help the model determine the frequency and types of memories created.

Here is an example prompt for chat personalization. You could use this prompt in the "Custom Instructions" field of a Claude.ai Project.

text
Follow these steps for each interaction:

1. User Identification:
   - You should assume that you are interacting with default_user
   - If you have not identified default_user, proactively try to do so.

2. Memory Retrieval:
   - Always begin your chat by saying only "Remembering..." and retrieve all relevant information from your knowledge graph
   - Always refer to your knowledge graph as your "memory"

3. Memory
   - While conversing with the user, be attentive to any new information that falls into these categories:
     a) Basic Identity (age, gender, location, job title, education level, etc.)
     b) Behaviors (interests, habits, etc.)
     c) Preferences (communication style, preferred language, etc.)
     d) Goals (goals, targets, aspirations, etc.)
     e) Relationships (personal and professional relationships up to 3 degrees of separation)

4. Memory Update:
   - If any new information was gathered during the interaction, update your memory as follows:
     a) Create entities for recurring organizations, people, and significant events
     b) Connect them to the current entities using relations
     c) Store facts about them as observations

Building

Docker:

sh
docker build -t mcp/memory -f src/memory/Dockerfile .

For Awareness: a prior mcp/memory volume contains an index.js file that could be overwritten by the new container. If you are using a docker volume for storage, delete the old docker volume's index.js file before starting the new container.

License

This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.


File: src/git/README.md

mcp-server-git: A git MCP server

Overview

A Model Context Protocol server for Git repository interaction and automation. This server provides tools to read, search, and manipulate Git repositories via Large Language Models.

Source: https://github.com/modelcontextprotocol/servers/tree/main/src/git

Please note that mcp-server-git is currently in early development. The functionality and available tools are subject to change and expansion as we continue to develop and improve the server.

Tools

  1. git_status

    • Shows the working tree status
    • Input:
      • repo_path (string): Path to Git repository
    • Returns: Current status of working directory as text output
  2. git_diff_unstaged

    • Shows changes in working directory not yet staged
    • Inputs:
      • repo_path (string): Path to Git repository
      • context_lines (number, optional): Number of context lines to show (default: 3)
    • Returns: Diff output of unstaged changes
  3. git_diff_staged

    • Shows changes that are staged for commit
    • Inputs:
      • repo_path (string): Path to Git repository
      • context_lines (number, optional): Number of context lines to show (default: 3)
    • Returns: Diff output of staged changes
  4. git_diff

    • Shows differences between branches or commits
    • Inputs:
      • repo_path (string): Path to Git repository
      • target (string): Target branch or commit to compare with
      • context_lines (number, optional): Number of context lines to show (default: 3)
    • Returns: Diff output comparing current state with target
  5. git_commit

    • Records changes to the repository
    • Inputs:
      • repo_path (string): Path to Git repository
      • message (string): Commit message
    • Returns: Confirmation with new commit hash
  6. git_add

    • Adds file contents to the staging area
    • Inputs:
      • repo_path (string): Path to Git repository
      • files (string[]): Array of file paths to stage
    • Returns: Confirmation of staged files
  7. git_reset

    • Unstages all staged changes
    • Input:
      • repo_path (string): Path to Git repository
    • Returns: Confirmation of reset operation
  8. git_log

    • Shows the commit logs with optional date filtering
    • Inputs:
      • repo_path (string): Path to Git repository
      • max_count (number, optional): Maximum number of commits to show (default: 10)
      • start_timestamp (string, optional): Start timestamp for filtering commits. Accepts ISO 8601 format (e.g., '2024-01-15T14:30:25'), relative dates (e.g., '2 weeks ago', 'yesterday'), or absolute dates (e.g., '2024-01-15', 'Jan 15 2024')
      • end_timestamp (string, optional): End timestamp for filtering commits. Accepts ISO 8601 format (e.g., '2024-01-15T14:30:25'), relative dates (e.g., '2 weeks ago', 'yesterday'), or absolute dates (e.g., '2024-01-15', 'Jan 15 2024')
    • Returns: Array of commit entries with hash, author, date, and message
  9. git_create_branch

    • Creates a new branch
    • Inputs:
      • repo_path (string): Path to Git repository
      • branch_name (string): Name of the new branch
      • base_branch (string, optional): Base branch to create from (defaults to current branch)
    • Returns: Confirmation of branch creation
  10. git_checkout

  • Switches branches
  • Inputs:
    • repo_path (string): Path to Git repository
    • branch_name (string): Name of branch to checkout
  • Returns: Confirmation of branch switch
  1. git_show
  • Shows the contents of a commit
  • Inputs:
    • repo_path (string): Path to Git repository
    • revision (string): The revision (commit hash, branch name, tag) to show
  • Returns: Contents of the specified commit
  1. git_branch
  • List Git branches
  • Inputs:
    • repo_path (string): Path to the Git repository.
    • branch_type (string): Whether to list local branches ('local'), remote branches ('remote') or all branches('all').
    • contains (string, optional): The commit sha that branch should contain. Do not pass anything to this param if no commit sha is specified
    • not_contains (string, optional): The commit sha that branch should NOT contain. Do not pass anything to this param if no commit sha is specified
  • Returns: List of branches

Installation

When using uv no specific installation is needed. We will
use uvx to directly run mcp-server-git.

Using PIP

Alternatively you can install mcp-server-git via pip:

text
pip install mcp-server-git

After installation, you can run it as a script using:

text
python -m mcp_server_git

Configuration

Usage with Claude Desktop

Add this to your claude_desktop_config.json:

Using uvx

json
"mcpServers": {
  "git": {
    "command": "uvx",
    "args": ["mcp-server-git", "--repository", "path/to/git/repo"]
  }
}

Using docker

  • Note: replace '/Users/username' with a path that you want to be accessible by this tool
json
"mcpServers": {
  "git": {
    "command": "docker",
    "args": ["run", "--rm", "-i", "--mount", "type=bind,src=/Users/username,dst=/Users/username", "mcp/git"]
  }
}

Using pip installation

json
"mcpServers": {
  "git": {
    "command": "python",
    "args": ["-m", "mcp_server_git", "--repository", "path/to/git/repo"]
  }
}

Usage with VS Code

For quick installation, use one of the one-click install buttons below...

For manual installation, you can configure the MCP server using one of these methods:

Method 1: User Configuration (Recommended)
Add the configuration to your user-level MCP configuration file. Open the Command Palette (Ctrl + Shift + P) and run MCP: Open User Configuration. This will open your user mcp.json file where you can add the server configuration.

Method 2: Workspace Configuration
Alternatively, you can add the configuration to a file called .vscode/mcp.json in your workspace. This will allow you to share the configuration with others.

For more details about MCP configuration in VS Code, see the official VS Code MCP documentation.

json
{
  "servers": {
    "git": {
      "command": "uvx",
      "args": ["mcp-server-git"]
    }
  }
}

For Docker installation:

json
{
  "mcp": {
    "servers": {
      "git": {
        "command": "docker",
        "args": [
          "run",
          "--rm",
          "-i",
          "--mount", "type=bind,src=${workspaceFolder},dst=/workspace",
          "mcp/git"
        ]
      }
    }
  }
}

Usage with [Zed](https://github.com/zed-industries/zed)

Add to your Zed settings.json:

Using uvx

json
"context_servers": [
  "mcp-server-git": {
    "command": {
      "path": "uvx",
      "args": ["mcp-server-git"]
    }
  }
],

Using pip installation

json
"context_servers": {
  "mcp-server-git": {
    "command": {
      "path": "python",
      "args": ["-m", "mcp_server_git"]
    }
  }
},

Usage with [Zencoder](https://zencoder.ai)

  1. Go to the Zencoder menu (...)
  2. From the dropdown menu, select Agent Tools
  3. Click on the Add Custom MCP
  4. Add the name (i.e. git) and server configuration from below, and make sure to hit the Install button

Using uvx

json
{
    "command": "uvx",
    "args": ["mcp-server-git", "--repository", "path/to/git/repo"]
}

Debugging

You can use the MCP inspector to debug the server. For uvx installations:

text
npx @modelcontextprotocol/inspector uvx mcp-server-git

Or if you've installed the package in a specific directory or are developing on it:

text
cd path/to/servers/src/git
npx @modelcontextprotocol/inspector uv run mcp-server-git

Running tail -n 20 -f ~/Library/Logs/Claude/mcp*.log will show the logs from the server and may
help you debug any issues.

Development

If you are doing local development, there are two ways to test your changes:

  1. Run the MCP inspector to test your changes. See Debugging for run instructions.

  2. Test using the Claude desktop app. Add the following to your claude_desktop_config.json:

Docker

json
{
  "mcpServers": {
    "git": {
      "command": "docker",
      "args": [
        "run",
        "--rm",
        "-i",
        "--mount", "type=bind,src=/Users/username/Desktop,dst=/projects/Desktop",
        "--mount", "type=bind,src=/path/to/other/allowed/dir,dst=/projects/other/allowed/dir,ro",
        "--mount", "type=bind,src=/path/to/file.txt,dst=/projects/path/to/file.txt",
        "mcp/git"
      ]
    }
  }
}

UVX

json
{
"mcpServers": {
  "git": {
    "command": "uv",
    "args": [
      "--directory",
      "//mcp-servers/src/git",
      "run",
      "mcp-server-git"
    ]
    }
  }
}

Build

Docker build:

bash
cd src/git
docker build -t mcp/git .

License

This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.


File: src/filesystem/README.md

Filesystem MCP Server

Node.js server implementing Model Context Protocol (MCP) for filesystem operations.

Published on npm as @modelcontextprotocol/server-filesystem.

Features

  • Read/write files
  • Create/list/delete directories
  • Move files/directories
  • Search files
  • Get file metadata
  • Dynamic directory access control via Roots

Directory Access Control

The server uses a flexible directory access control system. Directories can be specified via command-line arguments or dynamically via Roots.

Method 1: Command-line Arguments

Specify Allowed directories when starting the server:

bash
mcp-server-filesystem /path/to/dir1 /path/to/dir2

MCP clients that support Roots can dynamically update the Allowed directories.

Roots notified by Client to Server, completely replace any server-side Allowed directories when provided.

Important: If server starts without command-line arguments AND client doesn't support roots protocol (or provides empty roots), the server will throw an error during initialization.

This is the recommended method, as this enables runtime directory updates via roots/list_changed notifications without server restart, providing a more flexible and modern integration experience.

How It Works

The server's directory access control follows this flow:

  1. Server Startup

    • Server starts with directories from command-line arguments (if provided)
    • If no arguments provided, server starts with empty allowed directories
  2. Client Connection & Initialization

    • Client connects and sends initialize request with capabilities
    • Server checks if client supports roots protocol (capabilities.roots)
  3. Roots Protocol Handling (if client supports roots)

    • On initialization: Server requests roots from client via roots/list
    • Client responds with its configured roots
    • Server replaces ALL allowed directories with client's roots
    • On runtime updates: Client can send notifications/roots/list_changed
    • Server requests updated roots and replaces allowed directories again
  4. Fallback Behavior (if client doesn't support roots)

    • Server continues using command-line directories only
    • No dynamic updates possible
  5. Access Control

    • All filesystem operations are restricted to allowed directories
    • Use list_allowed_directories tool to see current directories
    • Server requires at least ONE allowed directory to operate

Note: The server will only allow operations within directories specified either via args or via Roots.

API

Tools

  • read_text_file

    • Read complete contents of a file as text
    • Inputs:
      • path (string)
      • head (number, optional): First N lines
      • tail (number, optional): Last N lines
    • Always treats the file as UTF-8 text regardless of extension
    • Cannot specify both head and tail simultaneously
  • read_media_file

    • Read a file and return it as a base64-encoded content block with its MIME type
    • Inputs:
      • path (string)
    • Streams the file and returns base64 data with the corresponding MIME type. Image and
      audio files are returned as image/audio content; any other file type is returned as
      an embedded resource (a valid MCP content block for arbitrary binary data)
  • read_multiple_files

    • Read multiple files simultaneously
    • Input: paths (string[])
    • Failed reads won't stop the entire operation
  • write_file

    • Create new file or overwrite existing (exercise caution with this)
    • Inputs:
      • path (string): File location
      • content (string): File content
  • edit_file

    • Make selective edits using advanced pattern matching and formatting
    • Features:
      • Line-based and multi-line content matching
      • Whitespace normalization with indentation preservation
      • Multiple simultaneous edits with correct positioning
      • Indentation style detection and preservation
      • Git-style diff output with context
      • Preview changes with dry run mode
    • Inputs:
      • path (string): File to edit
      • edits (array): List of edit operations
        • oldText (string): Text to search for (can be substring)
        • newText (string): Text to replace with
      • dryRun (boolean): Preview changes without applying (default: false)
    • Returns detailed diff and match information for dry runs, otherwise applies changes
    • Best Practice: Always use dryRun first to preview changes before applying them
  • create_directory

    • Create new directory or ensure it exists
    • Input: path (string)
    • Creates parent directories if needed
    • Succeeds silently if directory exists
  • list_directory

    • List directory contents with [FILE] or [DIR] prefixes
    • Input: path (string)
  • list_directory_with_sizes

    • List directory contents with [FILE] or [DIR] prefixes, including file sizes
    • Inputs:
      • path (string): Directory path to list
      • sortBy (string, optional): Sort entries by "name" or "size" (default: "name")
    • Returns detailed listing with file sizes and summary statistics
    • Shows total files, directories, and combined size
  • move_file

    • Move or rename files and directories
    • Inputs:
      • source (string)
      • destination (string)
    • Fails if destination exists
  • search_files

    • Recursively search for files/directories that match or do not match patterns
    • Inputs:
      • path (string): Starting directory
      • pattern (string): Search pattern
      • excludePatterns (string[]): Exclude any patterns.
    • Glob-style pattern matching
    • Returns full paths to matches
  • directory_tree

    • Get recursive JSON tree structure of directory contents
    • Inputs:
      • path (string): Starting directory
      • excludePatterns (string[]): Exclude any patterns. Glob formats are supported.
    • Returns:
      • JSON array where each entry contains:
        • name (string): File/directory name
        • type ('file'|'directory'): Entry type
        • children (array): Present only for directories
          • Empty array for empty directories
          • Omitted for files
    • Output is formatted with 2-space indentation for readability
  • get_file_info

    • Get detailed file/directory metadata
    • Input: path (string)
    • Returns:
      • Size
      • Creation time
      • Modified time
      • Access time
      • Type (file/directory)
      • Permissions
  • list_allowed_directories

    • List all directories the server is allowed to access
    • No input required
    • Returns:
      • Directories that this server can read/write from

Tool annotations (MCP hints)

This server sets MCP ToolAnnotations
on each tool so clients can:

  • Distinguish read‑only tools from write‑capable tools.
  • Understand which write operations are idempotent (safe to retry with the same arguments).
  • Highlight operations that may be destructive (overwriting or heavily mutating data).
  • Signal that a tool does not reach an open or external world (every filesystem tool sets openWorldHint: false).

The mapping for filesystem tools is:

Tool readOnlyHint idempotentHint destructiveHint Notes
read_text_file true – – Pure read
read_media_file true – – Pure read
read_multiple_files true – – Pure read
list_directory true – – Pure read
list_directory_with_sizes true – – Pure read
directory_tree true – – Pure read
search_files true – – Pure read
get_file_info true – – Pure read
list_allowed_directories true – – Pure read
create_directory false true false Re‑creating the same dir is a no‑op
write_file false true true Overwrites existing files
edit_file false false true Re‑applying edits can fail or double‑apply
move_file false false true Deletes source file

Note: idempotentHint and destructiveHint are meaningful only when readOnlyHint is false, as defined by the MCP spec. Every tool also sets openWorldHint: false — this server only accesses the local filesystem within its allowed directories, never an open or external world.

Usage with Claude Desktop

Add this to your claude_desktop_config.json:

Note: you can provide sandboxed directories to the server by mounting them to /projects. Adding the ro flag will make the directory readonly by the server.

Docker

Note: all directories must be mounted to /projects by default.

json
{
  "mcpServers": {
    "filesystem": {
      "command": "docker",
      "args": [
        "run",
        "-i",
        "--rm",
        "--mount", "type=bind,src=/Users/username/Desktop,dst=/projects/Desktop",
        "--mount", "type=bind,src=/path/to/other/allowed/dir,dst=/projects/other/allowed/dir,ro",
        "--mount", "type=bind,src=/path/to/file.txt,dst=/projects/path/to/file.txt",
        "mcp/filesystem",
        "/projects"
      ]
    }
  }
}

NPX

json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/Users/username/Desktop",
        "/path/to/other/allowed/dir"
      ]
    }
  }
}

On Windows, use cmd /c to launch npx:

json
{
  "mcpServers": {
    "filesystem": {
      "command": "cmd",
      "args": [
        "/c",
        "npx",
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/Users/username/Desktop",
        "/path/to/other/allowed/dir"
      ]
    }
  }
}

Usage with VS Code

For quick installation, click the installation buttons below...

For manual installation, you can configure the MCP server using one of these methods:

Method 1: User Configuration (Recommended)
Add the configuration to your user-level MCP configuration file. Open the Command Palette (Ctrl + Shift + P) and run MCP: Open User Configuration. This will open your user mcp.json file where you can add the server configuration.

Method 2: Workspace Configuration
Alternatively, you can add the configuration to a file called .vscode/mcp.json in your workspace. This will allow you to share the configuration with others.

For more details about MCP configuration in VS Code, see the official VS Code MCP documentation.

You can provide sandboxed directories to the server by mounting them to /projects. Adding the ro flag will make the directory readonly by the server.

Docker

Note: all directories must be mounted to /projects by default.

json
{
  "servers": {
    "filesystem": {
      "command": "docker",
      "args": [
        "run",
        "-i",
        "--rm",
        "--mount", "type=bind,src=${workspaceFolder},dst=/projects/workspace",
        "mcp/filesystem",
        "/projects"
      ]
    }
  }
}

NPX

json
{
  "servers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "${workspaceFolder}"
      ]
    }
  }
}

On Windows, use:

json
{
  "servers": {
    "filesystem": {
      "command": "cmd",
      "args": [
        "/c",
        "npx",
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "${workspaceFolder}"
      ]
    }
  }
}

Build

Docker build:

bash
docker build -t mcp/filesystem -f src/filesystem/Dockerfile .

License

This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.


File: src/fetch/README.md

Fetch MCP Server

A Model Context Protocol server that provides web content fetching capabilities. This server enables LLMs to retrieve and process content from web pages, converting HTML to markdown for easier consumption.

Source: https://github.com/modelcontextprotocol/servers/tree/main/src/fetch

[!CAUTION]
This server can access local/internal IP addresses and may represent a security risk. Exercise caution when using this MCP server to ensure this does not expose any sensitive data.

The fetch tool will truncate the response, but by using the start_index argument, you can specify where to start the content extraction. This lets models read a webpage in chunks, until they find the information they need.

Available Tools

  • fetch - Fetches a URL from the internet and extracts its contents as markdown.
    • url (string, required): URL to fetch
    • max_length (integer, optional): Maximum number of characters to return (default: 5000)
    • start_index (integer, optional): Start content from this character index (default: 0)
    • raw (boolean, optional): Get raw content without markdown conversion (default: false)

Prompts

  • fetch
    • Fetch a URL and extract its contents as markdown
    • Arguments:
      • url (string, required): URL to fetch

Installation

Optionally: Install node.js, this will cause the fetch server to use a different HTML simplifier that is more robust.

When using uv no specific installation is needed. We will
use uvx to directly run mcp-server-fetch.

Using PIP

Alternatively you can install mcp-server-fetch via pip:

text
pip install mcp-server-fetch

After installation, you can run it as a script using:

text
python -m mcp_server_fetch

Configuration

Configure for Claude.app

Add to your Claude settings:

Using uvx

json
{
  "mcpServers": {
    "fetch": {
      "command": "uvx",
      "args": ["mcp-server-fetch"]
    }
  }
}

Using docker

json
{
  "mcpServers": {
    "fetch": {
      "command": "docker",
      "args": ["run", "-i", "--rm", "mcp/fetch"]
    }
  }
}

Using pip installation

json
{
  "mcpServers": {
    "fetch": {
      "command": "python",
      "args": ["-m", "mcp_server_fetch"]
    }
  }
}

Configure for VS Code

For quick installation, use one of the one-click install buttons below...

For manual installation, add the following JSON block to your User Settings (JSON) file in VS Code. You can do this by pressing Ctrl + Shift + P and typing Preferences: Open User Settings (JSON).

Optionally, you can add it to a file called .vscode/mcp.json in your workspace. This will allow you to share the configuration with others.

Note that the mcp key is needed when using the mcp.json file.

Using uvx

json
{
  "mcp": {
    "servers": {
      "fetch": {
        "command": "uvx",
        "args": ["mcp-server-fetch"]
      }
    }
  }
}

Using Docker

json
{
  "mcp": {
    "servers": {
      "fetch": {
        "command": "docker",
        "args": ["run", "-i", "--rm", "mcp/fetch"]
      }
    }
  }
}

Customization - robots.txt

By default, the server will obey a websites robots.txt file if the request came from the model (via a tool), but not if
the request was user initiated (via a prompt). This can be disabled by adding the argument --ignore-robots-txt to the
args list in the configuration.

Customization - User-agent

By default, depending on if the request came from the model (via a tool), or was user initiated (via a prompt), the
server will use either the user-agent

text
ModelContextProtocol/1.0 (Autonomous; +https://github.com/modelcontextprotocol/servers)

or

text
ModelContextProtocol/1.0 (User-Specified; +https://github.com/modelcontextprotocol/servers)

This can be customized by adding the argument --user-agent=YourUserAgent to the args list in the configuration.

Customization - Proxy

The server can be configured to use a proxy by using the --proxy-url argument.

Windows Configuration

If you're experiencing timeout issues on Windows, you may need to set the PYTHONIOENCODING environment variable to ensure proper character encoding:

Windows configuration (uvx)

json
{
  "mcpServers": {
    "fetch": {
      "command": "uvx",
      "args": ["mcp-server-fetch"],
      "env": {
        "PYTHONIOENCODING": "utf-8"
      }
    }
  }
}

Windows configuration (pip)

json
{
  "mcpServers": {
    "fetch": {
      "command": "python",
      "args": ["-m", "mcp_server_fetch"],
      "env": {
        "PYTHONIOENCODING": "utf-8"
      }
    }
  }
}

This addresses character encoding issues that can cause the server to timeout on Windows systems.

Debugging

You can use the MCP inspector to debug the server. For uvx installations:

text
npx @modelcontextprotocol/inspector uvx mcp-server-fetch

Or if you've installed the package in a specific directory or are developing on it:

text
cd path/to/servers/src/fetch
npx @modelcontextprotocol/inspector uv run mcp-server-fetch

Contributing

We encourage contributions to help expand and improve mcp-server-fetch. Whether you want to add new tools, enhance existing functionality, or improve documentation, your input is valuable.

For examples of other MCP servers and implementation patterns, see:
https://github.com/modelcontextprotocol/servers

Pull requests are welcome! Feel free to contribute new ideas, bug fixes, or enhancements to make mcp-server-fetch even more powerful and useful.

License

mcp-server-fetch is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.


File: src/everything/README.md

Everything MCP Server

Architecture
| Project Structure
| Startup Process
| Server Features
| Extension Points
| How It Works

This MCP server attempts to exercise all the features of the MCP protocol. It is not intended to be a useful server, but rather a test server for builders of MCP clients. It implements prompts, tools, resources, sampling, and more to showcase MCP capabilities.

Tools, Resources, Prompts, and Other Features

A complete list of the registered MCP primitives and other protocol features demonstrated can be found in the Server Features document.

Usage with Claude Desktop (uses [stdio Transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#stdio))

Add to your claude_desktop_config.json:

json
{
  "mcpServers": {
    "everything": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-everything"
      ]
    }
  }
}

On Windows, use cmd /c to launch npx:

json
{
  "mcpServers": {
    "everything": {
      "command": "cmd",
      "args": [
        "/c",
        "npx",
        "-y",
        "@modelcontextprotocol/server-everything"
      ]
    }
  }
}

Usage with VS Code

For quick installation, use one of the one-click install buttons below...

For manual installation, you can configure the MCP server using one of these methods:

Method 1: User Configuration (Recommended)
Add the configuration to your user-level MCP configuration file. Open the Command Palette (Ctrl + Shift + P) and run MCP: Open User Configuration. This will open your user mcp.json file where you can add the server configuration.

Method 2: Workspace Configuration
Alternatively, you can add the configuration to a file called .vscode/mcp.json in your workspace. This will allow you to share the configuration with others.

For more details about MCP configuration in VS Code, see the official VS Code MCP documentation.

NPX

json
{
  "servers": {
    "everything": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-everything"]
    }
  }
}

On Windows, use:

json
{
  "servers": {
    "everything": {
      "command": "cmd",
      "args": ["/c", "npx", "-y", "@modelcontextprotocol/server-everything"]
    }
  }
}

Running from source with [HTTP+SSE Transport](https://modelcontextprotocol.io/specification/2024-11-05/basic/transports#http-with-sse) (deprecated as of [2025-03-26](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports))

shell
cd src/everything
npm install
npm run start:sse

Run from source with [Streamable HTTP Transport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http)

shell
cd src/everything
npm install
npm run start:streamableHttp

Running as an installed package

Install

shell
npm install @modelcontextprotocol/server-everything@latest

Run the default (stdio) server

shell
npx @modelcontextprotocol/server-everything

Or specify stdio explicitly

shell
npx @modelcontextprotocol/server-everything stdio

Run the SSE server

shell
npx @modelcontextprotocol/server-everything sse

Run the streamable HTTP server

shell
npx @modelcontextprotocol/server-everything streamableHttp

License

This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.

2. Official Technical Reference & Guides (modelcontextprotocol/docs)

File: README.md

Model Context Protocol documentation

This documentation has moved to modelcontextprotocol/modelcontextprotocol.

Please file issues and pull requests for documentation changes there.


File: docs/tools/debugging.mdx


title: Debugging

Effective debugging is essential when developing MCP servers or integrating them with applications. This guide covers the debugging tools and approaches available in the MCP ecosystem.

This guide is for macOS. Guides for other platforms are coming soon.

Debugging tools overview

MCP provides several tools for debugging at different levels:

  1. MCP Inspector

    • Interactive debugging interface
    • Direct server testing
    • See the Inspector guide for details
  2. Claude Desktop Developer Tools

    • Integration testing
    • Log collection
    • Chrome DevTools integration
  3. Server Logging

    • Custom logging implementations
    • Error tracking
    • Performance monitoring

Debugging in Claude Desktop

Checking server status

The Claude.app interface provides basic server status information:

  1. Click the icon to view:

    • Connected servers
    • Available prompts and resources
  2. Click the icon to view:

    • Tools made available to the model

Viewing logs

Review detailed MCP logs from Claude Desktop:

bash
# Follow logs in real-time
tail -n 20 -F ~/Library/Logs/Claude/mcp*.log

The logs capture:

  • Server connection events
  • Configuration issues
  • Runtime errors
  • Message exchanges

Using Chrome DevTools

Access Chrome's developer tools inside Claude Desktop to investigate client-side errors:

  1. Create a developer_settings.json file with allowDevTools set to true:
bash
echo '{"allowDevTools": true}' > ~/Library/Application\ Support/Claude/developer_settings.json
  1. Open DevTools: Command-Option-Shift-i

Note: You'll see two DevTools windows:

  • Main content window
  • App title bar window

Use the Console panel to inspect client-side errors.

Use the Network panel to inspect:

  • Message payloads
  • Connection timing

Common issues

Working directory

When using MCP servers with Claude Desktop:

  • The working directory for servers launched via claude_desktop_config.json may be undefined (like / on macOS) since Claude Desktop could be started from anywhere
  • Always use absolute paths in your configuration and .env files to ensure reliable operation
  • For testing servers directly via command line, the working directory will be where you run the command

For example in claude_desktop_config.json, use:

json
{
  "command": "npx",
  "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/username/data"]
}

Instead of relative paths like ./data

Environment variables

MCP servers inherit only a subset of environment variables automatically, like USER, HOME, and PATH.

To override the default variables or provide your own, you can specify an env key in claude_desktop_config.json:

json
{
  "myserver": {
    "command": "mcp-server-myapp",
    "env": {
      "MYAPP_API_KEY": "some_key",
    }
  }
}

Server initialization

Common initialization problems:

  1. Path Issues

    • Incorrect server executable path
    • Missing required files
    • Permission problems
    • Try using an absolute path for command
  2. Configuration Errors

    • Invalid JSON syntax
    • Missing required fields
    • Type mismatches
  3. Environment Problems

    • Missing environment variables
    • Incorrect variable values
    • Permission restrictions

Connection problems

When servers fail to connect:

  1. Check Claude Desktop logs
  2. Verify server process is running
  3. Test standalone with Inspector
  4. Verify protocol compatibility

Implementing logging

Server-side logging

When building a server that uses the local stdio transport, all messages logged to stderr (standard error) will be captured by the host application (e.g., Claude Desktop) automatically.

Local MCP servers should not log messages to stdout (standard out), as this will interfere with protocol operation.

For all transports, you can also provide logging to the client by sending a log message notification:

```python server.request_context.session.send_log_message( level="info", data="Server started successfully", ) ``` ```typescript server.sendLoggingMessage({ level: "info", data: "Server started successfully", }); ```

Important events to log:

  • Initialization steps
  • Resource access
  • Tool execution
  • Error conditions
  • Performance metrics

Client-side logging

In client applications:

  1. Enable debug logging
  2. Monitor network traffic
  3. Track message exchanges
  4. Record error states

Debugging workflow

Development cycle

  1. Initial Development

    • Use Inspector for basic testing
    • Implement core functionality
    • Add logging points
  2. Integration Testing

    • Test in Claude Desktop
    • Monitor logs
    • Check error handling

Testing changes

To test changes efficiently:

  • Configuration changes: Restart Claude Desktop
  • Server code changes: Use Command-R to reload
  • Quick iteration: Use Inspector during development

Best practices

Logging strategy

  1. Structured Logging

    • Use consistent formats
    • Include context
    • Add timestamps
    • Track request IDs
  2. Error Handling

    • Log stack traces
    • Include error context
    • Track error patterns
    • Monitor recovery
  3. Performance Tracking

    • Log operation timing
    • Monitor resource usage
    • Track message sizes
    • Measure latency

Security considerations

When debugging:

  1. Sensitive Data

    • Sanitize logs
    • Protect credentials
    • Mask personal information
  2. Access Control

    • Verify permissions
    • Check authentication
    • Monitor access patterns

Getting help

When encountering issues:

  1. First Steps

    • Check server logs
    • Test with Inspector
    • Review configuration
    • Verify environment
  2. Support Channels

    • GitHub issues
    • GitHub discussions
  3. Providing Information

    • Log excerpts
    • Configuration files
    • Steps to reproduce
    • Environment details

Next steps

Learn to use the MCP Inspector

File: docs/tools/inspector.mdx


title: Inspector

The MCP Inspector is an interactive developer tool for testing and debugging MCP servers. While the Debugging Guide covers the Inspector as part of the overall debugging toolkit, this document provides a detailed exploration of the Inspector's features and capabilities.

Getting started

Installation and basic usage

The Inspector runs directly through npx without requiring installation:

bash
npx @modelcontextprotocol/inspector <command>
bash
npx @modelcontextprotocol/inspector <command> <arg1> <arg2>

Inspecting servers from NPM or PyPi

A common way to start server packages from NPM or PyPi.

```bash npx -y @modelcontextprotocol/inspector npx # For example npx -y @modelcontextprotocol/inspector npx server-postgres postgres://127.0.0.1/testdb ``` ```bash npx @modelcontextprotocol/inspector uvx # For example npx @modelcontextprotocol/inspector uvx mcp-server-git --repository ~/code/mcp/servers.git ```

Inspecting locally developed servers

To inspect servers locally developed or downloaded as a repository, the most common
way is:

```bash npx @modelcontextprotocol/inspector node path/to/server/index.js args... ``` ```bash npx @modelcontextprotocol/inspector \ uv \ --directory path/to/server \ run \ package-name \ args... ```

Please carefully read any attached README for the most accurate instructions.

Feature overview

The Inspector provides several features for interacting with your MCP server:

Server connection pane

  • Allows selecting the transport for connecting to the server
  • For local servers, supports customizing the command-line arguments and environment

Resources tab

  • Lists all available resources
  • Shows resource metadata (MIME types, descriptions)
  • Allows resource content inspection
  • Supports subscription testing

Prompts tab

  • Displays available prompt templates
  • Shows prompt arguments and descriptions
  • Enables prompt testing with custom arguments
  • Previews generated messages

Tools tab

  • Lists available tools
  • Shows tool schemas and descriptions
  • Enables tool testing with custom inputs
  • Displays tool execution results

Notifications pane

  • Presents all logs recorded from the server
  • Shows notifications received from the server

Best practices

Development workflow

  1. Start Development

    • Launch Inspector with your server
    • Verify basic connectivity
    • Check capability negotiation
  2. Iterative testing

    • Make server changes
    • Rebuild the server
    • Reconnect the Inspector
    • Test affected features
    • Monitor messages
  3. Test edge cases

    • Invalid inputs
    • Missing prompt arguments
    • Concurrent operations
    • Verify error handling and error responses

Next steps

Check out the MCP Inspector source code
text
<Card
    title="Debugging Guide"
    icon="bug"
    href="/docs/tools/debugging"
>
    Learn about broader debugging strategies
</Card>

File: docs/concepts/architecture.mdx


title: "Core architecture"

The Model Context Protocol (MCP) is built on a flexible, extensible architecture that enables seamless communication between LLM applications and integrations. This document covers the core architectural components and concepts.

Overview

MCP follows a client-server architecture where:

  • Hosts are LLM applications (like Claude Desktop or IDEs) that initiate connections
  • Clients maintain 1:1 connections with servers, inside the host application
  • Servers provide context, tools, and prompts to clients
mermaid
flowchart LR
    subgraph "Host"
        client1[MCP Client]
        client2[MCP Client]
    end
    subgraph "Server Process"
        server1[MCP Server]
    end
    subgraph "Server Process"
        server2[MCP Server]
    end

    client1 <-->|Transport Layer| server1
    client2 <-->|Transport Layer| server2

Core components

Protocol layer

The protocol layer handles message framing, request/response linking, and high-level communication patterns.

```typescript class Protocol { // Handle incoming requests setRequestHandler(schema: T, handler: (request: T, extra: RequestHandlerExtra) => Promise): void
text
// Handle incoming notifications
    setNotificationHandler<T>(schema: T, handler: (notification: T) => Promise<void>): void

    // Send requests and await responses
    request<T>(request: Request, schema: T, options?: RequestOptions): Promise<T>

    // Send one-way notifications
    notification(notification: Notification): Promise<void>
}
```
```python class Session(BaseSession[RequestT, NotificationT, ResultT]): async def send_request( self, request: RequestT, result_type: type[Result] ) -> Result: """ Send request and wait for response. Raises McpError if response contains error. """ # Request handling implementation
text
async def send_notification(
        self,
        notification: NotificationT
    ) -> None:
        """Send one-way notification that doesn't expect response."""
        # Notification handling implementation

    async def _received_request(
        self,
        responder: RequestResponder[ReceiveRequestT, ResultT]
    ) -> None:
        """Handle incoming request from other side."""
        # Request handling implementation

    async def _received_notification(
        self,
        notification: ReceiveNotificationT
    ) -> None:
        """Handle incoming notification from other side."""
        # Notification handling implementation
```

Key classes include:

  • Protocol
  • Client
  • Server

Transport layer

The transport layer handles the actual communication between clients and servers. MCP supports multiple transport mechanisms:

  1. Stdio transport

    • Uses standard input/output for communication
    • Ideal for local processes
  2. HTTP with SSE transport

    • Uses Server-Sent Events for server-to-client messages
    • HTTP POST for client-to-server messages

All transports use JSON-RPC 2.0 to exchange messages. See the specification for detailed information about the Model Context Protocol message format.

Message types

MCP has these main types of messages:

  1. Requests expect a response from the other side:

    typescript
    interface Request {
      method: string;
      params?: { ... };
    }
  2. Results are successful responses to requests:

    typescript
    interface Result {
      [key: string]: unknown;
    }
  3. Errors indicate that a request failed:

    typescript
    interface Error {
      code: number;
      message: string;
      data?: unknown;
    }
  4. Notifications are one-way messages that don't expect a response:

    typescript
    interface Notification {
      method: string;
      params?: { ... };
    }

Connection lifecycle

1. Initialization

mermaid
sequenceDiagram
    participant Client
    participant Server

    Client->>Server: initialize request
    Server->>Client: initialize response
    Client->>Server: initialized notification

    Note over Client,Server: Connection ready for use
  1. Client sends initialize request with protocol version and capabilities
  2. Server responds with its protocol version and capabilities
  3. Client sends initialized notification as acknowledgment
  4. Normal message exchange begins

2. Message exchange

After initialization, the following patterns are supported:

  • Request-Response: Client or server sends requests, the other responds
  • Notifications: Either party sends one-way messages

3. Termination

Either party can terminate the connection:

  • Clean shutdown via close()
  • Transport disconnection
  • Error conditions

Error handling

MCP defines these standard error codes:

typescript
enum ErrorCode {
  // Standard JSON-RPC error codes
  ParseError = -32700,
  InvalidRequest = -32600,
  MethodNotFound = -32601,
  InvalidParams = -32602,
  InternalError = -32603
}

SDKs and applications can define their own error codes above -32000.

Errors are propagated through:

  • Error responses to requests
  • Error events on transports
  • Protocol-level error handlers

Implementation example

Here's a basic example of implementing an MCP server:

```typescript import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
text
const server = new Server({
  name: "example-server",
  version: "1.0.0"
}, {
  capabilities: {
    resources: {}
  }
});

// Handle requests
server.setRequestHandler(ListResourcesRequestSchema, async () => {
  return {
    resources: [
      {
        uri: "example://resource",
        name: "Example Resource"
      }
    ]
  };
});

// Connect transport
const transport = new StdioServerTransport();
await server.connect(transport);
```
```python import asyncio import mcp.types as types from mcp.server import Server from mcp.server.stdio import stdio_server
text
app = Server("example-server")

@app.list_resources()
async def list_resources() -> list[types.Resource]:
    return [
        types.Resource(
            uri="example://resource",
            name="Example Resource"
        )
    ]

async def main():
    async with stdio_server() as streams:
        await app.run(
            streams[0],
            streams[1],
            app.create_initialization_options()
        )

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

Best practices

Transport selection

  1. Local communication

    • Use stdio transport for local processes
    • Efficient for same-machine communication
    • Simple process management
  2. Remote communication

    • Use SSE for scenarios requiring HTTP compatibility
    • Consider security implications including authentication and authorization

Message handling

  1. Request processing

    • Validate inputs thoroughly
    • Use type-safe schemas
    • Handle errors gracefully
    • Implement timeouts
  2. Progress reporting

    • Use progress tokens for long operations
    • Report progress incrementally
    • Include total progress when known
  3. Error management

    • Use appropriate error codes
    • Include helpful error messages
    • Clean up resources on errors

Security considerations

  1. Transport security

    • Use TLS for remote connections
    • Validate connection origins
    • Implement authentication when needed
  2. Message validation

    • Validate all incoming messages
    • Sanitize inputs
    • Check message size limits
    • Verify JSON-RPC format
  3. Resource protection

    • Implement access controls
    • Validate resource paths
    • Monitor resource usage
    • Rate limit requests
  4. Error handling

    • Don't leak sensitive information
    • Log security-relevant errors
    • Implement proper cleanup
    • Handle DoS scenarios

Debugging and monitoring

  1. Logging

    • Log protocol events
    • Track message flow
    • Monitor performance
    • Record errors
  2. Diagnostics

    • Implement health checks
    • Monitor connection state
    • Track resource usage
    • Profile performance
  3. Testing

    • Test different transports
    • Verify error handling
    • Check edge cases
    • Load test servers

File: docs/concepts/prompts.mdx


title: "Prompts"

Prompts enable servers to define reusable prompt templates and workflows that clients can easily surface to users and LLMs. They provide a powerful way to standardize and share common LLM interactions.

Prompts are designed to be **user-controlled**, meaning they are exposed from servers to clients with the intention of the user being able to explicitly select them for use.

Overview

Prompts in MCP are predefined templates that can:

  • Accept dynamic arguments
  • Include context from resources
  • Chain multiple interactions
  • Guide specific workflows
  • Surface as UI elements (like slash commands)

Prompt structure

Each prompt is defined with:

typescript
{
  name: string;              // Unique identifier for the prompt
  description?: string;      // Human-readable description
  arguments?: [              // Optional list of arguments
    {
      name: string;          // Argument identifier
      description?: string;  // Argument description
      required?: boolean;    // Whether argument is required
    }
  ]
}

Discovering prompts

Clients can discover available prompts through the prompts/list endpoint:

typescript
// Request
{
  method: "prompts/list"
}

// Response
{
  prompts: [
    {
      name: "analyze-code",
      arguments: [
        {
          name: "language",
          required: true
        }
      ]
    }
  ]
}

Using prompts

To use a prompt, clients make a prompts/get request:

typescript
// Request
{
  method: "prompts/get",
  params: {
    name: "analyze-code",
    arguments: {
      language: "python"
    }
  }
}

// Response
{
  messages: [
    {
      role: "user",
      content: {
        type: "text",
        text: "Please analyze the following Python code for potential improvements:\n\n```python\ndef calculate_sum(numbers):\n    total = 0\n    for num in numbers:\n        total = total + num\n    return total\n\nresult = calculate_sum([1, 2, 3, 4, 5])\nprint(result)\n```"
      }
    }
  ]
}

Dynamic prompts

Prompts can be dynamic and include:

Embedded resource context

json
{
  "name": "analyze-project",
  "description": "Analyze project logs and code",
  "arguments": [
    {
      "name": "timeframe",
      "description": "Time period to analyze logs",
      "required": true
    },
    {
      "name": "fileUri",
      "description": "URI of code file to review",
      "required": true
    }
  ]
}

When handling the prompts/get request:

json
{
  "messages": [
    {
      "role": "user",
      "content": {
        "type": "text",
        "text": "Analyze these system logs and the code file for any issues:"
      }
    },
    {
      "role": "user",
      "content": {
        "type": "resource",
        "resource": {
          "uri": "logs://recent?timeframe=1h",
          "text": "[2024-03-14 15:32:11] ERROR: Connection timeout in network.py:127\n[2024-03-14 15:32:15] WARN: Retrying connection (attempt 2/3)\n[2024-03-14 15:32:20] ERROR: Max retries exceeded",
          "mimeType": "text/plain"
        }
      }
    },
    {
      "role": "user",
      "content": {
        "type": "resource",
        "resource": {
          "uri": "file:///path/to/code.py",
          "text": "def connect_to_service(timeout=30):\n    retries = 3\n    for attempt in range(retries):\n        try:\n            return establish_connection(timeout)\n        except TimeoutError:\n            if attempt == retries - 1:\n                raise\n            time.sleep(5)\n\ndef establish_connection(timeout):\n    # Connection implementation\n    pass",
          "mimeType": "text/x-python"
        }
      }
    }
  ]
}

Multi-step workflows

typescript
const debugWorkflow = {
  name: "debug-error",
  async getMessages(error: string) {
    return [
      {
        role: "user",
        content: {
          type: "text",
          text: `Here's an error I'm seeing: ${error}`
        }
      },
      {
        role: "assistant",
        content: {
          type: "text",
          text: "I'll help analyze this error. What have you tried so far?"
        }
      },
      {
        role: "user",
        content: {
          type: "text",
          text: "I've tried restarting the service, but the error persists."
        }
      }
    ];
  }
};

Example implementation

Here's a complete example of implementing prompts in an MCP server:

``` /* Detailed source-code truncated for AI context efficiency. */ ``` ``` /* Detailed source-code truncated for AI context efficiency. */ ```

Best practices

When implementing prompts:

  1. Use clear, descriptive prompt names
  2. Provide detailed descriptions for prompts and arguments
  3. Validate all required arguments
  4. Handle missing arguments gracefully
  5. Consider versioning for prompt templates
  6. Cache dynamic content when appropriate
  7. Implement error handling
  8. Document expected argument formats
  9. Consider prompt composability
  10. Test prompts with various inputs

UI integration

Prompts can be surfaced in client UIs as:

  • Slash commands
  • Quick actions
  • Context menu items
  • Command palette entries
  • Guided workflows
  • Interactive forms

Updates and changes

Servers can notify clients about prompt changes:

  1. Server capability: prompts.listChanged
  2. Notification: notifications/prompts/list_changed
  3. Client re-fetches prompt list

Security considerations

When implementing prompts:

  • Validate all arguments
  • Sanitize user input
  • Consider rate limiting
  • Implement access controls
  • Audit prompt usage
  • Handle sensitive data appropriately
  • Validate generated content
  • Implement timeouts
  • Consider prompt injection risks
  • Document security requirements

File: docs/concepts/resources.mdx


title: "Resources"

Resources are a core primitive in the Model Context Protocol (MCP) that allow servers to expose data and content that can be read by clients and used as context for LLM interactions.

Resources are designed to be **application-controlled**, meaning that the client application can decide how and when they should be used. Different MCP clients may handle resources differently. For example: - Claude Desktop currently requires users to explicitly select resources before they can be used - Other clients might automatically select resources based on heuristics - Some implementations may even allow the AI model itself to determine which resources to use

Server authors should be prepared to handle any of these interaction patterns when implementing resource support. In order to expose data to models automatically, server authors should use a model-controlled primitive such as Tools.

Overview

Resources represent any kind of data that an MCP server wants to make available to clients. This can include:

  • File contents
  • Database records
  • API responses
  • Live system data
  • Screenshots and images
  • Log files
  • And more

Each resource is identified by a unique URI and can contain either text or binary data.

Resource URIs

Resources are identified using URIs that follow this format:

text
[protocol]://[host]/[path]

For example:

  • file:///home/user/documents/report.pdf
  • postgres://database/customers/schema
  • screen://localhost/display1

The protocol and path structure is defined by the MCP server implementation. Servers can define their own custom URI schemes.

Resource types

Resources can contain two types of content:

Text resources

Text resources contain UTF-8 encoded text data. These are suitable for:

  • Source code
  • Configuration files
  • Log files
  • JSON/XML data
  • Plain text

Binary resources

Binary resources contain raw binary data encoded in base64. These are suitable for:

  • Images
  • PDFs
  • Audio files
  • Video files
  • Other non-text formats

Resource discovery

Clients can discover available resources through two main methods:

Direct resources

Servers expose a list of concrete resources via the resources/list endpoint. Each resource includes:

typescript
{
  uri: string;           // Unique identifier for the resource
  name: string;          // Human-readable name
  description?: string;  // Optional description
  mimeType?: string;     // Optional MIME type
}

Resource templates

For dynamic resources, servers can expose URI templates that clients can use to construct valid resource URIs:

typescript
{
  uriTemplate: string;   // URI template following RFC 6570
  name: string;          // Human-readable name for this type
  description?: string;  // Optional description
  mimeType?: string;     // Optional MIME type for all matching resources
}

Reading resources

To read a resource, clients make a resources/read request with the resource URI.

The server responds with a list of resource contents:

typescript
{
  contents: [
    {
      uri: string;        // The URI of the resource
      mimeType?: string;  // Optional MIME type

      // One of:
      text?: string;      // For text resources
      blob?: string;      // For binary resources (base64 encoded)
    }
  ]
}
Servers may return multiple resources in response to one `resources/read` request. This could be used, for example, to return a list of files inside a directory when the directory is read.

Resource updates

MCP supports real-time updates for resources through two mechanisms:

List changes

Servers can notify clients when their list of available resources changes via the notifications/resources/list_changed notification.

Content changes

Clients can subscribe to updates for specific resources:

  1. Client sends resources/subscribe with resource URI
  2. Server sends notifications/resources/updated when the resource changes
  3. Client can fetch latest content with resources/read
  4. Client can unsubscribe with resources/unsubscribe

Example implementation

Here's a simple example of implementing resource support in an MCP server:

```typescript const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: { resources: {} } });
text
// List available resources
server.setRequestHandler(ListResourcesRequestSchema, async () => {
  return {
    resources: [
      {
        uri: "file:///logs/app.log",
        name: "Application Logs",
        mimeType: "text/plain"
      }
    ]
  };
});

// Read resource contents
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
  const uri = request.params.uri;

  if (uri === "file:///logs/app.log") {
    const logContents = await readLogFile();
    return {
      contents: [
        {
          uri,
          mimeType: "text/plain",
          text: logContents
        }
      ]
    };
  }

  throw new Error("Resource not found");
});
```
```python app = Server("example-server")
text
@app.list_resources()
async def list_resources() -> list[types.Resource]:
    return [
        types.Resource(
            uri="file:///logs/app.log",
            name="Application Logs",
            mimeType="text/plain"
        )
    ]

@app.read_resource()
async def read_resource(uri: AnyUrl) -> str:
    if str(uri) == "file:///logs/app.log":
        log_contents = await read_log_file()
        return log_contents

    raise ValueError("Resource not found")

# Start server
async with stdio_server() as streams:
    await app.run(
        streams[0],
        streams[1],
        app.create_initialization_options()
    )
```

Best practices

When implementing resource support:

  1. Use clear, descriptive resource names and URIs
  2. Include helpful descriptions to guide LLM understanding
  3. Set appropriate MIME types when known
  4. Implement resource templates for dynamic content
  5. Use subscriptions for frequently changing resources
  6. Handle errors gracefully with clear error messages
  7. Consider pagination for large resource lists
  8. Cache resource contents when appropriate
  9. Validate URIs before processing
  10. Document your custom URI schemes

Security considerations

When exposing resources:

  • Validate all resource URIs
  • Implement appropriate access controls
  • Sanitize file paths to prevent directory traversal
  • Be cautious with binary data handling
  • Consider rate limiting for resource reads
  • Audit resource access
  • Encrypt sensitive data in transit
  • Validate MIME types
  • Implement timeouts for long-running reads
  • Handle resource cleanup appropriately

File: docs/concepts/roots.mdx


title: "Roots"

Roots are a concept in MCP that define the boundaries where servers can operate. They provide a way for clients to inform servers about relevant resources and their locations.

What are Roots?

A root is a URI that a client suggests a server should focus on. When a client connects to a server, it declares which roots the server should work with. While primarily used for filesystem paths, roots can be any valid URI including HTTP URLs.

For example, roots could be:

text
file:///home/user/projects/myapp
https://api.example.com/v1

Why Use Roots?

Roots serve several important purposes:

  1. Guidance: They inform servers about relevant resources and locations
  2. Clarity: Roots make it clear which resources are part of your workspace
  3. Organization: Multiple roots let you work with different resources simultaneously

How Roots Work

When a client supports roots, it:

  1. Declares the roots capability during connection
  2. Provides a list of suggested roots to the server
  3. Notifies the server when roots change (if supported)

While roots are informational and not strictly enforcing, servers should:

  1. Respect the provided roots
  2. Use root URIs to locate and access resources
  3. Prioritize operations within root boundaries

Common Use Cases

Roots are commonly used to define:

  • Project directories
  • Repository locations
  • API endpoints
  • Configuration locations
  • Resource boundaries

Best Practices

When working with roots:

  1. Only suggest necessary resources
  2. Use clear, descriptive names for roots
  3. Monitor root accessibility
  4. Handle root changes gracefully

Example

Here's how a typical MCP client might expose roots:

json
{
  "roots": [
    {
      "uri": "file:///home/user/projects/frontend",
      "name": "Frontend Repository"
    },
    {
      "uri": "https://api.example.com/v1",
      "name": "API Endpoint"
    }
  ]
}

This configuration suggests the server focus on both a local repository and an API endpoint while keeping them logically separated.


File: docs/concepts/sampling.mdx


title: "Sampling"

Sampling is a powerful MCP feature that allows servers to request LLM completions through the client, enabling sophisticated agentic behaviors while maintaining security and privacy.

This feature of MCP is not yet supported in the Claude Desktop client.

How sampling works

The sampling flow follows these steps:

  1. Server sends a sampling/createMessage request to the client
  2. Client reviews the request and can modify it
  3. Client samples from an LLM
  4. Client reviews the completion
  5. Client returns the result to the server

This human-in-the-loop design ensures users maintain control over what the LLM sees and generates.

Message format

Sampling requests use a standardized message format:

typescript
{
  messages: [
    {
      role: "user" | "assistant",
      content: {
        type: "text" | "image",

        // For text:
        text?: string,

        // For images:
        data?: string,             // base64 encoded
        mimeType?: string
      }
    }
  ],
  modelPreferences?: {
    hints?: [{
      name?: string                // Suggested model name/family
    }],
    costPriority?: number,         // 0-1, importance of minimizing cost
    speedPriority?: number,        // 0-1, importance of low latency
    intelligencePriority?: number  // 0-1, importance of capabilities
  },
  systemPrompt?: string,
  includeContext?: "none" | "thisServer" | "allServers",
  temperature?: number,
  maxTokens: number,
  stopSequences?: string[],
  metadata?: Record<string, unknown>
}

Request parameters

Messages

The messages array contains the conversation history to send to the LLM. Each message has:

  • role: Either "user" or "assistant"
  • content: The message content, which can be:
    • Text content with a text field
    • Image content with data (base64) and mimeType fields

Model preferences

The modelPreferences object allows servers to specify their model selection preferences:

  • hints: Array of model name suggestions that clients can use to select an appropriate model:

    • name: String that can match full or partial model names (e.g. "claude-3", "sonnet")
    • Clients may map hints to equivalent models from different providers
    • Multiple hints are evaluated in preference order
  • Priority values (0-1 normalized):

    • costPriority: Importance of minimizing costs
    • speedPriority: Importance of low latency response
    • intelligencePriority: Importance of advanced model capabilities

Clients make the final model selection based on these preferences and their available models.

System prompt

An optional systemPrompt field allows servers to request a specific system prompt. The client may modify or ignore this.

Context inclusion

The includeContext parameter specifies what MCP context to include:

  • "none": No additional context
  • "thisServer": Include context from the requesting server
  • "allServers": Include context from all connected MCP servers

The client controls what context is actually included.

Sampling parameters

Fine-tune the LLM sampling with:

  • temperature: Controls randomness (0.0 to 1.0)
  • maxTokens: Maximum tokens to generate
  • stopSequences: Array of sequences that stop generation
  • metadata: Additional provider-specific parameters

Response format

The client returns a completion result:

typescript
{
  model: string,  // Name of the model used
  stopReason?: "endTurn" | "stopSequence" | "maxTokens" | string,
  role: "user" | "assistant",
  content: {
    type: "text" | "image",
    text?: string,
    data?: string,
    mimeType?: string
  }
}

Example request

Here's an example of requesting sampling from a client:

json
{
  "method": "sampling/createMessage",
  "params": {
    "messages": [
      {
        "role": "user",
        "content": {
          "type": "text",
          "text": "What files are in the current directory?"
        }
      }
    ],
    "systemPrompt": "You are a helpful file system assistant.",
    "includeContext": "thisServer",
    "maxTokens": 100
  }
}

Best practices

When implementing sampling:

  1. Always provide clear, well-structured prompts
  2. Handle both text and image content appropriately
  3. Set reasonable token limits
  4. Include relevant context through includeContext
  5. Validate responses before using them
  6. Handle errors gracefully
  7. Consider rate limiting sampling requests
  8. Document expected sampling behavior
  9. Test with various model parameters
  10. Monitor sampling costs

Human in the loop controls

Sampling is designed with human oversight in mind:

For prompts

  • Clients should show users the proposed prompt
  • Users should be able to modify or reject prompts
  • System prompts can be filtered or modified
  • Context inclusion is controlled by the client

For completions

  • Clients should show users the completion
  • Users should be able to modify or reject completions
  • Clients can filter or modify completions
  • Users control which model is used

Security considerations

When implementing sampling:

  • Validate all message content
  • Sanitize sensitive information
  • Implement appropriate rate limits
  • Monitor sampling usage
  • Encrypt data in transit
  • Handle user data privacy
  • Audit sampling requests
  • Control cost exposure
  • Implement timeouts
  • Handle model errors gracefully

Common patterns

Agentic workflows

Sampling enables agentic patterns like:

  • Reading and analyzing resources
  • Making decisions based on context
  • Generating structured data
  • Handling multi-step tasks
  • Providing interactive assistance

Context management

Best practices for context:

  • Request minimal necessary context
  • Structure context clearly
  • Handle context size limits
  • Update context as needed
  • Clean up stale context

Error handling

Robust error handling should:

  • Catch sampling failures
  • Handle timeout errors
  • Manage rate limits
  • Validate responses
  • Provide fallback behaviors
  • Log errors appropriately

Limitations

Be aware of these limitations:

  • Sampling depends on client capabilities
  • Users control sampling behavior
  • Context size has limits
  • Rate limits may apply
  • Costs should be considered
  • Model availability varies
  • Response times vary
  • Not all content types supported

File: docs/concepts/tools.mdx


title: "Tools"

Tools are a powerful primitive in the Model Context Protocol (MCP) that enable servers to expose executable functionality to clients. Through tools, LLMs can interact with external systems, perform computations, and take actions in the real world.

Tools are designed to be **model-controlled**, meaning that tools are exposed from servers to clients with the intention of the AI model being able to automatically invoke them (with a human in the loop to grant approval).

Overview

Tools in MCP allow servers to expose executable functions that can be invoked by clients and used by LLMs to perform actions. Key aspects of tools include:

  • Discovery: Clients can list available tools through the tools/list endpoint
  • Invocation: Tools are called using the tools/call endpoint, where servers perform the requested operation and return results
  • Flexibility: Tools can range from simple calculations to complex API interactions

Like resources, tools are identified by unique names and can include descriptions to guide their usage. However, unlike resources, tools represent dynamic operations that can modify state or interact with external systems.

Tool definition structure

Each tool is defined with the following structure:

typescript
{
  name: string;          // Unique identifier for the tool
  description?: string;  // Human-readable description
  inputSchema: {         // JSON Schema for the tool's parameters
    type: "object",
    properties: { ... }  // Tool-specific parameters
  }
}

Implementing tools

Here's an example of implementing a basic tool in an MCP server:

```typescript const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: { tools: {} } });
text
// Define available tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [{
      name: "calculate_sum",
      inputSchema: {
        type: "object",
        properties: {
          a: { type: "number" },
          b: { type: "number" }
        },
        required: ["a", "b"]
      }
    }]
  };
});

// Handle tool execution
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === "calculate_sum") {
    const { a, b } = request.params.arguments;
    return {
      content: [
        {
          type: "text",
          text: String(a + b)
        }
      ]
    };
  }
  throw new Error("Tool not found");
});
```
```python app = Server("example-server")
text
@app.list_tools()
async def list_tools() -> list[types.Tool]:
    return [
        types.Tool(
            name="calculate_sum",
            description="Add two numbers together",
            inputSchema={
                "type": "object",
                "properties": {
                    "a": {"type": "number"},
                    "b": {"type": "number"}
                },
                "required": ["a", "b"]
            }
        )
    ]

@app.call_tool()
async def call_tool(
    name: str,
    arguments: dict
) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
    if name == "calculate_sum":
        a = arguments["a"]
        b = arguments["b"]
        result = a + b
        return [types.TextContent(type="text", text=str(result))]
    raise ValueError(f"Tool not found: {name}")
```

Example tool patterns

Here are some examples of types of tools that a server could provide:

System operations

Tools that interact with the local system:

typescript
{
  name: "execute_command",
  inputSchema: {
    type: "object",
    properties: {
      command: { type: "string" },
      args: { type: "array", items: { type: "string" } }
    }
  }
}

API integrations

Tools that wrap external APIs:

typescript
{
  name: "github_create_issue",
  inputSchema: {
    type: "object",
    properties: {
      title: { type: "string" },
      body: { type: "string" },
      labels: { type: "array", items: { type: "string" } }
    }
  }
}

Data processing

Tools that transform or analyze data:

typescript
{
  name: "analyze_csv",
  inputSchema: {
    type: "object",
    properties: {
      filepath: { type: "string" },
      operations: {
        type: "array",
        items: {
          enum: ["sum", "average", "count"]
        }
      }
    }
  }
}

Best practices

When implementing tools:

  1. Provide clear, descriptive names and descriptions
  2. Use detailed JSON Schema definitions for parameters
  3. Include examples in tool descriptions to demonstrate how the model should use them
  4. Implement proper error handling and validation
  5. Use progress reporting for long operations
  6. Keep tool operations focused and atomic
  7. Document expected return value structures
  8. Implement proper timeouts
  9. Consider rate limiting for resource-intensive operations
  10. Log tool usage for debugging and monitoring

Security considerations

When exposing tools:

Input validation

  • Validate all parameters against the schema
  • Sanitize file paths and system commands
  • Validate URLs and external identifiers
  • Check parameter sizes and ranges
  • Prevent command injection

Access control

  • Implement authentication where needed
  • Use appropriate authorization checks
  • Audit tool usage
  • Rate limit requests
  • Monitor for abuse

Error handling

  • Don't expose internal errors to clients
  • Log security-relevant errors
  • Handle timeouts appropriately
  • Clean up resources after errors
  • Validate return values

Tool discovery and updates

MCP supports dynamic tool discovery:

  1. Clients can list available tools at any time
  2. Servers can notify clients when tools change using notifications/tools/list_changed
  3. Tools can be added or removed during runtime
  4. Tool definitions can be updated (though this should be done carefully)

Error handling

Tool errors should be reported within the result object, not as MCP protocol-level errors. This allows the LLM to see and potentially handle the error. When a tool encounters an error:

  1. Set isError to true in the result
  2. Include error details in the content array

Here's an example of proper error handling for tools:

```typescript try { // Tool operation const result = performOperation(); return { content: [ { type: "text", text: `Operation successful: ${result}` } ] }; } catch (error) { return { isError: true, content: [ { type: "text", text: `Error: ${error.message}` } ] }; } ``` ```python try: # Tool operation result = perform_operation() return types.CallToolResult( content=[ types.TextContent( type="text", text=f"Operation successful: {result}" ) ] ) except Exception as error: return types.CallToolResult( isError=True, content=[ types.TextContent( type="text", text=f"Error: {str(error)}" ) ] ) ```

This approach allows the LLM to see that an error occurred and potentially take corrective action or request human intervention.

Testing tools

A comprehensive testing strategy for MCP tools should cover:

  • Functional testing: Verify tools execute correctly with valid inputs and handle invalid inputs appropriately
  • Integration testing: Test tool interaction with external systems using both real and mocked dependencies
  • Security testing: Validate authentication, authorization, input sanitization, and rate limiting
  • Performance testing: Check behavior under load, timeout handling, and resource cleanup
  • Error handling: Ensure tools properly report errors through the MCP protocol and clean up resources

File: docs/concepts/transports.mdx


title: "Transports"

Transports in the Model Context Protocol (MCP) provide the foundation for communication between clients and servers. A transport handles the underlying mechanics of how messages are sent and received.

Message Format

MCP uses JSON-RPC 2.0 as its wire format. The transport layer is responsible for converting MCP protocol messages into JSON-RPC format for transmission and converting received JSON-RPC messages back into MCP protocol messages.

There are three types of JSON-RPC messages used:

Requests

typescript
{
  jsonrpc: "2.0",
  id: number | string,
  method: string,
  params?: object
}

Responses

typescript
{
  jsonrpc: "2.0",
  id: number | string,
  result?: object,
  error?: {
    code: number,
    message: string,
    data?: unknown
  }
}

Notifications

typescript
{
  jsonrpc: "2.0",
  method: string,
  params?: object
}

Built-in Transport Types

MCP includes two standard transport implementations:

Standard Input/Output (stdio)

The stdio transport enables communication through standard input and output streams. This is particularly useful for local integrations and command-line tools.

Use stdio when:

  • Building command-line tools
  • Implementing local integrations
  • Needing simple process communication
  • Working with shell scripts
```typescript const server = new Server({ name: "example-server", version: "1.0.0" }, { capabilities: {} });
text
const transport = new StdioServerTransport();
await server.connect(transport);
```
```typescript const client = new Client({ name: "example-client", version: "1.0.0" }, { capabilities: {} });
text
const transport = new StdioClientTransport({
  command: "./server",
  args: ["--option", "value"]
});
await client.connect(transport);
```
```python app = Server("example-server")
text
async with stdio_server() as streams:
    await app.run(
        streams[0],
        streams[1],
        app.create_initialization_options()
    )
```
```python params = StdioServerParameters( command="./server", args=["--option", "value"] )
text
async with stdio_client(params) as streams:
    async with ClientSession(streams[0], streams[1]) as session:
        await session.initialize()
```

Server-Sent Events (SSE)

SSE transport enables server-to-client streaming with HTTP POST requests for client-to-server communication.

Use SSE when:

  • Only server-to-client streaming is needed
  • Working with restricted networks
  • Implementing simple updates
```typescript import express from "express";
text
const app = express();

const server = new Server({
  name: "example-server",
  version: "1.0.0"
}, {
  capabilities: {}
});

let transport: SSEServerTransport | null = null;

app.get("/sse", (req, res) => {
  transport = new SSEServerTransport("/messages", res);
  server.connect(transport);
});

app.post("/messages", (req, res) => {
  if (transport) {
    transport.handlePostMessage(req, res);
  }
});

app.listen(3000);
```
```typescript const client = new Client({ name: "example-client", version: "1.0.0" }, { capabilities: {} });
text
const transport = new SSEClientTransport(
  new URL("http://localhost:3000/sse")
);
await client.connect(transport);
```
```python from mcp.server.sse import SseServerTransport from starlette.applications import Starlette from starlette.routing import Route
text
app = Server("example-server")
sse = SseServerTransport("/messages")

async def handle_sse(scope, receive, send):
    async with sse.connect_sse(scope, receive, send) as streams:
        await app.run(streams[0], streams[1], app.create_initialization_options())

async def handle_messages(scope, receive, send):
    await sse.handle_post_message(scope, receive, send)

starlette_app = Starlette(
    routes=[
        Route("/sse", endpoint=handle_sse),
        Route("/messages", endpoint=handle_messages, methods=["POST"]),
    ]
)
```
```python async with sse_client("http://localhost:8000/sse") as streams: async with ClientSession(streams[0], streams[1]) as session: await session.initialize() ```

Custom Transports

MCP makes it easy to implement custom transports for specific needs. Any transport implementation just needs to conform to the Transport interface:

You can implement custom transports for:

  • Custom network protocols
  • Specialized communication channels
  • Integration with existing systems
  • Performance optimization
```typescript interface Transport { // Start processing messages start(): Promise;
text
// Send a JSON-RPC message
  send(message: JSONRPCMessage): Promise<void>;

  // Close the connection
  close(): Promise<void>;

  // Callbacks
  onclose?: () => void;
  onerror?: (error: Error) => void;
  onmessage?: (message: JSONRPCMessage) => void;
}
```
Note that while MCP Servers are often implemented with asyncio, we recommend implementing low-level interfaces like transports with `anyio` for wider compatibility. ```python @contextmanager async def create_transport( read_stream: MemoryObjectReceiveStream[JSONRPCMessage | Exception], write_stream: MemoryObjectSendStream[JSONRPCMessage] ): """ Transport interface for MCP.
text
Args:
        read_stream: Stream to read incoming messages from
        write_stream: Stream to write outgoing messages to
    """
    async with anyio.create_task_group() as tg:
        try:
            # Start processing messages
            tg.start_soon(lambda: process_messages(read_stream))

            # Send messages
            async with write_stream:
                yield write_stream

        except Exception as exc:
            # Handle errors
            raise exc
        finally:
            # Clean up
            tg.cancel_scope.cancel()
            await write_stream.aclose()
            await read_stream.aclose()
```

Error Handling

Transport implementations should handle various error scenarios:

  1. Connection errors
  2. Message parsing errors
  3. Protocol errors
  4. Network timeouts
  5. Resource cleanup

Example error handling:

```typescript class ExampleTransport implements Transport { async start() { try { // Connection logic } catch (error) { this.onerror?.(new Error(`Failed to connect: ${error}`)); throw error; } }
text
async send(message: JSONRPCMessage) {
    try {
      // Sending logic
    } catch (error) {
      this.onerror?.(new Error(`Failed to send message: ${error}`));
      throw error;
    }
  }
}
```
Note that while MCP Servers are often implemented with asyncio, we recommend implementing low-level interfaces like transports with `anyio` for wider compatibility. ```python @contextmanager async def example_transport(scope: Scope, receive: Receive, send: Send): try: # Create streams for bidirectional communication read_stream_writer, read_stream = anyio.create_memory_object_stream(0) write_stream, write_stream_reader = anyio.create_memory_object_stream(0)
text
async def message_handler():
            try:
                async with read_stream_writer:
                    # Message handling logic
                    pass
            except Exception as exc:
                logger.error(f"Failed to handle message: {exc}")
                raise exc

        async with anyio.create_task_group() as tg:
            tg.start_soon(message_handler)
            try:
                # Yield streams for communication
                yield read_stream, write_stream
            except Exception as exc:
                logger.error(f"Transport error: {exc}")
                raise exc
            finally:
                tg.cancel_scope.cancel()
                await write_stream.aclose()
                await read_stream.aclose()
    except Exception as exc:
        logger.error(f"Failed to initialize transport: {exc}")
        raise exc
```

Best Practices

When implementing or using MCP transport:

  1. Handle connection lifecycle properly
  2. Implement proper error handling
  3. Clean up resources on connection close
  4. Use appropriate timeouts
  5. Validate messages before sending
  6. Log transport events for debugging
  7. Implement reconnection logic when appropriate
  8. Handle backpressure in message queues
  9. Monitor connection health
  10. Implement proper security measures

Security Considerations

When implementing transport:

Authentication and Authorization

  • Implement proper authentication mechanisms
  • Validate client credentials
  • Use secure token handling
  • Implement authorization checks

Data Security

  • Use TLS for network transport
  • Encrypt sensitive data
  • Validate message integrity
  • Implement message size limits
  • Sanitize input data

Network Security

  • Implement rate limiting
  • Use appropriate timeouts
  • Handle denial of service scenarios
  • Monitor for unusual patterns
  • Implement proper firewall rules

Debugging Transport

Tips for debugging transport issues:

  1. Enable debug logging
  2. Monitor message flow
  3. Check connection states
  4. Validate message formats
  5. Test error scenarios
  6. Use network analysis tools
  7. Implement health checks
  8. Monitor resource usage
  9. Test edge cases
  10. Use proper error tracking